首页 > 解决方案 > 如何在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 中抛出

标签: phpmysql

解决方案


您使用的是 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'];
    }

推荐阅读