I have two tables with this content:
Table users:
id 1
username demoUser
pwd 123
uid ghuyd3t2fgaggascxucxtu767fjc1g1e
Table all_product:
id 1
p_name demoNmae
price demo
product_id ghuyd3t2fgaggascxucxtu767fjc1g1e
I want to join them and fetch data, this is the code I'm using:
$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'];
}
But I got this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'' in /Applications/AMPPS/www/AppenceMedia/fetch_user.php:22 Stack trace: #0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22): PDOStatement->execute() #1 {main} thrown in /Applications/AMPPS/www/AppenceMedia/fetch_user.php on line 22
Be sure that you have really a table named users and If you are using table alias the try use these in everywhere
$query = "SELECT tableUsers.*, tableProduct.*
FROM users tableUsers
JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id
WHERE tableProduct.product_id = tableUsers.$uid";
anyway you should not use php var in sql .. you are at risk for sqlijection .. try take a look at prepared statement and binding param
I think your query is a bit wrong. You should do it like:
table_name as table_alias
So in your case:
$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
You're using the alias of table but in select you're using the name of table.. that gives you the error.
Also in where condition bind the parameter
Try this code:
$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'];
}