以下是我在MySQL表达式中包含PHP变量的失败尝试。用1替换变量会导致打印结果。任何帮助将不胜感激。
$query = "
SELECT name FROM teams
WHERE id = '$shooterID'";
$shooters = mysql_query($query)
or die(mysql_error());
$i = 0;
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[$i];
$i++;
}
$shooters = mysql_query("
SELECT name FROM teams
WHERE id = '$shooterID'")
or die(mysql_error());
$i = 0;
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[$i];
$i++;
}
由于
尝试使用这里的方法并没有完全解决问题(尽管再次感谢)。以下是我修改过的工作以及更多上下文(我不需要清理数据,因为它直接来自另一个查询。
$shooters = mysql_query("
SELECT * FROM events JOIN teams
on events.shooter = teams.id
") or die(mysql_error());
$i = 0;
while($results = mysql_fetch_array( $shooters )) {
$shooterIDs[$i] = $results[0];
$i++;
}
//var_dump($shooterIDs); == array(1) { [0]=> string(1) "1" }
$query = "
SELECT name FROM teams
WHERE id = '".$shooterID[0]."'";
$shooters = mysql_query($query)
or die(mysql_error());
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[0];
}
原来我的最后一次尝试是在变量名称$ shooterIDs [0]中错过了's'。愚蠢的错误。可能还有其他人已经在你的所有帮助下解决了。谢谢!
答案 0 :(得分:4)
查询不是你的问题,输出是:
错误:
$i = 0;
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[$i];
$i++;
}
正确:
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[0];
}
同时强>
如果要包含这样的变量,请确保正确清理输入。例如:
$shooterID = (int)$_GET['shooter_id'];
如果数字不是数字,则强制数字为0
;如果数字传入1
,则强制为shooter_id[]=somthing
,但它永远不会是SQL注入字符串。< / p>
答案 1 :(得分:0)
不要在查询中放置$ shooterID周围的单引号。
你可能也想要这样的东西:
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[0];
$i++;
}
打印出结果。
答案 2 :(得分:0)
你试过了吗?
$query = "SELECT name FROM teams WHERE id = '" . $shooterID . "'";
另外,我没有看到你在任何地方定义$shooterID
,确保你定义它
即。
$shooterID = 0;
另外,
$i = 0;
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[$i];
$i++;
}
应该是
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter[0];
}
或
while($shooter = mysql_fetch_array( $shooters )) {
echo $shooter['name'];
}
或
while($shooter = mysql_fetch_object( $shooters )) {
echo $shooter->name;
}
答案 3 :(得分:0)
尝试这样的事情(为了清晰起见,添加了评论):
// Create the query, assuming $shooterID is an integer
$query = "SELECT name FROM teams WHERE id = '{$shooterID}'";
// Execute query
$shooters = mysql_query($query);
// Check result
if (!$shooters) { die(mysql_error()); }
// Iterate through rows
while ($shooter = mysql_fetch_array($shooters)) {
// To display the entire $shooter array
print_r($shooter);
// To select the first item in $shooter array (no matter what it is)
echo $shooter[0];
// To specifically select the name field in $shooter array
echo $shooter['name'];
// To iterate over the $shooter array and display all fields
// This will only be the name, unless you change the query to SELECT * FROM,
// in which case this will return all fields in the table
foreach ($shooter as $field) {
echo $field;
}
}
答案 4 :(得分:0)
此外,您可能希望在输出中有一些分离:
while ($shooter = mysql_fetch_array( $shooters ))
{
echo $shooter[0], "\n"; // or '<br>' if outputting to html
}