在PHP中使用BETWEEN和LIKE查询

时间:2016-07-26 14:34:17

标签: php database mysqli sql-like between

我希望在两个日期之间进行搜索。用户输入两个日期,我想在两个输入日期之间搜索日期。

Screenshot from website

这是我的代码:

if (isset($_POST["submit3"])) {
    $get_date3=$_POST["fdate3"];
    $get_date4=$_POST["fdate4"];
$con=mysqli_connect("localhost","root","","taghvim");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT * FROM dating WHERE t_fdate LIKE BETWEEN '$get_date3' AND '$get_date4'";
$result=mysqli_query($con,$sql);

// Associative array
$row=mysqli_fetch_assoc($result);
printf ("%s (%s)\n",$row["t_id"],$row["t_fdate"].$row["t_edate"]);

// Free result set
mysqli_free_result($result);

mysqli_close($con);    
}

和我的错误:

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\Taghvim-2\process.php on line 95
() 
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\Taghvim-2\process.php on line 99

2 个答案:

答案 0 :(得分:0)

据我所知,它应该是:

$sql="SELECT * FROM dating WHERE t_fdate BETWEEN '$get_date3' AND '$get_date4'";

您的关键字LIKE导致问题。请注意上面的查询非常糟糕,您应该将参数绑定到查询:

if ($stmt = mysqli_prepare($con, "SELECT * FROM dating WHERE t_fdate BETWEEN ? AND ?")) {

    /* bind parameters */
    mysqli_stmt_bind_param($stmt, "s", $get_date3);
    mysqli_stmt_bind_param($stmt, "s", $get_date4);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* get the result from the executed statement above */
    $result = mysqli_stmt_get_result($con);

    /* Get the first row from the database, or loop through it */
    $row = mysqli_fetch_assoc($result);

    //Other code here

    /* close statement */
    mysqli_stmt_close($stmt);
}

答案 1 :(得分:0)

like between是不可能的。期。 X between Y and Z只是

的便捷快捷方式
(y <= x) && (x <= z)

此类比较没有可用的通配符匹配。