简体   繁体   中英

Joining a MySQL table in PHP

I'm trying to join a table in PHP so I can show the degree name from the degree table.

below is the code, which, works when I query in MySQL. However, when the information is pulled into the html table it shows the first and last name but there's a blank where the major name would be.

student table

student info...

degree (int)

degree table

pkID (int)

degreeName (varchar2)

$pkID = $_GET['id'];
echo "Student ID: " . $pkID;

//create the connection
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_password = '********';
$mysql_db = 'database';

//create conection
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_db);

//check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT s.fname,s.lname, d.degreeName FROM students s,      degree d WHERE s.degree = d.pkID AND s.id = " . $pkID);

echo "<table border='1'>
<tr>
<th>F Name</th>
<th>L Name</th>
<th>Major</th>
</tr>";

while ($row=mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['fname'] . "</td>";
    echo "<td>" . $row['lname'] . "</td>";
    echo "<td>" . $row['degreeName'] . "</td>";
    echo "</tr>";
}
echo "</table>";

尝试这个

$result = mysqli_query($con, "SELECT s.fname,s.lname, d.degreeName FROM students s  inner join degree d on s.degree = d.pkID WHERE s.id = " . $pkID);

Make your JOINs explicit :

SELECT s.fname, s.lname, d.degreeName
FROM students s INNER JOIN degree d
  ON s.degree = d.id
WHERE s.id = $pkID

MySQL can do some internal fudgery to get what it thinks you want, but it won't always work the way you expect, or at all sometimes.

In your original query SQL is going to try to do a full CROSS JOIN , aka attach every row in students to every row in degree , and then filter based on your WHERE conditions. You might not notice this being bad when you have 10 rows in each table, making that CROSS JOIN temp table a measly 100 rows. But if each had 1000 rows, and the CROSS JOIN temp table would involve 1,000,000 rows.

Also, you should really look into parameterizing your queries, or at least sanitizing your inputs. Concatenating variables like $pkID into your query is how SQL injection happens.

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