我试图将一个PHP变量(在本例中为$ beg)输入到mySQL查询中,但它返回一个空数组结果。数据库中字段的类型是整数。当我输入实际值而不是变量时,我得到正确的结果。怎么了?
$beg = time()-5000;
settype($beg, "integer");
$result = mysql_query('SELECT * FROM records WHERE time>=$beg ORDER BY time ASC');
$statusdata = array();
while ($row = mysql_fetch_array($result)) {
array_push($statusdata, $row["status"]);
}
答案 0 :(得分:5)
确保在字符串中使用$ variables时使用双引号。
$result = mysql_query("SELECT * FROM records WHERE time>= $beg ORDER BY time ASC");
答案 1 :(得分:2)
您应该使用预准备语句而不是mysql_query。
$beg = time()-5000;
settype($beg, "integer");
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT status FROM records WHERE time>=? ORDER BY time ASC");
$stmt->bind_param('i', $beg);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($status);
$statusdata = array();
while($stmt->fetch())
{
array_push($statusdata, $status);
}
$stmt->close();
答案 2 :(得分:0)
更改行
$result = mysql_query("SELECT * FROM records WHERE time>=$beg ORDER BY time ASC");
您必须使用双引号字符串来放置变量。
答案 3 :(得分:0)
更改您的查询
$result = mysql_query(" SELECT * FROM records WHERE time >= $beg ORDER BY time ASC ");
您不能在单引号内使用变量。
答案 4 :(得分:0)
尝试这种方法,我经常使用:
$beg = time() - 5000;
$query = sprintf("SELECT * FROM %s WHERE time >= '%o' ORDER BY %s ASC", "records", $beg, "time");
$result = mysql_query($query);
记住,time()结果是整数,你不需要将他设置为整数