PHP使用连接表进行搜索



所以我有两个表:

品牌:

  • id
  • brand_name
  • 产品:

  • id
  • id_brand(颗)
  • nama_product
  • harga_product
  • warna_product
  • berat_produc

我想搜索产品并返回该品牌名称,我使用以下代码:

$query = mysqli_query($koneksi,"SELECT product.* FROM brand 
LEFT JOIN product on brand.id = product.id_brand
WHERE product.nama_product LIKE '%".$keyword."%'
OR product.harga_product LIKE '%".$keyword."%'
OR product.berat_product LIKE '%".$keyword."%'
OR product.warna_product LIKE '%".$keyword."%' 
ORDER BY id ASC");
$hitung_data = mysqli_num_rows($query);
if ($hitung_data > 0) {
while ($data = mysqli_fetch_array($query)) {
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $data['nama_product']; ?></td>
<td><?php echo $data['brand_name']; ?></td>
<td><?php echo $data['harga_product']; ?></td>
<td><?php echo $data['berat_product']; ?></td>
<td><?php echo $data['warna_product']; ?></td>
</tr>
<?php } } else { ?> 
<tr>
<td colspan='4' class="text-center">Tidak ada data ditemukan</td>
</tr>
<?php } ?>

突然出现如下错误:

Notice: Undefined index: brand_name in C:xampphtdocsProject-Jokitugaspw2022admindashboardproduct_data.php on line 37

怎么解?

brand_namebrand表的一部分,因此您也需要为您的结果选择它。而不是:

SELECT product.* FROM brand 
LEFT JOIN product on brand.id = product.id_brand
WHERE product.nama_product LIKE '%".$keyword."%'
OR product.harga_product LIKE '%".$keyword."%'
OR product.berat_product LIKE '%".$keyword."%'
OR product.warna_product LIKE '%".$keyword."%' 
ORDER BY id ASC

使用:

SELECT product.*, brand.* FROM brand 
LEFT JOIN product on brand.id = product.id_brand
WHERE product.nama_product LIKE '%".$keyword."%'
OR product.harga_product LIKE '%".$keyword."%'
OR product.berat_product LIKE '%".$keyword."%'
OR product.warna_product LIKE '%".$keyword."%' 
ORDER BY id ASC

相关内容

  • 没有找到相关文章

最新更新