SQL 注入保护...第 2 半语句不起作用

SQL Injection protection...2nd Half of statement does not work

我的 PHP 语句的第一部分相应地更新了数据库中的值,但第二部分不再设置 cookie 值,我做错了什么,我知道它有些小问题:

    include("db_connect.php");
session_start();
$input_game = $_POST['game'];
$input_user = $_POST['email'];

//$sql = "UPDATE users_table SET Pref_Game = '" . $input_game . "' WHERE Email='" . $input_user . "'";
$stmt = $conn->prepare("UPDATE users_table SET Pref_Game = ? WHERE Email= ?");
$stmt->bind_param("ss", $input_game, $input_user);

声明的第二部分:

   if( $stmt->execute() ) {
$cookie_name2 = "content";
setcookie($cookie_name2,$input_game, time() + (86400 * 30), "/"); // 86400 = 1 day
} else {
    //Error
}

有人可以阐明这个问题,将其整合到声明的第二部分中吗?所以它相应地工作。

在条件测试中将 execute() 中的 return 换行。 (execute() return 成功时为 TRUE,失败时为 FALSE。)

您还可以使用预处理语句运行您的后续查询,例如:

if( $stmt->execute() ) {

   $sql="SELECT Pref_Game FROM users_table WHERE Email = ?";
   $stmt2 = $conn->prepare($sql);
   $stmt2->bind_param("s",$input_user);
   $stmt2->execute();
   $pref_game = $stmt2->fetchColumn();
   setcookie($cookie_name2,$pref_game, time() + (86400 * 30), "/"); // 86400 = 1 day
   $stmt2->close();

} else {
   //Error
}

备注:

这假设 Email 在 users_table 中是唯一的。此示例代码未测试 $stmt2->execute return 是否成功,您可以将其包装在条件测试中,因此我们不会落入 fetchColumn. If the query is successful, but doesn't return a row, then thefetchColumn() ` 将 return FALSE。

if( $stmt->execute() ) {

   $sql="SELECT Pref_Game FROM users_table WHERE Email = ?";
   $stmt2 = $conn->prepare($sql);
   $stmt2->bind_param("s",$input_user);
   if ( $stmt2->execute() ) {
       $pref_game = $stmt2->fetchColumn();
       setcookie($cookie_name2,$pref_game, time() + (86400 * 30), "/"); // 86400 = 1 day
   } else {
     // error executing stmt2
   }
} else {
  // error executing stmt
}