Php 返回资源id 8而不是所需值的Mysql查询
嗨,我正在尝试发现如何修复我的查询以返回正确的结果。我的问题是:Php 返回资源id 8而不是所需值的Mysql查询,php,mysql,Php,Mysql,嗨,我正在尝试发现如何修复我的查询以返回正确的结果。我的问题是: $selectShoeRatingQuery = "SELECT cast(round(AVG(rating)*2)/ 2 as decimal(10,1)) FROM rating WHERE shoe_id = '$_GET[id]'"; $shoeRating = mysql_query($selectShoeRatingQuery); 查询应返回一个小数点后1位为3.5的数字。在PhpMyAdmin中进行测试时,它工作正
$selectShoeRatingQuery = "SELECT cast(round(AVG(rating)*2)/ 2 as decimal(10,1)) FROM rating WHERE shoe_id = '$_GET[id]'";
$shoeRating = mysql_query($selectShoeRatingQuery);
查询应返回一个小数点后1位为3.5的数字。在PhpMyAdmin中进行测试时,它工作正常,但是在我的站点上,它返回资源id 8
数据库连接正常。试试
SELECT round(AVG(rating) * 2.0) / 2.0 AS result
FROM rating
WHERE ....
mysql\u查询返回一个资源。您需要从中获取一行:
$query = mysql_query($selectShoeRatingQuery);
$row = mysql_fetch_row($query);
$shoeRating = $row[0];
而且,除非你别无选择,否则不要使用mysql_uuu扩展集!它们被弃用了,PDO等人更好。您的查询很容易受到攻击
引用
对于返回resultset的SELECT、SHOW、description、EXPLAIN和其他语句,mysql_query在成功时返回资源,在出错时返回FALSE
你需要把它取出来,这样你就可以用了
$row = MySQL_fetch_row($query);
如果您现在不使用已准备好的语句,请至少使用
警告
你的代码容易受到攻击,你需要逃避所有的get和post,更好的方法是使用
博览群书
笔记
整个ext/mysql PHP扩展提供了所有以前缀mysql\ux命名的函数,现在和将来都将被删除。因此,请使用PDO或MySQLi
博览群书
通过PHP调用时,select查询返回一个资源,它本质上是指向结果第一行的指针。要获取数据,必须使用mysql\u fetch\u数组,它将获取指针引用的行 读取该行后,指针将自动递增以指向下一行 所以,你的代码应该是这样的
$connection = mysqli_connect(...);
$query = ""; //put your query here
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
//$row will contain the data of the row in an array format. Use it here.
}
此外,请不要使用mysql函数,因为它们现在已被弃用。使用MySQLi或PDO。谢谢您,这解决了我的问题。@enifeder还确保您正确地退出get请求
$selectShoeRatingQuery = "SELECT cast(round(AVG(rating)*2)/ 2 as decimal(10,1)) as
rating
FROM rating WHERE shoe_id = '$_GET[id]'";
$shoeRating = mysql_query($selectShoeRatingQuery);
$result = mysql_fetch_array($shoeRating);
echo $result["rating"];
$connection = mysqli_connect(...);
$query = ""; //put your query here
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
//$row will contain the data of the row in an array format. Use it here.
}
$selectShoeRatingQuery = "SELECT cast(round(AVG(rating)*2)/ 2 as decimal(10,1)) as
rating
FROM rating WHERE shoe_id = '$_GET[id]'";
$shoeRating = mysql_query($selectShoeRatingQuery);
$result = mysql_fetch_array($shoeRating);
echo $result["rating"];