2012-08-26 44 views
0

我正在學習新的東西,檢查數據庫中是否使用了用戶名,並根據我在網上找到的教程創建了一些代碼。我理解這個邏輯,但不知道我是否以正確的方式接近了它。在本質上。信息從表單域傳遞過來。如果輸入的數據與數據庫中的字段匹配,那麼我希望它返回/回顯結果'是'。如果它不匹配,我需要它迴應'不'。似乎挺直。PHP中的數組顯示問題AJAX

該教程是爲預定值設計的。即 $ existing_users = array('test',''one','two',three');

雖然我想'測試',''一','兩',三''實際上從數據庫中動態拉動。

於是我就有關將設置它這樣做,雖然我寫的代碼,當我嘗試把動態值中不工作我的代碼如下:

$existing_users = array(); 
mysql_select_db($database_db, $db); 
$result = mysql_query('SELECT * FROM clients') or exit(mysql_error()); 
while ($row = mysql_fetch_assoc($result)) {$existing_users[] = $row['shortcode'];} 

$arr = $existing_users; 

$display = "'" . implode("', '", $arr) . "'"; 

    // THIS IS THE PROBLEM 
    // If the code is written out as: 
    // $existing_users=array('test',''one','two',three'); 
    // It works. 
    // When the script is coded as below. It doesn't work. 
    // Note. If I echo $display is displays 'test',''one','two',three' 

$existing_users=array($display); 

//value received from the get method 
$user_name=$_POST['user_name']; 

//checking weather user exists or not in $existing_users array 
if (in_array($user_name, $existing_users)) 
{ 

//user name is not available 
echo "no"; 
} 
else 
{ 
//user name is available 
echo "yes"; 
} 

我我不確定我是否正在接近這個正確的方式,因爲我正在竊聽一個在線通話,這可能會有一個更簡單的方法。任何想法將不勝感激。

+1

請不要將'mysql_ *'函數用於新代碼。他們不再被維護,社區已經開始[棄用流程](http://goo.gl/KJveJ)。查看[**紅框**](http://php.net/manual/en/function.mysql-pconnect.php)?相反,您應該瞭解[準備好的語句](http://goo.gl/vn8zQ)並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli的)。如果你不能決定,[本文](http://goo.gl/3gqF9)將有助於選擇。如果你關心學習,[這是一本很好的PDO教程](http://goo.gl/vFWnC)。 –

+0

不知道爲什麼你要分配一個新變量'$ arr'。 – PeeHaa

+0

您正在向'$ existing_users'數組添加一個字符串。你爲什麼要做所有轉換和複製'$ existing_users'的開始? – PeeHaa

回答

3

這裏有一個更快的方法做到這一點:

$user_name=mysqli_real_escape_string($_POST['user_name']); 

$result = mysql_query("SELECT * FROM clients where shortcode like '$user_name'") or exit(mysql_error()); 

if(mysql_num_rows($result)==0) 
    echo 'no'; 
else 
    echo 'yes' 

我沒有驗證輸入從$ _POST tho

無論如何,你有什麼教程?

+0

我只是顯示如何做得更快,甚至提到我沒有驗證輸入*嘆息* –

+1

我應該熟悉mysqli –

+1

你應該。無論是'mysqli_ *'還是PDO。 – PeeHaa

1

你不需要重拍$existing_users,因爲您已經創建了從數據庫查詢

$existing_users = array(); 
mysql_select_db($database_db, $db); 
$result = mysql_query('SELECT * FROM clients') or exit(mysql_error()); 
while ($row = mysql_fetch_assoc($result)) { 
    $existing_users[] = $row['shortcode']; 
} 

$user_name=$_POST['user_name']; 

if (in_array($user_name, $existing_users)){ 
    echo "no"; 
} else { 
    //user name is available 
    echo "yes"; 
} 

該數組並嘗試移動你的代碼生成PDO

$db = new PDO('mysql:host=localhost;dbname='.$database_db, 'username', 'password', array(ATTR::PDO_EMULATE_PREPARES => false)); 
$stmt = $db->prepare("SELECT * FROM clients WHERE `shortcode`=:shortcode"); 
$stmt->execute(array(':shortcode' => $_POST['user_name'])); 

if($stmt->rowCount() == 1){ 
    echo 'no'; 
} else { 
    echo 'yes'; 
}