使用时准备好的语句和空值?

时间:2013-01-19 22:24:50

标签: php mysqli

我需要评估用户是否在特定日期之后登录系统。为此,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();

任何见解都会有所帮助,

1 个答案:

答案 0 :(得分:0)

准备好的声明似乎遇到了$ 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();
}

那是一种痛苦。