PHP关联Brand与Product表搜索产品时出现Undefined index: brand_name错误的解决方法
解决Undefined index: brand_name的问题
这个错误的原因很明确:你的SQL查询结果里根本没有brand_name字段!
你写的查询是:
$query = mysqli_query($koneksi,"SELECT product.* FROM brand LEFT JOIN product on brand.id = product.id_brand WHERE ...");
这里只选取了product表的所有字段(product.*),但brand_name是brand表的字段,所以PHP在读取$data['brand_name']的时候找不到这个索引,就抛出了Notice错误。
修复步骤:
1. 修改SQL查询,包含brand_name字段
把查询语句改成明确选取需要的字段,包括brand.brand_name,另外考虑到你是搜索产品,用INNER JOIN比LEFT JOIN更合理(正常情况下产品都关联了品牌,LEFT JOIN会保留没有对应产品的品牌数据,这不是你需要的):
$query = mysqli_query($koneksi,"SELECT product.*, brand.brand_name FROM product INNER JOIN brand 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 product.id ASC");
我把JOIN的顺序调换了,从brand LEFT JOIN product改成product INNER JOIN brand,这样更贴合“搜索产品并关联对应品牌”的业务逻辑。
2. 修复表格的colspan布局错误
你的else分支里写了<td colspan='4'>,但实际表格有6列,会导致页面布局错乱,改成:
<td colspan='6' class="text-center">Tidak ada data ditemukan</td>
3. 紧急修复:解决SQL注入风险!
你现在直接把$keyword拼进SQL语句里,这是非常危险的SQL注入漏洞,攻击者可以通过构造恶意关键词篡改你的数据库。建议使用mysqli预处理语句来处理:
修改后的安全版本代码:
// 准备预处理语句 $stmt = mysqli_prepare($koneksi, "SELECT product.*, brand.brand_name FROM product INNER JOIN brand ON brand.id = product.id_brand WHERE product.nama_product LIKE ? OR product.harga_product LIKE ? OR product.berat_product LIKE ? OR product.warna_product LIKE ? ORDER BY product.id ASC"); // 给每个LIKE参数添加通配符 $searchKeyword = "%".$keyword."%"; // 绑定参数(四个s表示四个字符串类型的参数) mysqli_stmt_bind_param($stmt, "ssss", $searchKeyword, $searchKeyword, $searchKeyword, $searchKeyword); // 执行语句 mysqli_stmt_execute($stmt); // 获取结果集 $result = mysqli_stmt_get_result($stmt); $hitung_data = mysqli_num_rows($result); if ($hitung_data > 0) { while ($data = mysqli_fetch_array($result)) { ?> <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 } // 关闭语句 mysqli_stmt_close($stmt); } else { ?> <tr> <td colspan='6' class="text-center">Tidak ada data ditemukan</td> </tr> <?php }
这样既解决了brand_name未定义的问题,又修复了SQL注入漏洞,同时修正了表格布局的小问题。
内容的提问来源于stack exchange,提问作者Daffa Raka Mahendra
相关产品推荐
相关产品推荐

