2012-02-22 19 views
2

我試圖將我的代碼更改爲msqli從mysql準備的語句。我不確定如何調整當前可用的代碼,以檢查數據庫中是否存在電子郵件。以下是我目前正在使用該作品的代碼。我如何將此變爲準備好的陳述並獲得相同的結果?使用預處理語句檢查數據庫中是否已存在電子郵件

//if email is equal to an email already in the database, display an error message 

if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'"))) 
{ 
    echo "<p class='red'>Email is already registered with us</p>"; 
} else { 
    // missing code? 
} 
+0

歡迎SO。我已將您的帖子重新格式化爲盡我所能。確保閱讀常見問題以習慣標記。有一些代碼錯過了你可能想發佈的內容。 – pmr 2012-02-23 00:31:55

回答

0

應該是這樣的:

// create mysqli object 
$mysqli = new mysqli(/* fill in your connection info here */); 

$email = $_POST['email']; // might want to validate and sanitize this first before passing to database... 

// set query 
$query = "SELECT COUNT(*) FROM users WHERE email = ?" 

// prepare the query, bind the variable and execute 
$stmt = $mysqli->prepare($query); 
$stmt->bind_param($email); 
$stmt->execute() 

// grab the result 
$stmt->store_result(); 

// get the count 
$numRows = $stmt->num_rows(); 

if($numRows) 
{ 
    echo "<p class='red'>Email is already registered with us</p>"; 
} 
else 
{ 
    // .... 
} 

此鏈接可以幫助你,以及:

http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

+0

謝謝,但我得到一個錯誤:致命錯誤:調用一個非對象的成員函數bind_param() – user1227124 2012-02-23 08:51:58

+0

確定排序它,我添加(電子郵件),而不是(*) – user1227124 2012-02-23 17:23:55

+0

'$ stmt-> bind_param($ email )'應該是'$ stmt-> bind_param('s',$ email)'。 – 2012-02-23 22:28:21

相關問題