Split mySQL Query Results using PHP - php

I am working on a PHP function that looks up the list of departments in a school stored in a database table using MySQL and then splits the results into two columns if the result is more than 1 department.
I have tried for, while and foreach loops and for some reason I keep getting an endless loop as a result. I am not sure where I am going wrong.
My function is as follows:
function translateDegreeLists($school) {
require('includes/EM-langSelect-4.php');
$values = array();
$coacs_code = 1;
$cob_code = 2;
$avcon_code = 4;
$coe_code = 3;
$cose_code = 5;
$cotm_code = 6;
$query = "SELECT dept_name, ".$content." AS content FROM explore_majors.departments WHERE school_id = ".$school."";
$result = mysql_query($query);
$nums = mysql_num_rows($result);
if($nums == 1) {
echo '1 Option';
}
elseif(($nums / 2) == 2) {
echo '2 Columns with 2 Options';
}
elseif (($nums / 2) >= 3) {
echo '2 Columns with more than 3 Options';
}
echo '<div class="column column-1-2">';
for ($i=0; $i < $nums; $i++)
{
$row = mysql_fetch_assoc($result);
$dept_name = $row['content'];
echo '<h4>'.$dept_name.'</h4>';
echo '<ul>';
echo '<li>test</li>';
echo '</ul>';
}
echo '</div>';
}
Note: The $content in the query is pulled from the EM-lang-4.php which determines the browser language and selects the appropriate column in the DB.
This is the base of the function as the code above generates a list of 4 departments all within the same column div.
The end result is that I want the function to calculate how many departments are found and if more than 1, split them equally between 2 divs. The divs will be identical with the exception of the content inside.
Any ideas what I am doing wrong?

I believe the problem is that you are running mysql_fetch_assoc every time in the for loop. The loop should be structured as so:
while ($row = mysql_fetch_assoc($result)) {
$dept_name = $row['content'];
echo '<h4>'.$dept_name.'</h4>';
echo '<ul>';
echo '<li>test</li>';
echo '</ul>';
}
Note that this will not format the columns but you will at least be able to print the results of your query.
Php.net is your friend! See example one in the documentation for mysql_fetch_assoc
Lastly mysql_*** functions are deprecated and will eventually be removed from future php versions! See the red warning in the docs

Related

PHP / MySQL - how to transpose data (columns into rows) with dynamic column names into a table

I know there are other questions/answers about this sort of thing, but it took me a while to figure this specifically out, so I figured I'd share it with the community, as likely there are others who could benefit.
I had put together code like the following, which worked fine, but if you needed to add a column, meant adding the name 4 times before you even got to adding it where you wanted in the table:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("
SELECT widget_id
, widget_name
, widget_price
, widget_upc
, widget_color
FROM widgets
WHERE widget_price > ?
");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
// Initiate arrays to place variables from query in order to transpose data from database
$widget_id = [];
$widget_name = [];
$widget_price = [];
$widget_upc = [];
$widget_color = [];
// If there are results, fetch values for each row and add values to each corresponding array
if($result->num_rows > 0 ){
while($row=$result->fetch_assoc()){
$widget_id[] = $row['widget_id'];
$widget_name[] = $row['widget_name'];
$widget_price[] = $row['widget_price'];
$widget_upc[] = $row['widget_upc'];
$widget_color[] = $row['widget_color'];
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
So I wanted to figure out a better way... see my answer below...
After spending a while working on it, I came up with this:
<?php
// Prepare statement & retreive data from database
$sql_retreive = $con->prepare("SELECT widget_id, widget_name, widget_price, widget_upc, widget_color FROM widgets WHERE widget_price > ?");
$bind_process = $sql_retreive->bind_param('d',$price);
$sql_retreive->execute();
$result = $sql_retreive->get_result();
if($result->num_rows > 0 ){ // If there are results, fetch values for each row and add values to each corresponding array
// Initiate an array for each field specified, in which to place variables from query, in order to transpose data from database
for($i = 0; $i < mysqli_num_fields($result); $i++) { // loop through fields
$field_info = mysqli_fetch_field($result); // for each, retreive the field info
$column = $field_info->name; // retreive the field name from the field info
$$column = []; // note double $$, create a blank array using the field name, will loop through for each
} // end of for loop
while($row=$result->fetch_assoc()){ // for each row of responses, place the data into the above created arrays
$field_info = mysqli_fetch_fields($result); // retreive the field info
foreach ($field_info as $field_value) { // for each, retreive the field info
$column = $field_value->name; // retreive the field name from the field info
$$column[] = $row[$column]; // note double $$, using the array (which uses the field name), place the row data in, and loop through for each
} // end of foreach loop
} // end of while
} // end of if num_rows > 0
// Build dynamic table with results transposed
echo "<table class='table'><thead>";
echo "<tr><th>Widgets</th>"; for ($i=0; $i<count($crop_name);$i++) {echo "<th>".$widget_name[$i]." (".$widget_id[$i].")</th>";}
echo "</tr></thead><tbody>";
echo "<tr><td>widget_price</td>"; for ($i=0; $i<count($widget_price);$i++) {echo "<td>".$widget_price[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_upc</td>"; for ($i=0; $i<count($widget_upc);$i++) {echo "<td>".$widget_upc[$i]."</td>";} echo "</tr>";
echo "<tr><td>widget_color</td>"; for ($i=0; $i<count($widget_color);$i++) {echo "<td>".$widget_color[$i]."</td>";} echo "</tr>";
echo "</tbody></table>";
?>
This enables you to just add the column/field name into the query, and then use the values where you want in the table.
Please upvote if you find this helpful!

PHP to display all MySQL columns without knowing how many there are

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.

PHP run query off each array variable and return results in table

I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.

How to echo columns 1...n from mysql database except the first one in php?

I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.

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

Categories