我有两个具有此内容的表:
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'];
}
但是我得到了这个错误:
致命错误:消息'SQLSTATE [42S02]:未捕获的异常'PDOException':未找到基本表或视图:/Applications/AMPPS/www/AppenceMedia/fetch_user.php:22中的未知表'users':22堆栈跟踪:#0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22):PDOStatement-> execute()#1 {main}放在第22行的/Applications/AMPPS/www/AppenceMedia/fetch_user.php中
答案 0 :(得分:1)
您使用表的别名,但是在选择中,您使用表的名称..这会给您带来错误。
也在条件绑定参数的地方
尝试以下代码:
$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'];
}
答案 1 :(得分:0)
请确保您确实有一个名为users的表,如果您使用表别名,请尝试在各处使用它们
$query = "SELECT tableUsers.*, tableProduct.*
FROM users tableUsers
JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id
WHERE tableProduct.product_id = tableUsers.$uid";
无论如何,您不应该在sql中使用php var ..您有被冒用的风险。.尝试看看准备好的语句和绑定参数
答案 2 :(得分:0)
我认为您的查询有误。您应该这样做:
table_name as table_alias
所以在您的情况下:
$query = "SELECT users.*, tableProduct.* FROM tableUsers as users JOIN all_product as tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
br