我正在尝试访问数据库中的两个表,一个代理和其他属性。当我单击上一页上的链接时,它会将我带到地址栏中的 id。我不明白为什么我总是收到这条错误消息:警告:mysql_numrows() 期望参数 1 是资源,在第 16 行的 C:''wamp''www''practice''details.php 中给出的布尔值
$id = $_GET['id'];
$agent ="SELECT agentId FROM properties WHERE id='$id'";
$agentQuery ="SELECT * FROM agents WHERE agentId='$agent'";
$agentResult=mysql_query($agentQuery);
$agentNum=mysql_numrows($agentResult);
我已经有这段代码在工作了:
$query ="SELECT * FROM properties WHERE id = '$id'";
$result=mysql_query($query);
$num=mysql_numrows($result);
让我们将查询代码压缩为单个语句:
$agentResult=mysql_query(
"SELECT * FROM agents WHERE agentId='SELECT agentId FROM properties WHERE id='$id''"
);
这不是一个有效的查询。
再加上您实际上并没有检查来自mysql_query()
的返回值以查看它是否成功的事实,并且您有您提供的错误。
mysql_*
函数已弃用 yadda yadda学习使用 PDO 或 mySQLi。
忽略我刚才说的所有这些事情,你的代码应该更像:
$id = $_GET['id'];
$agent_q = "SELECT agentId FROM properties WHERE id='$id' LIMIT 1";
if( ! $rs = mysql_query($agent_q) ) {
die(mysql_error());
} else if( mysql_numrows($rs) == 0 ) {
echo('no agent by that ID');
} else {
$row = mysql_fetch_assoc($rs);
$agent = $row['agentId'];
$agentQuery ="SELECT * FROM agents WHERE agentId='$agent'";
if( ! $agentResult = mysql_query($agentQuery) ) {
die(mysql_error());
}
$agentNum = mysql_numrows($agentResult);
}
或者通过以下方式简化查询:
SELECT a.*
FROM agents a INNER JOIN properties p
ON a.agentID = p.agentId
WHERE p.id = $id
您的查询可能收到错误,因此结果( $agentResult
) 是 false
。因此,错误消息显示"给定布尔值"。
试着用if
的声明来拥抱你的mysql_numrows
:
$agentResult=mysql_query($agentQuery);
if ($agentResult)
{
$agentNum=mysql_numrows($agentResult);
}
else
{
echo mysql_error(); // To show the query error
}
假设$id=<someid>
,这个
$agent ="SELECT agentId FROM properties WHERE id='$id'";
$agentQuery ="SELECT * FROM agents WHERE agentId='$agent'";
解析为:
$agentQuery ="SELECT * FROM agents WHERE agentId='SELECT agentId FROM properties WHERE id='<someid>''";
..无法执行。