【问题标题】:Prepared statement and null value when using?使用时准备好的语句和空值?
【发布时间】:2013-01-19 22:24:50
【问题描述】:

我需要评估用户是否在特定日期之后登录系统。为此,MySQL 数据库中有三个表,用户、调查和登录。调查包含需要与上次登录的用户进行比较的时间点的日期。问题如下。

当我使用“?”占位符,生成的 num_rows 计数始终为 0。但是当我在将查询语句交给 $mysqli->prepare() 之前分配值时,该过程按预期工作。不知何故, store_result() 没有选择该列。这是我的代码:

 if (isset($userId)){
//get survey release date
$res3 = $mysqli->query("SELECT sur_date,sur_url FROM survey ORDER BY sur_id DESC limit 1");
$array = $res3->fetch_assoc();
$theta_date = $array['sur_date'];
//$theta_date = "2013-01-18 01:00:00";

   //this didn't generate errors, but didn't output the correct result either.
   //$query = "SELECT login_id FROM logins WHERE login_user=? AND login_date>=?";
   //if ($stmt = $mysqli->prepare($query)){
   // $stmt->bind_param('ss',$userID,$theda_date);
   // $stmt->execute();

  //this works
  $query = "SELECT login_id FROM logins WHERE login_user='$userId' AND login_date>='$theta_date'";
    if ($stmt = $mysqli->prepare($query)){
    $stmt->execute() or die("The query did not work");

    //if number is greater than 0 do something
    $stmt->store_result();
      printf("The number of login ids after theta are %d",$stmt->num_rows);
  $stmt->close();
}else{
   echo "The query did not execute.";
}
 }else{
   echo "The User ID was not valid.";
   exit();
 }
 $mysqli->close();

任何见解都会有所帮助,

【问题讨论】:

  • $theta_date $theda_date 错字?
  • 感谢 bmeswing,但这是我的帖子中的错字,而不是代码中的错字。虽然我不会把它放在我身边。

标签: php mysqli


【解决方案1】:

准备好的语句似乎与 $theta_date 日期时间格式有问题。 $theta_date 在调查表中存储为“2013-01-18 01:00:00”。 bind_param() 试图解析 $theta_date 作为参考。这是解决方案:

 //convert datetime to Unix timestamp with strtotime()
 $theta_date = $array['sur_date'];
 $timestamp = strtotime($theta_date);

 //In the prepared statement, use MySQL FROM_UNIXTIME function to convert timestamp
 $query = "SELECT login_id FROM logins WHERE login_user=? AND login_date>=FROM_UNIXTIME(?)";

 //changed the parameter types to integer and bound $timestamp to second placeholder
 if ($stmt = $mysqli->prepare($query)){
   $stmt->bind_param('ii',$userId,$timestamp);
   $stmt->execute();

//the rest is the same
 $stmt->store_result();
   printf("The number of login ids after theta are %d",$stmt->num_rows);
   $stmt->close();
}

那是一种痛苦。

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    相关资源
    最近更新 更多