PHP左连接不显示结果

时间:2015-02-17 16:07:07

标签: php mysql join left-join

我想在PHP中继续加入表。我是一个留下加入的总菜鸟,我无法弄清楚我做错了什么!

$value=$_GET['value'];
$storeid=$_GET['store'];
$id=$_GET['id'];
$latitude=$_GET['lat'];
$longitude=$_GET['long'];

$result = mysqli_query($con,"SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM link_qr, carlist LEFT JOIN link_qr.vin ON carlist.vin
WHERE qr="$value";");

while($row = mysqli_fetch_array($result)) {
    echo $row['id']; 
    echo $row['vin'];
    echo $row['qr'];
}

这是表结构

表:link_qr

  

ID ------ VIN --------- QR ------ webid ---------其他

表:carlist

  

ID --- --- stknum VIN ---- ---- VT STAT --- ---其他--- STORE_ID --- web_code QRCode的

完成所有操作后,我想拥有以下内容。

我想加入carlist和link_qr,其中vins彼此相等,然后我需要它返回carlist id,其中vin等于qr。

以下是我遇到的错误:

**Notice: Undefined index: store in /api/app_request/left_join.php on line 13
Notice: Undefined index: id in /api/app_request/left_join.php on line 14
Notice: Undefined index: lat in /api/app_request/left_join.php on line 15
Notice: Undefined index: long in /api/app_request/left_join.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in api/app_request/left_join.php on line 22**

2 个答案:

答案 0 :(得分:1)

有几点需要注意:

首先,您的SQL查询不正确:

SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin 
FROM carlist 
LEFT JOIN linkqr ON linkqr.vin=carlist.vin 
WHERE qr="$value";

只要存在这些表和列,就应该是正确的格式。其次,您不应该查询具有未转义值的数据库。这导致SQL注入。更合适的是,你可以写下你的查询:

$query = <<<SQL
SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin 
FROM carlist 
LEFT JOIN linkqr ON linkqr.vin=carlist.vin 
WHERE qr=?
SQL;

$stmt = mysqli_prepare($query);
mysqli_bind_param($stmt, "s", $value); // this sets the ? in the sql query to $value
mysqli_execute($stmt);
$result = mysqli_get_result($stmt);
while($row = mysqli_fetch_array($result)) {
    echo $row['id']; 
    echo $row['vin'];
    echo $row['qr'];
}

答案 1 :(得分:0)

为什么不这样做:

"SELECT C.PrimaryId, Field, AnotherField
 FROM tablename AS C
 LEFT JOIN tablename AS L ON C.matching_id = T.matching_id
 WHERE tablename.fieldname = :fieldname