Convert MySQL query loop to PHP array (table) - php

I have a system which looks through a database, creates a table of a specified size and then fills the cells with either full or empty depending if there is data in the database for that specific location.
At the moment it works by doing a SQL query for each cell and then populating, but I have 30,000+ records in the database and even with a LIMIT 1 it's still taking about 5 second to load the table.
I'm wondering if dumping the entire contents into a PHP array and then querying that way would be better, but can't work out the best way to sort it, any tips welcome.
Current (working) code:
echo <<<EOD
<table class="racktable"><tr>
<td colspan ="$colspan">Rack Details </td>
</tr>
<tr>
<td colspan ="$colspan"><center>Edit Rack / Empty Rack / Delete Rack</center> </td>
</tr>
EOD;
//Loop through rows, creating a <tr> for each in the table
for ($row1 = 1; $row1 <= $rows; $row1++) {
echo <<<EOD
<tr><td><a name="$row1"></a>$row1</td>
EOD;
//Loop through columns creating <td> within <tr>
for ($col1 = 1; $col1 <= $columns; $col1++) {
$sql2 = "SELECT ID, sample, rack, srow, col, location FROM samples WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack' LIMIT 1";
if (!$result2 = $db->query($sql2)) {
die('There was an error running the query [' . $db->error . ']');
}
$row3 = $result2->num_rows;
//If location is empty, colout green
if ($row3 == 0) {
echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";
}
else {
//Location is not empty, colour red and link to sample
while ($row2 = $result2->fetch_assoc()) {
$columns1 = $row2['col'];
$ID = $row2['ID'];
$tooltip = $row2['sample'];
$queryStr = $_SERVER['QUERY_STRING'];
$spath = $_SERVER['PHP_SELF'] . "?" . $queryStr . "&sample=" . $ID;
echo <<<EOD
<td style="background-color: #FF0000" title="$tooltip">$col1 <img src="icon.png" style="border: 0" alt=""></td>
EOD;
}
}
}
echo "</tr>";
}
echo "</table>";

You can convert all data from DB directly into a php array with this code:
while(($PHPToPHP[] = mysql_fetch_assoc($SqlResult )) || array_pop($dataToPHP));
may be work for your code:
while(($dataToPHP[] = $result2->fetch_assoc()) || array_pop($dataToPHP))
And to see what it does use print_r($dataToPHP).
To manage the errors die('There was an error running the query [' . $db->error . ']'); and if ($row3 == 0) { echo "<td style=\"background-color: #A3CD81\">" . $col1 . "</td>";} to colorize, you need to make some tests to correctly manage.

You need an array with index like your where
SELECT ID, sample, rack, srow, col, location
FROM samples
WHERE srow = $row1 and col = $col1 and location = '$location' and rack = '$rack'
LIMIT 1";
Your array looks like:
$samples = array(
"$row1:$col1:$location:$rack" => array( 'id' => $id, 'sample' => $sample
)
Or you can use some hash array like:
$samples = array(
md5( "$row1:$col1:$location:$rack" ) => array( 'id' => $id, 'sample' => $sample
)
Insert all values once - than get it like
$val = $samples["$row1:$col1:$location:$rack"];
// or from hash array
$val = $samples[md5( "$row1:$col1:$location:$rack" )];

Related

Trying to get MySQL results to display horizontally

I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );

PHP MYSQL Table only display one row of results

I have a page where I am using a parameter in the URL as a filter for my SQL query.
I created a variable from the URL parameter:
$station = htmlspecialchars($_GET["station"]);
Then set up a conditional query depending on whether or not the URL parameter is set:
if(isset($_GET['station'])) {
$query = "SELECT * FROM song_of_the_day WHERE station = '$station'";
}
else {
$query = "SELECT * FROM song_of_the_day WHERE end_date >= CURDATE()";
}
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
Then I display the results in a table:
echo "<table width='758' border='0' cellpadding='10' cellspacing='0' class='myTable'>";
while($row = mysql_fetch_array( $result )) {
echo '<tr>';
echo '<td align="left" width="48">' . $row['station'] . '</td>';
echo '<td align="left">' . date('M j, Y',strtotime($row['end_date'])) . '</td>';
echo '<td width="24" align="left"><img src="http://yourligas.yourli.com/ad-inventory/edit.png" border="0"></td>';
echo '<td width="24" align="left"></td>';
echo "</tr>";
echo '</tbody>';
}
echo "</table>";
The query works find when the ELSE command uses the query, where I'm not relying on the parameter in my SQL, but the problem I am seeing when the URL parameter ISSET is only one row gets displayed from the query when there is more than one row that matches the criteria in the actual database. Does anybody know why this is happening?
Thank you
In this line, you appear to be consuming the first row of data while attempting to get the number of rows found:
$num_rows = mysql_fetch_row($result);
This removes the first row from your result cursor.
Instead, you probably meant to do the following:
$num_rows = mysql_num_rows($result);

How to use PHP variables in MySQL queries with WHILE fetched rows?

I have successfully done the php script that connect to my database and return desired data. But i need to extend this script to insert a variable that will show the price with some calculations (tax,no-tax,margin etc.).
This script show me only price value of the first database row 0.00 in all fetched rows and its not correct - for the first database row is ok because product have 0.0000 price, but the other rows are filled with correct values. It seems like the while loop dont like my $styledprice variable . I can't figure how to show correct field values in all lines. Any ideas much apppreciated? I'm a PHP beginner!
$pricequery = "SELECT rrp FROM my_products";
$b2bprice = mysql_query($pricequery);
$rrps = mysql_fetch_array($b2bprice);
$price = $rrps['rrp'];
$styledprice = number_format($price, 2, '.', '');
$query = mysql_query("
SELECT
CONCAT(' <td> ',p.id,' </td><td> ',p.manufacturer,' </td><td> ',p.reference,' </td><td> ',p.name,' </td><td> ',p.quantity,' <td> ','".$styledprice."',' </td> ') AS row
FROM my_products p
");
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while($row=mysql_fetch_array($query))
{
echo "<tr>".$row['row']."</tr>";
}
echo "
</table>";
Yes i know about mysql_ functions that are deprecated.
Something like this should work better.
It seperates the resultset from the database and the output via HTML.
// Get the Result Set
$result = mysql_query("SELECT p.id, p.manufacturer, p.reference, p.name, p.quantity FROM my_products p");
// Convert the rows and columns from the Result Set to a PHP Array
$data = array(); // empty array
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
// Now you have access any row or column
echo "<table>";
foreach($data as $row){
// prepare the data
$formatttedQuantity = number_format($row['quantity'], 2, '.', '');
// show each Table Row
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['manufacturer'] . "</td>";
echo "<td>" . $row['reference'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $formatttedQuantity . "</td>";
echo "</tr>";
}
echo "</table>";
It looks like you can do this all in one sql command like:
<?php
$sql = "SELECT * FROM my_products";
$result = mysql_query( $sql );
echo "
<table>
<tr>
<td><h5>ID</h5></td>
<td><h5>Manufacturer</h5></td>
<td><h5>PN</h5></td>
<td><h5>Name</h5></td>
<td><h5>Quantity</h5></td>
<td><h5>Price</h5></td>
</tr>";
while( $row=mysql_fetch_array( $result ) ){
$price=$row['rrp'];
$styledprice = number_format( $price, 2, '.', '' );
echo "
<tr>
<td>{$row['id']}</td>
<td>{$row['manufacturer']}</td>
<td>{$row['reference']}</td>
<td>{$row['name']}</td>
<td>{$row['quantity']}</td>
<td>{$styledprice}</td>
</tr>";
}
echo "
</table>";
?>

Efficient Method To Display Group Title Once — PHP/MySQL/jQuery

There are three tables in MySQL: Employees, Branches, Departments. I need information to appear in the following way:
ATLANTA Branch Delivery Department Phillip J. Fry Phone: 123456
Engineering Department Turanga Leela Phone: 123457
Bender Rodriguez Phone: 123458
The simple PHP code currently:
1) Takes rows from three tables (simple SELECT query with JOIN)
2) Puts them in row (mysql_fetch_assoc)
3) Displays using the PHP While loop
The result is then like this:
ATLANTA Branch Delivery Department Phillip J. Fry Phone: 123456
ATLANTA Branch Engineering Department Turanga Leela Phone: 123457
ATLANTA Branch Engineering Department Bender Rodriguez Phone: 123458
What technique (JS, jQuery, Ajax) or method can you recommend so I can pull row information using only one query and not duplicate the Branch name and Department name?
UPDATE: If I put the branch name outside the loop (using While loop), there would be multiple loops: 1) To get a branch, 2) To get a department, 3) To get all employees in that department. Loop.
UPDATE: Sharing the code:
<?php
// Create connection
$connection = mysql_connect('localhost','root', '') or die('Connection error.');
mysql_query("SET NAMES 'utf8'", $connection);
mysql_select_db("eReference");
// Check Employees
$query = "SELECT Employees.fName, Employees.lName, Department.deptName, Branch.branchName, ".
"FROM Employees ".
"LEFT JOIN Department ".
"ON Employees.department = Department.id ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.id ;";
$result = mysql_query($query, $connection) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
?>
<h2><?php echo $row['branchName']; ?></h2>
<?php if ($row['deptName']) echo "<h3>" . $row['deptName'] . "</h3>"; ?>
<h4><?php echo $row['fName'] . " " . $row['lName']; ?></h4></p>
<?php
}
?>
<?php
$i = 1; // to be incremented after printing branchName once
while ($row = mysql_fetch_assoc($result)) {
if($i == 1) { ?>
<h2><?php echo $row['branchName']; $i ++; ?></h2>
<?php } ?>
<?php if ($row['deptName']) echo "<h3>" . $row['deptName'] . "</h3>"; ?>
<h4><?php echo $row['fName'] . " " . $row['lName']; ?></h4></p>
<?php } ?>
Just add a variable $i = 1 and check before printing if it is equal to 1. After printing it for first time, increment it.
It is just addition of an if statement.
Hope this helps.
This is how I would do it.
Create a multi-dimensional array with the data, and iterate through the array to render the output.
This will not be the most efficient in terms of memory usage, but unless you have thousands of rows of data, it probably won't be an issue.
The benefit of this, is that the html rendering code is much simpler and easier to understand, plus sql and html are not intermingled. (which is good for code maintenance)
<?php
// Create connection
$connection = mysql_connect('localhost','root', '') or die('Connection error.');
mysql_query("SET NAMES 'utf8'", $connection);
mysql_select_db("eReference");
// Check Employees
$query = "SELECT Employees.fName, Employees.lName, Department.deptName, Branch.branchName, ".
"FROM Employees ".
"LEFT JOIN Department ".
"ON Employees.department = Department.id ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.id ;";
// note you probably want to add an order by statement here too, to ensure consistent sorting
$result = mysql_query($query, $connection) or die(mysql_error());
$data = array();
// build a multi-dimensional array from the result set
while ($row = mysql_fetch_assoc($result)) {
$data[($row['branchName'])][($row['deptName'])][] = array(
'name' => "{$row['fName']} {$row['lName']}",
'phone' => $row['phone'] // add phone, doesn't exist in original query, but just to illustrate how it would work
);
}
// sql finishes here
?>
<?php
// html rendering
// use htmlentities to escape any html chars, such as < > etc
foreach ($data as $branchName => $departments) {
echo '<h2>',htmlentities($branchName),'</h2>';
foreach ($departments as $deptName => $employees) {
foreach ($employees as $employee) {
echo '<h3>',htmlentities($deptName),'</h3>';
echo '<h4>',htmlentities($employee['name']),'</h4>';
echo '<h4>',htmlentities($employee['phone']),'</h4>';
}
}
}
?>
The result gotten from your sql should be an array so use a while loop to iterate throw the array while echo the result of the current index
Maybe this will work..
<?php
$deptName;
while($row = mysql_fetch_assoc($result))
{
if ($row['deptName'])
{
if ($deptName != $row['deptName'])
{
echo "<h3>" . $row['deptName'] . "</h3>";
$deptName = $row['deptName'];
}
}
}
?>
$result = mysql_query($query, $connection) or die(mysql_error());
$newarray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$newarray[$i]['deptName'] = $row['deptName'];
$newarray[$i]['fName'] = $row['fName'];
$newarray[$i]['lName'] = $row['lName'];
$i++;
}
<h2><?php echo $newarray[0]['branchName']; ?></h2>
while($newarray){
?>
<?php if ($newarray['deptName']) echo "<h3>" . $newarray['deptName'] . "</h3>"; ?>
<h4><?php echo $newarray['fName'] . " " . $newarray['lName']; ?></h4></p>
}
?>
So, this is what it did:
$query = "SELECT Employees.lName, Employees.fName, Employees.mName, Position.position, ".
"department.deptName, department.deptId, ".
"Branch.branchName, Branch.branchId, ContactInformation.* ".
"FROM Employees ".
"LEFT JOIN Position ".
"ON Employees.position = Position.id ".
"LEFT JOIN Department ".
"ON Employees.department = Department.deptId ".
"LEFT JOIN Branch ".
"ON Employees.branch = Branch.branchId ".
"LEFT JOIN ContactInformation ".
"ON Employees.contactInformation = ContactInformation.id ".
"ORDER BY Employees.branch, Employees.department ASC;";
$result = mysql_query($query, $connection) or die(mysql_error());
$arrayOfEmployees = array();
while ($row = mysql_fetch_assoc($result)) {
$arrayOfEmployees[($row['branchName'])][($row['deptName'])][] = array(
'lName' => $row['lName'],
'fName' => $row['fName'],
'mName' => $row['mName'],
'position' => $row['position'],
'lPhone1' => $row['lPhone1'],
'lPhone2' => $row['lPhone2'],
'mPhone' => $row['mPhone'],
'fax' => $row['fax'],
'office' => $row['office'],
'email' => $row['email']
);
}
foreach($arrayOfEmployees as $branchName => $arrayOfDepartments) {
echo "<h2>".$branchName."</h2>";
foreach($arrayOfDepartments as $deptName => $arrayOfEmployeeContacts) {
echo '<h3>',htmlentities($deptName),'</h3>';
foreach($arrayOfEmployeeContacts as $employeeContacts) {
echo "<h4>".$employeeContacts["lName"]." ".$employeeContacts["fName"]." ".$employeeContacts["mName"]."</h4>";
echo "<p>";
if($employeeContacts["position"]) echo $employeeContacts["position"]."<br>";
$num = $employeeContacts["lPhone1"];
if($employeeContacts["lPhone1"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["lPhone2"];
if($employeeContacts["lPhone2"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["mPhone"];
if($employeeContacts["mPhone"]) echo "+".substr($num,0,1)." (".substr($num,1,3).") "." ".substr($num,4,3)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
$num = $employeeContacts["fax"];
if($employeeContacts["fax"]) echo "+".substr($num,0,1)." (".substr($num,1,4).") "." ".substr($num,5,2)."-".substr($num,7,2)."-".substr($num,9,2)."<br>";
if($employeeContacts["email"]) echo "".$employeeContacts["email"]."<br>";
if($employeeContacts["office"]) echo "Кабинет — ".$employeeContacts["office"];
echo "</p>";
}
}
}
Tested. The solution works well dynamically — just add more branches and departments into the database. Here is the efficiency check against the method I originally used (in microseconds):
Array-based Original
1 1.015 1.012
2 1.016 1.02
3 1.026 1.013
4 1.015 1.002
5 1.026 1.02
6 1.014 1.02
7 1.013 1.019
8 1.005 1.014
9 1.013 1.006
10 1.021 1.015
Average 1.0164 1.0141

MySQL PHP while loop - one record less than expected returned

I have run into an interesting problem with retrieving data from mysql tables using one select query with couple of joins.
1) query:
$task_details = "SELECT tasks.task, ";
$task_details = $task_details . "tasks.description,";
$task_details = $task_details . "tasks.finishby, ";
$task_details = $task_details . "responsibles.full_name, ";
$task_details = $task_details . "task_assignments.completed, ";
$task_details = $task_details . "tasks.id, ";
$task_details = $task_details . "responsibles.user_id ";
$task_details = $task_details . "FROM tasks,task_assignments,responsibles ";
$task_details = $task_details . "WHERE ";
$task_details = $task_details . "tasks.id = task_assignments.id_task AND ";
$task_details = $task_details . "responsibles.id = task_assignments.id_assignee AND ";
$task_details = $task_details . "tasks.id = $id_task;";
$task_details_q = mysql_query($task_details) or die(mysql_error());
1a) Resulting example query:
SELECT tasks.task, tasks.description, tasks.finishby, responsibles.full_name, task_assignments.completed, tasks.id, responsibles.user_id
FROM tasks, task_assignments, responsibles
WHERE tasks.id = task_assignments.id_task
AND responsibles.id = task_assignments.id_assignee
AND tasks.id =19
2) HTML / PHP code:
<table class="task_table">
<thead>
<th>Task</th>
<th>Description</th>
<th>Due date</th>
<th>Person</th>
<th>Completed</th>
</thead>
<?php
$even = false;
$trow = "";
while($row = mysql_fetch_array($task_details_q))
{
$trow = $trow . "<tr";
if($even) $trow = $trow . " style=\"background-color: #f2f2ed; \"";
$trow = $trow. ">";
$trow = $trow . "<td >$row[0]</td>";
$trow = $trow . "<td>" . $row[1] . "</td>";
$trow = $trow . "<td>" . date('d-m-Y',$row[2]) . "</td>";
$trow = $trow . "<td>$row[3]</td>";
$trow = $trow . "<td style=\"text-align: center;\" >";
if($row[4] > 0)
{
$trow = $trow . "yes";
}
else
{
$trow = $trow . "no";
}
$trow = $trow . "</td>";
$trow = $trow . "</tr>";
$even =! $even;
$number = $number + 1;
}
$trow = $trow . "<tr style=\"border-top: 1px solid #666666;\"><td></td><td></td><td></td><td></td>";
$trow = $trow . "<td>";
$trow = $trow . "Complete all";
echo $trow;
?>
</table><br />
<span style="text-align: center;display:block;font-size: 12px;">Go back to task overview</span>
3) Problem / Question: For some reason the displayed table always omits one record.I have used the same (or very similar concept) in number of PHP scripts but have never run into the same issue. I think the query itself is not a problem - when I run it directly against the DB, it returns correct number of values...(I think).
2 things:
1) You should not be submitting an answer ever time you add info. You should click "Edit" under your original question and add the new info into the question.
2) I think if I clarify how mysql_query and mysql_fetch_array work you'll see what's happening.
When you call mysql_query with a "SELECT", query it returns a resource. This resource is just a reference to a record set. Then when you call mysql_fetch_array on that resource it will return the current record from the set, and advance the record pointer.
So, when you first call mysql_query the record pointer points to the first result. Then you call mysql_fetch_array the first record is returned as an array, and the pointer advances to the 2nd record. The next time you call mysql_fetch_array this 2nd record is returned and the pointer will then point to the 3rd record.
If there is no 3rd record, the next time you call mysql_fetch_array it will not be able to find a corresponding record, and will return false.
This is why you use while($row = mysql_fetch_array($task_details_q,MYSQL_NUM)). You are putting a result into the variable $row and advancing the result pointer, then perfoming some actions with $row. Eventually you will advance the pointer past the last result and $row will be false, which will stop your while loop from advancing.
Now that I've gone through the theory here's what's happening with your code (I'll just remove irrelevant code with //... and add my own comments along the way):
$task_details_q = mysql_query($task_details) or die(mysql_error());
//now you have a resource $task_details_q, it points to the first result
$task_details_array = mysql_fetch_array($task_details_q,MYSQL_NUM);
//you retreive the first result, and advance the pointer to the second result
for($x=0;$x < sizeof($task_details_array);$x++)
{
//you perform operations (echo'ing in this case) on your first result
echo $x . ". : " . $task_details_array[$x] . "<br />";
}
//... HTML CODE SKIPPED
$even = false;
$trow = "";
//the first time this while statement is called you place the data from the second result in $row,
//and advance the pointer to the third result
//the next time you go through the loop you try to place the data from the third result in $row,
//since you say there are only 2 results to your query $row is simply false.
//This causes the while to stop executing and the code to continue on
while($row = mysql_fetch_array($task_details_q,MYSQL_NUM))
{
//... PRINT TABLE CELLS FROM $row SKIPPED
}
//... REMAINING HTML SKIPPED
I'm unsure if you actually need the block of code:
$task_details_array = mysql_fetch_array($task_details_q,MYSQL_NUM);
for($x=0;$x < sizeof($task_details_array);$x++)
{
echo $x . ". : " . $task_details_array[$x] . "<br />";
}
or if you just added it for debugging. If it's just there for debugging, remove it and your first result will be displayed in the while loop. If you need that for loop to execute, comment on this answer and I'll edit my answer to use the first result both in the for and while loops.
As the php seems correct, it is possible that the cause of the problem is in the html. Your header row does not have <tr> tags so perhaps the browser is choking on that as you are missing the first record.
After fixing this, I would recommend to check your html in an html validator to make sure there are no more mistakes there.
#Ben: This is the complete code between mysql_query($task_details) and while($row = mysql_fetch_array($task_details_q)):
$task_details_q = mysql_query($task_details) or die(mysql_error());
$task_details_array = mysql_fetch_array($task_details_q,MYSQL_NUM);
for($x=0;$x < sizeof($task_details_array);$x++)
{
echo $x . ". : " . $task_details_array[$x] . "<br />";
}
?>
<h3>Task details - "<?php echo strtoupper($task_name); ?>"</h3>
<span class="notifierOK">Table below lists all people assigned to the task - including the status (complete / incomplete). To change person's status click on the 'yes' or 'no' link. If you then go back
to (previous page) the completion percentage value will be re-calculated.</span><br />
<form id="task_details" method="post" name="task_details" style="margin-left: auto; margin-right: auto;width: 800px;box-shadow:10px 10px 5px #888888;">
<table class="task_table">
<thead>
<tr>
<th>Task</th>
<th>Description</th>
<th>Due date</th>
<th>Person</th>
<th>Completed</th>
<tr />
</thead>
<?php
$even = false;
$trow = "";
while($row = mysql_fetch_array($task_details_q,MYSQL_NUM))
Please note I have added the 'MYSQL_NUM' as array type based on your suggestion so it doesn't necessarily belong there.
I solved it, i had the same issue.
$run_query = mysqli_query($conn, $stores);
if ($run_query === false){
//error
}else if (mysqli_num_rows($run_query)){
$row = mysqli_fetch_array($run_query);
echo 'bla bla bla' //on this echo I needed to show the data once.
$run_query = null;
$run_query = mysqli_query($conn, $stores);
while ($row = mysqli_fetch_array($run_query)) { //and here I needed to show up the loops of the results of my query.}
So... I just reset the variable that runned the query and re-runned the search. It worked for me! ;)

Categories