MySQLi: query with variable to another table

So, I have a database with several tables. Most of these tables contain information about the same document and are linked by identifier (this is stupid, because all this can be in one table, but the company I help cannot change it now). The contents of the two tables I'm currently working on can be seen below.

tblDocument: Contains ID + other information.

tblVerification: Contains identifier, verificationNo + other information.

Now, what I would like to do is find confirmation No in tblVerification from the identifier in tblDocument using PHP and MySQLi. I found a solution that allows me to pass a variable to the request, but it does not seem to be the most efficient solution, and the code confuses me. Any further information on how the query works or a new simpler solution is welcome.

<?php

$mysqli = new mysqli("ip", "name", "pw", "db");
$dbDoc = $mysqli->query("SELECT * FROM tblDocument ORDER BY ID");

while ($row = $dbDoc->fetch_assoc()) {
    $tempID = $row["ID"];

    $bind = 's';
    $queryThis = $mysqli->prepare("SELECT verificationNo FROM tblVerification WHERE ID = ?");
    $queryThis->bind_param($bind, $tempID);
    $queryThis->execute();
    $queryThis->bind_result($result);
    $queryThis->fetch();
    $queryThis->close();
    $tempVer = $result;

    echo $tempVer . " ";
}
?>

Actual question: Is this the most effective way to achieve this result using only PHP and MySQLi and / or what can you do to simplify it?

+4
source share
3 answers

Do you try to join him?

"SELECT tblDocument.*, tblVerification.verificationNo
FROM tblDocument INNER JOIN tblVerification
    ON tblDocument.ID=tblVerification.id
ORDER BY ID"
+2
source

SQL JOIN: -

: -

"SELECT tblDocument.*, tblVerification.verificationNo
FROM tblDocument
LEFT JOIN tblVerification
ON tblDocument.ID = tblVerification.ID
ORDER BY tblDocument.ID;"
+1

:

SELECT tv.id, tv.verificatioNo 
FROM tblVerification tv
INNER JOIN tblDocument td
ON tv.id = td.id
ORDER BY tv.id;

- id WHERE:

WHERE tv.id = ? 
+1
source

Source: https://habr.com/ru/post/1623256/


All Articles