$q= mysql_query("SELECT
`products`.product,
`products`.price,
`cart`.product,
`cart`.userid
FROM `products`
INNER JOIN `cart` ON `cart`.product=`products`.product") or die('Error: ' . mysql_error());
while($d=mysql_fetch_array($q))
{
echo "<td >";echo "<br><b> Product: </b>$d[2]";echo "</td>";
echo "<td >";echo "<b> Price: </b>$d[1]<br>";echo "</td>";
}
This displays inner joined result of tables -products and cart. product table has product, price and cart table has userid, product. How do i display the products ordered by $us that is logged in user by listing rows in inner joined table where userid= $us???
Use this mysql query
SELECT `products`.product, `products`.price, `cart`.product, `cart`.userid FROM `products` INNER JOIN `cart` ON `cart`.product=`products`.product where cart.userid= $us order by `products`.product ASC
$sql='select
p.`product`, p.`price`, c.`product`, c.`userid`
from `products` p
left outer join `cart` c on c.`product`=p.`product`
where c.`userid`="'.$us.'"';
$q=mysql_query( $sql ) or die('error: '.mysql_error() );
Assigning an alias to each table makes the final sql shorter and, to my mind, easier to read.
That said, as the mysql_
suite of functions in PHP are now deprecated and considered insecure perhaps you ought to migrate the code to either mysqli
or PDO
to avoid possible sql injection On the same note, by using the die('error:'.mysql_error())
if there is an error you would reveal to a potential attacker more than you should, not to mention the rest of the page not loading / degrading gracefully.