简体   繁体   中英

MYSQL SELECT statement with variable based on PHP for loop

Currently, $selection outputs the following: MIN(Bale_ID), MIN(Incoming_Moisture) which is exactly what it should be outputting (they're names from another table). However, when I put $selection into the mysql_query $data1, it seems to just be reading the last value (MIN(Incoming_Moisture)) and only displays the results for that. How do I get the query to read the entire array of elements in $selection? Thank you!!

while ($row1 = mysql_fetch_array($fieldnames1)) {   
$fields = $row1['fields1']; 
$explode = explode(',',$fields);

if ($row1) {
    for ($i=0; $i<$minrows; $i++) {
        if ($i<$minrows-1){
            $comma = ", ";
        }
        else {
            $comma = "";
        }
        //$selection = "MIN(".$explode[$i].")".$comma;
        //echo $selection;
        $data1 = mysql_query("SELECT MIN(".$explode[$i].")".$comma." from data WHERE (fchmitimestamp LIKE CONCAT(@year,'%',@month,'%',@day,'_________'))");
        $all1 = mysql_num_fields($data1); //return # of columns; for some reason is returning "1" right now.

        while ($row2 = mysql_fetch_array($data1)) {
            for ($col=0; $col<$all1; $col++) {
                echo $all1;
                echo "<td>Min: " . $row2[$col] . "</td>";
            }
            echo "</tr>";
        }
    }       
}
}
echo "</table>";

Look at the order of operations in your code:

loop {
     ... fetch data ...
     ... assign results to $data1 ...
}

Nowhere in your loop do you output or save the results you've got in $data1 , so each iteration of the loop overwrites the results of the previous iteration - in other words, only the LAST iteration's results will be stored.

you are running the query once per for loop cycle (1 field at a time) and since first ones yields in SQL error because of the trailin comma, these will not be echoed except the last one.

-- notice the error in first query
SELECT MIN(Bale_ID), from data WHERE (fchmitimestamp LIKE CONCAT(@year,'%',@month,'%',@day,'_________'))
SELECT MIN(Incoming_Moisture) from data WHERE (fchmitimestamp LIKE CONCAT(@year,'%',@month,'%',@day,'_________'))

use var_dump($selection) instead of echo $selection to see yourself

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