While statement only echoing last result - php

I am very new, I am having a small problem.. I cannot get my while loop to loop through my entire result set, it is only retrieving the last result set, and i am expecting 2 result sets.
I echo'd my query out to see the result i would get, and the echo printed out both the result sets i want to print out. Leading me to the confusion my while loop is the issue.
I have looked through lost on here but the posts i have seen it was a problem with their query, rather then their while loop. Any assistance would be greatly appreciated. I have used different posts on here to construct my query, but i don't know where to go from here.
date_default_timezone_set("Europe/London");
$date = jddayofweek(unixtojd());
$sql = "SELECT * FROM tbl WHERE ID = $ID AND Day = $date";
$results = $conn->query($sql);
echo $sql;
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$output = "Test2" . "</br>" . $row["time"] . "</br>";
}
} else {
$output = $output . "test1" . "</br>";
}
}

You are not echoing anything inside your while loop.
I think you need to concatenate the variable $output.
while ($row = $results->fetch_assoc()) {
$output .= "Test2" . "</br>" . $row["time"] . "</br>";
}

You are overwritting the content of $output on every iteration of the loop, you should use the concatenation operator to attach the value of the content to the end of the string.
$output .= "Test2" . "</br>" . $row["time"] . "</br>";

Related

SQL Select producing slightly different results in phpAdmin vs. phpHTML

I consistently miss the first row result, which is more noticeable when there is only one row result.
I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?
<?php
$sql = "SELECT * FROM Order_Items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = $id
AND qty <> 0
ORDER BY Parts.id";
$q = $pdo->prepare($sql);
$q->execute(array());
$row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>' . $row['part_num'] . '</td>';
echo '<td>' . $row['part_desc'] . '</td>';
echo '<td>' . $row['qty'] . '</td>';
}
Database::disconnect();
?>
You are duplicating $row = $q->fetch(PDO::FETCH_ASSOC);.When you asing $q to $row, $q->fetch is cleared (with no data) so in the IF sentence you have no rows to fetch in $q.
You have to remove $row = $q->fetch(PDO::FETCH_ASSOC); and just use it in the IF.
Also try to do a fetchAll() to $q.
$result = $query -> fetchAll();
foreach( $result as $row ) {
/*CODE*/
}
You are not getting an SQL error. This has nothing to do with the value of the line_item_id database column.
You are getting a PHP error. The variable $line_item_id is undefined.

How do I make a clickable url in my php page after getting data from MySQL DB?

I'm trying to pull data from 1 column of a db and making it into a link where the URL is being pulled from another column. Unfortunately, I have not been able to do this. I've attached the screenshot of the output here's the code I'm using:
$sql = "SELECT DISTINCT item_title, item_url, item_date, item_author FROM nbth";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<a>" . $row["item_title"]. " url: " . $row["item_url"]. " <br> - By " . $row["item_author"] . " " . $row["item_date"]. "<br><br></a>" ;
$HTML .= "".$row['item_title']."";
echo $HTML;
}
} else {
echo "0 results";
}
Screenshot of the results:
[![enter image description here][1]][1]
The titles do become links but the get looped again and again, the first title in the first line, then next the first title and second, then the first, second and third, so on and so forth. So, how do I fix this looping and still display the titles as links.
$HTML .= "".$row['item_title']."";
Remove the period (string concat) operator before the equal sign:
$HTML = "".$row['item_title']."";
It causes each iteration of the loop to concat the "".$row['item_title'].""; part every time to the $HTML variable.
Also, pls enclose the href attribute's value by quotation marks(").
echo $html outside the loop
or
while($row = $result->fetch_assoc()) {
$HTML ='';
echo "<a>" . $row["item_title"]. " url: " . $row["item_url"]. " <br> - By " . $row["item_author"] . " " . $row["item_date"]. "<br><br></a>" ;
$HTML = "".$row['item_title']."";
echo $HTML;
}
} else {
echo "0 results";
}

How to create a numbered list inside a table with PHP

I'm executing this type of code inside a table.
while($row = mysql_fetch_array($result))
{
echo "" . $row['id'] . "";
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
}
Which works great and gives me a numbered list (1 Mike Volvo, 2 Mike Ford) for example. The problem is that I now have multiple users in the same table so there are gaps in the list where someone else's entry is since i'm using auto incremented ID for numbers.
So assuming I have 5 entries I obviously want it to be 1-5 but right now its 5-30-45-65 or whatever.
Anyway I looked around for a solution and I found $number = 1; $number++; to be effective and it kind of works and gives me a 1-5 list independent of whatever the ID's are.
The problem is that when I reverse the list using ORDER BY xxx desc the last entry becomes 1 and the first entry becomes 5. But I always want the first entry to remain 1 and the last entry to be 5.
Do you have any ideas on how to create this function using PHP?
You need to simple user $number as you mentioned as in the following code
$number = 1;
while($row = mysql_fetch_array($result))
{
echo $number;
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
++$number;
}
Even if in your SQL you have order by it does not matter in that case.
From what I understand of your question... You are on the right track using the following code...
$LastId ='';
$number = 0;
while($row = mysql_fetch_array($result))
{
if($LastId != $row['id']){
$number++;
}
echo $number;
echo "" . $LastId = $row['id'] . "";
echo "" . $row['name'] . "";
echo "" . $row['car'] . "";
}
So...
If the 'id' isn't the same as the last 'id' (not the same user) it will increment it by 1. Otherwise it will stay the same.
Hope this is what you looking for and helps.
Although this is pretty trivial in php, I would not use php for it. You can easily do this in html:
echo "<ol>";
while($row = mysql_fetch_array($result))
{
echo "<li>" . $row['name'] . $row['car'] . "</li>";
}
echo "</ol>";

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

Combine Multiple rows from mysql array

right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance
You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...
Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.

Categories