编辑:两个查询都可以与 JOIN 语句结合使用
$query = "
SELECT
dd.user_id,
dd.foo
FROM
tmp_agent_coverage as ac
LEFT JOIN
tmp_detail_db as dd
ON
ac.agent_id=dd.user_id
WHERE
ac.primary_area LIKE '$search_term%'
";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");
while($r=mysqli_fetch_array($result))
{
echo $r['user_id'], ' ', $r['foo'], "\n";
}
edit2:独立的例子
<?php
$dbc = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($dbc->connect_error) {
var_dump($mysqli->connect_errno, $mysqli->connect_error);
die;
}
setup($dbc);
$search_term = 'xy';
$query = "
SELECT
dd.user_id,
dd.foo
FROM
tmp_agent_coverage as ac
LEFT JOIN
tmp_detail_db as dd
ON
ac.agent_id=dd.user_id
WHERE
ac.primary_area LIKE '$search_term%'
";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");
while($r=mysqli_fetch_array($result))
{
echo $r['user_id'], ' ', $r['foo'], "\n";
}
define('DEVELOPMENT_DEBUG_MESSAGES', 1);
function mysqliError($dbc, $description) {
if ( !defined('DEVELOPMENT_DEBUG_MESSAGES') || !DEVELOPMENT_DEBUG_MESSAGES ) {
echo '<div class="error">', htmlspecialchars($description), '</div>';
}
else {
echo '<fieldset class="error"><legend>', htmlspecialchars($description), '</legend>',
htmlspecialchars($dbc->error), '</div>';
}
}
function setup($dbc) {
$q = array(
'CREATE TEMPORARY TABLE tmp_agent_coverage (
agent_id int auto_increment,
primary_area varchar(32),
primary key(agent_id),
key(primary_area)
)',
"INSERT INTO tmp_agent_coverage (primary_area) VALUES ('xy1'),('dfg'),('xy2'),('abc'),('xy3')",
'CREATE TEMPORARY TABLE tmp_detail_db (
user_id int auto_increment,
foo varchar(32),
primary key(user_id)
)',
"INSERT INTO tmp_detail_db (foo) VALUES ('fooxy1'),('foodfg'),('fooxy2'),('fooabc'),('fooxy3')"
);
foreach($q as $query) {
$dbc->query($query) or die(__LINE__ .' '.$query. ' '. $dbc->error);
}
}
印刷
1 fooxy1
3 fooxy2
5 fooxy3
原始答案:
mysqli::query
返回 false 表示执行查询时发生错误。这可能是语法错误或特权或...或... $dbc 对象
的error
and属性应该包含有关错误的更详细信息。errno
但是您不应该向任意用户显示完整的错误消息。
因此,出于调试目的,定义一个函数,如
define('DEVELOPMENT_DEBUG_MESSAGES', 1);
function mysqliError($dbc, $description) {
if ( !defined('DEVELOPMENT_DEBUG_MESSAGES') || !DEVELOPMENT_DEBUG_MESSAGES ) {
echo '<div class="error">', htmlspecialchars($description), '</div>';
}
else {
echo '<fieldset class="error"><legend>', htmlspecialchars($description), '</legend>',
htmlspecialchars($dbc->error), '</div>';
}
}
然后在你的代码中使用这个函数,比如
<?php
define('DEVELOPMENT_DEBUG_MESSAGES', 1);
[...]
$query="SELECT agent_id FROM agent_coverage WHERE primary_area LIKE '$search_term%'";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");
define(...)
完成调试后删除该行。