<?php
$link = mysql_connect('localhost', 'user', 'password');
if (!$link) {
die('Failed to connect to MySQL: ' . mysql_error());
}
$db_selected = mysql_select_db('mysql', $link);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
$query = sprintf("SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND
CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' .mysql_error() . "\n";
$message .= 'Whole query: ' .$query;
die($message);
}
while ($row = mysql_fetch_array($result)) {
echo $row['shop_id'];
}
mysql_free_result($result);
echo "end";
?>
我知道SQL查询通过复制/粘贴到phpmyadmin来工作。我希望脚本只输出shop_id或shop_id系列。现在它输出资源ID#3。我查找了如何修复它,mysql_fetch_array应该是答案。我做错了什么?
答案 0 :(得分:1)
我正在查看您的查询,我只看到您选择了church_id并且您想要输出shop_id,您应该在您的选择中包含这样:
$query = sprintf("SELECT church_id, shop_id FROM hours WHERE day_of_week = DATE_FORMAT(NOW(), '%w') AND CURTIME() BETWEEN open_time AND close_time",
mysql_real_escape_string($day_of_week),
mysql_real_escape_string($open_time),
mysql_real_escape_string($close_time));
$result = mysql_query($query);
答案 1 :(得分:0)
这里有几个问题,第一个问题是您正在使用 mysql 扩展,该扩展未维护并正式弃用(由于被删除)。我建议你试试 mysqli ...
$link = new mysqli('localhost', 'user', 'password', 'mysql');
if ($link->errno) {
throw new Exception($link->error, $link->errno);
}
虽然您已经完成了保护查询的值得称赞的工作,但您确实应该使用 mysqli 中提供的更好的工具,尤其是prepared statements ...
$stmt = $link->prepare('SELECT church_id FROM hours
WHERE day_of_week = DATE_FORMAT(NOW(), ?) AND
CURTIME() BETWEEN open_time AND close_time');
if (!$stmt) {
throw new Exception($link->error, $link->errno);
}
$stmt->bindParam('s', $day_of_week); // assuming $day_of_week is properly defined
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
从 mysqli 预处理语句中获取数据与旧mysql_fetch_array
略有不同但是并不困难。一种方法是使用结果绑定
$stmt->bind_result($church_id);
while ($stmt->fetch()) {
echo $church_id;
}