简体   繁体   English

单个数组中的多个mysql查询结果

[英]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 您可以根据需要的值列表避免使用in子句进行简单的使用

$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 .. 但是您不应该在sql中使用php var。.您有sqlinjection ..的风险,为避免这种情况,您应该查看sqldruver以绑定参数..

but if you want append the result for different where condition on same table you should take a look at UNION clause 但是,如果您想将结果添加到同一张表的不同where条件中,则应查看UNION子句

$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. 1.您正在向查询中输入完整的数组。
2. You're doing no preparations on your query thus it's vulnerable to sql injection if $newArray is human input data. 2.您没有为查询做任何准备,因此如果$newArray是人工输入数据,则该查询很容易受到sql注入的攻击。
3. Your logic from looping thru the data, if you managed to get a single query correct, would always loop thru the last query. 3.如果您设法使单个查询正确,那么遍历数据的逻辑将始终遍历最后一个查询。 You need to move the $row = mysqli_fetch_assoc($result) stuff inside your actual loop. 您需要在实际循环中移动$row = mysqli_fetch_assoc($result)东西。

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>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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