php - 如何在php PDO中加入两个不同的表
问题描述
我有两个包含此内容的表:
Table users:
id 1
username demoUser
pwd 123
uid ghuyd3t2fgaggascxucxtu767fjc1g1e
Table all_product:
id 1
p_name demoNmae
price demo
product_id ghuyd3t2fgaggascxucxtu767fjc1g1e
我想加入他们并获取数据,这是我正在使用的代码:
$uid = $_GET['pid'];
$query = "SELECT users.*, all_product.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}
但我得到了这个错误:
致命错误:未捕获的异常“PDOException”和消息“SQLSTATE [42S02]:未找到基表或视图:/Applications/AMPPS/www/AppenceMedia/fetch_user.php:22 中的 1051 未知表“用户”:22 堆栈跟踪:#0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22): PDOStatement->execute() #1 {main} 在第 22 行的 /Applications/AMPPS/www/AppenceMedia/fetch_user.php 中抛出
解决方案
您使用的是 table 的别名,但在 select 中您使用的是 table 的名称 .. 这会给您带来错误。
同样在 where 条件下绑定参数
试试这个代码:
$uid = $_GET['pid'];
$query = "SELECT tableUsers.*, tableProduct.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = :product_id";
$statement = $con->prepare($query);
$statement->bindParam(':product_id', $uid, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}
推荐阅读
- tfs - 需要 TFS 版本(数字)列表及其到 TFS 2019 更新的映射
- javascript - 如何将 footer.tpl 添加到 .php 文件
- chatbot - /restart 和 slot 的问题
- vhdl - VHDL中的多维别名
- java - 我如何制作 youtube 下载器和编译器
- javascript - 如何将日期传递给 getFullYear()?
- linq - 使用 Linq 扩展从每个类别中获取最后一项
- postgresql - 是否可以在创建图像时初始化数据库,而不是在启动容器时?
- android - 如何在 Android 中获得设备所有者权限?
- arrays - *ngFor 按项目数量循环