使用程序样式的预准备语句

时间:2013-04-03 10:56:15

标签: php mysql mysqli

我目前习惯了mysqli,并且正在尝试转换我在mysql中编写的代码。我使用Procedural样式来转换代码,但是我意识到在mysqli中你可以使用预处理语句,而不是使用mysqli_real_escape_string。我试图理解这些准备好的陈述,但是我无法理解它们。如何将以下代码转换为预准备语句?

function user_exists($email){ 
$query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT `mem_id` FROM `members` WHERE `mem_email`='$email'"); 
$query_result = mysqli_num_rows($query); 
return $query_result; 
}

1 个答案:

答案 0 :(得分:2)

function user_exists($email){ 
    $stmt = mysqli_prepare($GLOBALS["___mysqli_ston"], "SELECT `mem_id` FROM `members` WHERE `mem_email`=?"); 
    mysqli_stmt_bind_param($stmt,"s",$email);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $query_result=mysqli_stmt_num_rows($stmt);
    mysqli_stmt_free_result($stmt);
    return $query_result; 
}

说真的,使用OOP风格会更好......

function user_exists($email){ 
    global $___mysqli_ston;//just follow your style
    $stmt = $___mysqli_ston->prepare("SELECT `mem_id` FROM `members` WHERE `mem_email`=?");
    $stmt->bind_param("s",$email);
    $stmt->execute();
    $stmt->store_result();
    $query_result=$stmt->num_rows;
    $stmt->free_result();
    return $query_result; 
}