PHP: using SQL result in a loop without re-executing query - php

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!

If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.

Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

Related

Multiple Tables of same Database on the same site

I want to display 9 different tables from my sql database in 9 different html created tables on the website.
In detail: I have 9 tables ("dt_bookmarks_01", "dt_bookmarks_02" etc.) with 4 columns "id" (which is primary and auto increment), icon (for favicon), link (url) and text (for the display text).
I've created 9 different html tables with bootstrap and want to output the content of each table in a different bootstrap table of my site.
My problem is that i have no idea how to get different "foreaches" or counter for each different table.
To automaticaly add new rows to the bootstrap table I use the count and foreach function. problem here is: I dont know how to seperate them from each other. If i have 4 entries in sql table 1 it multiplies the one and only entrie of sql table 2 to match the current count of 4.
I am very new to sql and php so I guess I just miss some fundamental functions or something.
document header:
php
$sql = "
SELECT *
FROM dt_bookmarks_01, dt_bookmarks_02";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
and for the html table I use:
php
<tbody>
<!--begin: SQL Selection -->
<?PHP
$count = 0;
foreach($rows as $item){
if (!empty($item['icon'])) {
$icon = '<img src="assets/media/bm-icons/'. $item['icon'] . '">';
}else{
$icon = '<img src="assets/media/bm-icons/default.png">';
}
$count++;
echo "<tr>";
/*echo "<td>" . $count . "</td>";*/
echo "<td> " . $icon . "</td>";
echo "<td> <a href=\"" . $item['link'] . "\"'>" . $item['text'] . "</a> </td>";
echo "<td></i> ";
echo "</i></td>";
echo "</tr>";
}
?>
<!--end: SQL Selection -->
</tbody>
I do not have a database on hand to give you an answer with complete code, but here is the idea:
<?php
for ($i = 1; $i <= 9; $i++)
{
$query = "SELECT index1,index2 FROM dt_bookmarks_0$i";
echo "<h1>This is the content of table $i</h1>";
# RUN THE QUERY HERE !!!
echo "<table>";
# EXTRACT THE RESULTS
foreach $rows as $item
{
echo "<tr><td>$item[index1]</td><td>$item[index2]</td></tr>"
}
echo "</table>";
echo "<br><br>";
}
?>
Loop on your tables.
In each table loop, you output the HTML code to display it's content.
Avoid SELECT *, specify your indexes (research "sql why avoid SELECT *")
So you loop twice. One time to go through the tables, the other to loop on the results.
so here is the new working code.
header:
<?PHP
require_once('/htdocs/_nt/mysql/data.php');
$sql = "
SELECT *
FROM dt_bookmarks";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$conn->close();
?>
and for the table output:
<?PHP
$count = 0;
foreach($rows as $item){
if ($item['category'] == talk) {
$count++;
echo "<tr>";
echo "<td> " . $icontalk . "</td>";
echo "<td> <a href=\"" . $item['url'] . "\"'>" . $item['text'] . "</a> </td>";
echo "</tr>";
}else{
echo "";
}
}
?>

index array results from mysql call so I can call multiple times

Ok, so I think I should be storing my mysql query as an array since I want to call upon the data multiple times. So instead of querying the database over and over, I can just do it once and then use the array over and over.
However, I am a bit lost in how to regenerate the table I was able to with mysql+php with the new array...
Here is my array call:
$userid = 3;
$results = mysqli_query($con,"SELECT user,product,etd FROM wp_summary WHERE user=$userid");
$history = array();
while( $row = mysqli_fetch_array($results) ){
$history[]= [
$row['product'],
$row['etd']
];
}
echo print_r($history); //debugging so I can see I actually called it right
But what I would like to do is now dynamically generate a table with a while loop on the rows. with a MySQL query, it was like this:
while($row = mysqli_fetch_array($result))
{
echo "<tr style='font-size: 0.8em'>";
echo "<td>" . $row['product'] . "</td>";
echo "<td>" . $row['etd'] . "</td>";
echo "</tr>";
}
But I can I convert this for the array now instead of the mysql query?
Solved my own riddle after the hint from #DimitrisFilippou ;
for ($i = 0; $i < count($history); $i++) {
echo '<br>';
echo $history[$i]['product'];
echo $history[$i]['etd'];
}

Need to Count results of a list created in PHP

Okay I have a list being populated and echoed out on a page.
$sql = "SELECT * FROM `game_toe` WHERE `owner`='$mech_units'";
$mydata = mysql_query($sql);
while($record = mysql_fetch_array($mydata)){
echo "<td>" . $record['units'] . "</td>";
Now the results fluctuate depending on the number of 'mech_units' there are. What I need is to display how many are being displayed in the list. Any suggestions?
you can use built in function mysql_num_rows($mydata). This will give you the total number of records that are fetched.
First of all, I would suggest using mysqli.
You could declare a variable which increases by one every time you echo a 'mech_unit'.
$sql = "SELECT * FROM `game_toe` WHERE `owner`='$mech_units'";
$mydata = mysql_query($sql);
$i = 0;
while($record = mysql_fetch_array($mydata)){
$i++;
echo "<td>" . $record['units'] . "</td>";
}
echo "There are " . $i . " mech_units.";
Another option would be to use the mysql_num_rows() function.

Select one value from database

I have the code bellow, it's ok but I want to be able to use for example the 4th value extracted from the database, use it alone, not put all of them in a list, I want to be able to use the values from database individually. How do I echo them?
Edit: I was thinking to simplify things, to be able to add the values from database into one array and then extract the value I need from the array (for example the 4th - ordered by "order_id"). But how?
Right now I can only create a list with all the values one after the other..
(Sorry, I am new to this). Thank you for all your help..
<?php
include '../../h.inc.php';
$con = mysql_connect($db['host'],$db['user'],$db['passwd']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM options WHERE Name LIKE 'x_swift%' ORDER BY order_id");
echo "<table border='1'>
<tr>
<th>Values</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['VALUE'] . "</td>";
echo "</tr>";
$array = array(mysql_fetch_array($strict));
}
echo "</table>";
mysql_close($con);
?>
To select the value in the value column of the row where order_id is 4, use this SQL:
$query = 'select value from options where order_id = 4';
Then you can access this result in many ways. One is to get the entire result row (which in this case is just one cell) as an associative array:
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
echo 'value = ' . $row['value'];
}
You can also get the value directly:
if ($result = mysql_query($query)) {
echo 'value = ' . mysql_result($result, 'value');
}
It would just be a query like...
$result = mysql_query("SELECT * FROM options WHERE ID = 3");
mysql_fetch_row($result);
Unless Im misunderstanding you....let me know
But you really should use PDO, instead of deprecated mysql_* functions
http://php.net/manual/en/book.pdo.php

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