简体   繁体   中英

PHP execute multiple queries and while loop

I am having some difficulty executing multiple queries.

I have been reading about mysqli_multi_query however I'm not sure how to implement this into my existing code.

Ideally I need to query two separate tables and display the results within the same while loop. Should this be a do-while, or am I way off?

My current code is;

$id = $_GET['id'];

//setup first query
$query = ("SELECT pub_id, title FROM vw_ft_search WHERE pub_id = $id");

//setup second query
$query = ("SELECT phys_desc FROM vw_physical_descriptions WHERE publication_id = $id");

$result = $conn->query($query);

if($result === false) {
    trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}

    while($row = $result->fetch_assoc()){

        //result from first query
        if (!empty($row['pub_id'])){ echo $row['pub_id'] . '<br />'; }
            else echo "no information" .'<br />';

        //result from first query
        if (!empty($row['title'])){ echo $row['title'] . '<br />'; }
            else echo "no information" .'<br />';

        //result from second query here

    }

New to this so any help/advice is appreciated.

Assuming these are 1:1 records you should try to JOIN your queries instead. Also, I fixed your SQL injection

$id = $conn->real_escape_string($_GET['id']);
$query = "SELECT vfs.pub_id, vfs.title, vpd.phys_desc
    FROM vw_ft_search vfs
        INNER JOIN vw_physical_descriptions vpd ON vfs.pub_id = vpd.publication_id
    WHERE vfs.pub_id = $id";

The best way is to use a join statement:

SELECT pub_id, title, phys_desc FROM vw_ft_search 
JOIN vw_physical_descriptions ON vw_physical_descriptions.publication_id=vw_ft_search.pub_id
WHERE vw_ft_search.pub_id = $id"

The JOIN mushes the table together, the ON tells the server how to match the data up.

Can $result = $conn->query($query); handle multi query? Maybe you should be using

$result = $conn->multi_query($query);

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