[英]Retrieving values from MySQL
I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. 我有一个非常简单的表,其中包含“受害者”列表以及相应类型的被销毁对象。 I'm trying to make an output page of this information, using this code:
我正在尝试使用以下代码制作此信息的输出页面:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits
comes out empty. 但是,
hits
是空的。 What's wrong with my SQL query? 我的SQL查询有什么问题?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query()
doesn't return the actual result of your query, but rather a resource
with which you can then access the results. mysql_query()
不返回实际结果查询,而是一个resource
与您可以再访问结果。
This is a typical pattern: 这是一个典型的模式:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc
returns the next row of the result set. 每次调用
mysql_fetch_assoc
返回结果集的下一行。 If you were expecting multiple rows to be returned, you can call this in a while loop: 如果您期望返回多行,则可以在while循环中调用它:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here: 由于在任何答案中都没有健全的错误检查,因此我将整个内容放在这里:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. 哦,这可以解决最初导致该问题的查询错误。 Note the quotes wrapping the
$vic
variable in the string, as well as the proper escaping of the string... 请注意将
$vic
变量包装在字符串中的引号,以及字符串的正确转义...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.