简体   繁体   中英

Mysql query working from command line but only half working in PHP

I have two tables

1.owners
id
firstname
lastname

2.product
id
id2
id3
item

SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='Jezebel';

Works fine from the command line returning all relevant items from owners and product but using the following PHP

$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='".$_POST['fname']."'")

only returns results from the table owners.

I have googled extensively and don't see anyone else with this problem.

$fname= $_POST['fname'];
$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='$fname'")

First, make your query similar to this

    $query = sprintf("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='%s'",mysql_real_escape_string(trim($_POST['fname'])));
    $result = mysql_query($query) or die(mysql_error());
    var_dump(mysql_fetch_assoc($result));

and let me know the result so I can update this answer.

First of all: You have two table which match on autoincrement column id ?

However, try this?

SELECT tb1.id, tb1. firstname, tb1.lastname, tb2.id, tb2.id2, tb2.id3, tb2.item FROM owners AS tb1 LEFT JOIN product AS tb2 ON tb2.id=tb1.id where tb1.firstname=$fname

I have found the error. It was nothing to do with the select statement. I had a typo in the display code. It should have been like this

echo "</td><td>"; 
echo $row['id3'];

But was like this instead

echo "</td></td>"; 
echo $row['id3'];

Thank you all for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM