简体   繁体   中英

multiple mysql query result in single array

how can i add result of multiple queries in a single array so it makes it easier to later output.

for example,

$newArray = array("mike", "john");
while ($newArray !== false){
    $sql = "Select * from accounts where name = '$newArray'";
    $result = mysqli_query($db_connection,$sql);
}

 while ($row = mysqli_fetch_assoc($result)) {
    printf $row['firstName'];
    echo "----";
    printf $row['num_accounts'];
    echo "----";
    prinf $row['location'];
    echo "----";
    echo "<br>";
}

i am sure i am missing something that obvious. but the idea is that i want to setup a loop to read from an array and then execute the query and store the results. each time query executes the condition is different but from same table, , but then keep adding the results to single output, making it easier to output in the end.

you could avoid the while simple using in clause based on list of values you need

$newList = "'mike', 'john'";

$sql = "Select * from accounts where name IN (" .$newList .")";

but you should not use php var in sql ..you are at risk for sqlinjection .. for avoid this you should take a look at your sqldruver for binding param ..

but if you want append the result for different where condition on same table you should take a look at UNION clause

$sql = "Select * from accounts where name IN (" .$newList .") 
        UNION 
        Select * from accounts  where you_col > 10";

There's a few things wrong with your code..
1. You are inputting a full array into your query.
2. You're doing no preparations on your query thus it's vulnerable to sql injection if $newArray is human input data.
3. Your logic from looping thru the data, if you managed to get a single query correct, would always loop thru the last query. You need to move the $row = mysqli_fetch_assoc($result) stuff inside your actual loop.

To get this code working it would look like so:

$newArray = array("mike", "john");
foreach($newArray as $name){
    $sql = "Select * from accounts where name = '{$name}'";
    $result = mysqli_query($db_connection,$sql);

    while ($row = mysqli_fetch_assoc($result)) {
        printf $row['firstName'];
        echo "----";
        printf $row['num_accounts'];
        echo "----";
        prinf $row['location'];
        echo "----";
        echo "<br>";
    }
}

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