SQL Select producing slightly different results in phpAdmin vs. phpHTML - php

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.

Related

While statement only echoing last result

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

MySQL row being outputted twice

I need to output a name from the last added row of my table, and it works sort of, it outputs the correct data twice. So instead of name1 it gives me name1name1. I'm still a novice with PHP but i think there is a double loop somewhere in this piece of code which is giving me a hard time, but i'm still unable to locate where that is..
If someone can give me a pointer that would be greatly appreciated.
<?php $query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
} ?>
By default, mysql_fetch_array() returns values both as associative and as enumerated (MYSQL_BOTH); specify either one or the other
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
EDIT
But the mysql extension is old and deprecated, and you really should be switching to mysqli or pdo with prepared statements and bind variables. If you're just learning, then it's best to learn the right methods with the right extensions from the start
No need of the while. You are fetching a single row. And use mysql_fetch_assoc for associative array
$row = mysql_fetch_assoc($results);
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
I would use mysql_fetch_assoc. Because this will only fetch the results as an associative array.
$query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}

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

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

Using PHP foreach to get mysql table data

ive got 1 database table contains row:
TABLE FROM reservations:
attandee01
attandee02
attandee03
attandee04
attandee05
attandee06
PHP CODE:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
echo '<td>' . $r['attandee1'] . '</td>';
echo '<td>' . $r['attandee2'] . '</td>'
echo '<td>' . $r['attandee3'] . '</td>'
endwhile;
or is there any simple way using foreach to echo attandee1 - attandee10?
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
endwhile;
Should echo each column value per table row.
EDIT: If you only want the attendees:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
for($i = 1; $i < 11 $i++) {
echo '<td>' . $r['attendee'.$i] . '</td>';
}
endwhile;
you can use foreach, of course, as $r is a regular array and can be iterated using foreach() operator. Did you try it?
However, looking at the field names, I suspect serious design flaw in your data structure.
It seems attandees should be stored in another table.
You may also consider using templates. Printing data directly from the database loop is very bad practice. You have to get all your data first and only then start printing it out.
Well yes:
for($i=1; $i<11; ++$i) {
echo "<td>".$r["attandee".$i]. "</td>";
}
But that is columns, what you want is the row based solution for that I'd use something like:
for($r=$q->fetch_assoc(); !is_null($r); $r= $q->fetch_assoc()) {
echo "<td>".array_pop($r)."</td>"; // output the only element in the array?
}
$q->free(); // don't forget to free the memory of the result set!
don't know if i understood your question... is this what you're looking for:
while($row = $q->fetch_array(MYSQLI_ASSOC)):
foreach($row as $field){
echo '<td>' . $field . '</td>';
}
endwhile;
Not really sure if this is what you are looking for, but give it a shot:
while($r = $q->fetch_array(MYSQLI_ASSOC)) {
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
}
As example you can use alternate syntax.
<table>
<?php foreach ($mysqli->query($sql) as $row ): ?>
<tr><td><?php echo $row['row_name1']; ?></td><td><?php echo $row['row_name2']; ?></td></tr>
<?php endforeach; ?>
</table>

Categories