Problem with a loop inside a PHP SQL statement - php

Here is my code, part of it is working flawlessly while the other isn't.
<?php
$query = "Select * from Query ORDER BY time DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
?>
<span class="hotspot" onmouseover="tooltip.show('<center><b><?php echo $row['name'] ?></b></center>');" onmouseout="tooltip.hide();">
<?php
echo "<img src='/" . $row['name'] . ".gif'> ";
}
?>
Now there is like 100+ rows, the second $row['name'] is working fine with the loop, but the first one is using the First rwos result for every result.Any Solution?

have you tried assigning $row['name'] to a variable then use the variable to build the HTML?

I'm not sure if this matters but you may want to put a semicolon in your first piece of echo code:
<?php echo $row['name']; ?>

I don't spot any obvious errors-- try adding one line code so it echos the $row['name'] earlier in the loop, which might help you understand better what's going on. See below:
<?php
$query = "Select * from Query ORDER BY time DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']."<br>"; // <-------- ADD THIS LINE
?>
<span class="hotspot" onmouseover="tooltip.show('<center><b><?php echo $row['name'] ?></b></center>');" onmouseout="tooltip.hide();">
<?php
echo "<img src='/" . $row['name'] . ".gif'> ";
}
?>

I found the problem.
The end </span> was after the loop.

Related

How to display the output in a vertical view dynamically?

I am just running a SQL query to fetch a particular data from the database and would like to display in horizontal way inspite of the vertical format, Can we do something to display the data as required.
For Getting the clear understanding of the question i have attached the Output which i am getting and the output which i required after the SQL query is executed.
Thanks in Advance.
Query:
<?php
include 'connect-db.php';
$query = "SELECT distinct work_component FROM daily_progress_demo WHERE package_no='$package_no'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<center>".$row['work_component']."</center>";
echo "<br />";
}
?>
you can do like this
echo "<table>"
echo "<tr>"
while($row = mysql_fetch_array($result)){
echo "<td>".$row['work_component']."</td>";
}
echo "</tr>";
echo "</table>";
echo $row['work_component']."<br>";

Echoing options from column in mySQL (option/select)

I've been working with this for almost an 3 hours now. It just seems unfixable. I've tried millions of options but just won't work.
So I want to echo from column title in table news so they apear like options in option select.
THis is how it looks now:
Here is the code:
<?php
global $mysqli;
mysqli_connect($mysqli,'localhost', 'root', '');
mysqli_select_db ($mysqli,"filip12356");
$sql = "SELECT DISTINCT title FROM news";
$result = mysqli_query($mysqli,$sql);
echo "<select name='title_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['title'] . "'>" . $row['title'] . "</option>";
}
echo "</select>";
?>
Well you seem to be using mysqli_ everywhere except here...
$row = mysql_fetch_array($result))
Should be..
$row = mysqli_fetch_array($result))
I would ensure that all files are UTF-8 encoded without BOM. It seems that the server is misunderstanding the php as text.

do while in do while in php

That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.

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

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

while staement inside another

.I have the following code. I am wondering why does my "echo '<font color="#FF0000">'.$update_date2.'</font><br><br>'.$status.'<br>';" does not show on the screen?
.is it okay to use while statement inside another while statement? as shown in my code below.
<?php
$getquery = mysql_query("SELECT * FROM it_task ORDER BY task_id DESC");
while ($rows = mysql_fetch_array($getquery))
{
$id= $rows['task_id'];
$date=$rows['date'];
$update_date = $rows['update_date'];
$project=$rows['project'];
$topic=$rows['topic'];
$instby=$rows['instby'];
$inst=$rows['inst'];
$dline=$rows['dline'];
$ocome=$rows['ocome'];
$comm=$rows['comm'];
$fin=$rows['fin'];
echo "<div id=\"container\">";
echo "<table>";
echo "<tr>";
echo "<div id=\"conid\">$id</div>";
echo "<div id=\"condate\">$date</div>";
echo "<div id=\"conproject\">$project</div>";
echo "<div id=\"contask\">$topic</div>";
echo "<div id=\"conselect\">$instby</div>";
echo "<div id=\"conselect1\">$inst</div>";
echo "<div id=\"condline\">$dline</div>";
echo "<div id=\"conocome\">";
$updatesquery = "SELECT * FROM it_task_update WHERE update_id=$id";
while($rows1 = mysql_fetch_array($updatesquery));
{
$update_date2 = $rows1['update_date'];
$status = $rows1['ocome'];
$update_id = $rows1['update_id'];
echo '<font color="#FF0000">'.$update_date2.'</font><br><br>'.$status.'<br>';
}
echo "</div>";
echo "<div id=\"concomm\">$comm</div>";
echo "<div id=\"confin\">$fin</div>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
?>
.where have i done wrong in this set of codes. can anyone guide me pls. TIA! More power! :)
$updatesquery = "SELECT * FROM it_task_update WHERE update_id=$id";
<---dude, where's my query?
while($rows1 = mysql_fetch_assoc($updatesquery));
You're not actually executing the query. You're trying to perform a fetch on a string, which is an error condition in MySQL, causing the fetch call to return FALSE, which makes the while() loop terminate immediately..
in other words, you're missing a call to mysql_query() in between those lines.
on another note, if the inner loop is going to be executed "many" times, you should look at rewiting both queries as a single one with a JOIN clause. It's almost always after to do a single large query then run multiple smaller ones.
Do you have any results from SELECT * FROM it_task_update WHERE update_id = $id?
Try doing
print_r($rows1); before line $update_date2 = $rows1['update_date'];
and view the results.
You have a semicolon after the inner while
while($rows1 = mysql_fetch_assoc($updatesquery));
{
// stuff
}
should be
while($rows1 = mysql_fetch_assoc($updatesquery))
{
// stuff
}
You're trying to retrieve results inside processing your query from a query you never execute. Notice that you called mysql_query before you started looping through your results. Then notice you tried to start fetching results from a query you never executed inside your inner while loop.
Yes, it is OK, to have a while or another type of loop inside another one, because it depends on your business logic. You have forgotten to execute the second query before the while loop, though. It would be better if you did this with an INNER JOIN or something so you don't waste the resources.
Also, I would suggest you not to print out the DOM elements with echo, but have them there like this <div id="username">Username: <?php echo $username; ?></div>. However, even in your case there is place for keeping your code clean. Here is my suggestion:
<?php
$getquery = mysql_query("SELECT * FROM it_task ORDER BY task_id DESC");
while ($rows = mysql_fetch_array($getquery))
{
$id= $rows['task_id'];
$date=$rows['date'];
$update_date = $rows['update_date'];
$project=$rows['project'];
$topic=$rows['topic'];
$instby=$rows['instby'];
$inst=$rows['inst'];
$dline=$rows['dline'];
$ocome=$rows['ocome'];
$comm=$rows['comm'];
$fin=$rows['fin'];
echo '<div id="container\">'.
'<table>'.
'<tr>'.
"<div id=\"conid\">$id</div>".
"<div id=\"condate\">$date</div>".
"<div id=\"conproject\">$project</div>".
"<div id=\"contask\">$topic</div>".
"<div id=\"conselect\">$instby</div>".
"<div id=\"conselect1\">$inst</div>".
"<div id=\"condline\">$dline</div>".
"<div id=\"conocome\">";
$updatesquery = "SELECT * FROM it_task_update WHERE update_id=$id";
// you need to execute the query
$updatesresult = mysql_query($updatesquery);
while($rows1 = mysql_fetch_assoc($updatesresult)) // <-- no semicolon here
{
$update_date2 = $rows1['update_date'];
$status = $rows1['ocome'];
$update_id = $rows1['update_id'];
echo '<font color="#FF0000">'.$update_date2.'</font><br><br>'.$status.'<br>';
}
echo '</div>'.
"<div id=\"concomm\">$comm</div>".
"<div id=\"confin\">$fin</div>".
'</tr>'.
'</table>'.
'</div>';
}
?>
Update
Your inner while statements should not be terminated with a semicolon at the logic point. Please check the code above to see where I have placed the comment for you.

Categories