Getting one result before the loop - php

I have a query which returns some results, and then I'm using a while loop to output the results.
The problem I'm having is that I want to return the 'question' before the while loop so that it doesn't display a number of times inside the loop.
I have the following code:
$query = "SELECT * FROM polls LEFT JOIN pollanswers ON polls.pollID = pollanswers.pollID WHERE polls.pollID = 1 ORDER By pollAnswerListing ASC";
$result = mysql_query($query);
echo '<p>Question</p>';
echo '<form action="#" class="poll-form">';
echo ' <p class="error"></p>';
echo ' <fieldset>';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}
echo ' </fieldset>';
echo '</form>';
As you can see the loop is working perfectly, but how do I output the question just once from the same SQL statement BEFORE outputting the loop?

You can fetch one row to display your question (assuming you have the same question value for multiple rows), then use mysql_data_seek() to rewind the result resource back to the first record to start your loop:
// Retrieve the first row...
$first_row = mysql_fecth_array($result, MYSQL_ASSOC);
// Output your question however you need to...
echo "whatever...";
// Then rewind the result back to zero
mysql_data_seek($result, 0);
// Proceed with the rest of your while loop
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}

I believe you should not do it like that. The question itself should be retrieved separately, not with answers, because including it in every row of the database result is a waste of resources. Remember, that the data (result of the query) has to be passed from the database and what you do is effectively multiplying this data unnecessarily.
You may not hit the problem now, because it seems there is a small number of possible answers, but you should do it the right way.
In case you still want to do it as you mentioned, then below you can find two solutions regarding getting results before for loop.
Not including first row in for loop
If you do not want it to be included in the loop, just do the following before the loop:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
and use $row as you use $row within the loop.
Including first row in for loop
In this case you can use solution mentioned by #Michael (similarly as my first solution above, but using mysql_data_seek($result, 0) before for loop, so it starts from the beginning of the result again, including first row).

How about:
$row = mysql_fetch_array($result, MYSQL_ASSOC)
if($row) {
echo '<p>Question</p>';
echo '<form action="#" class="poll-form">';
echo ' <p class="error"></p>';
// echo your poll name here somewhere...
echo ' <fieldset>';
do {
echo '<div class="row">';
echo '<input type="radio" name="poll" id="'.$row["pollAnswerID"].'" class="radio" value="'.$row["pollAnswerID"].'" /><label for="'.$row["pollAnswerID"].'">'.$row["pollAnswerValue"].'</label>';
echo '</div>';
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC));
echo ' </fieldset>';
echo '</form>';
}
This also fixes another bug in your old when the MYSQL query returns an empty result set: your old code would generate a bogus form. (The fix is in that this code doesn't generate a poll form if there is no poll.)

Related

PHP form submit with SQL query results in blank table?

I've currently got a page with a form, and I'd like to populate a table based off a SQL query using a variable. I know the value from the select dropdown is being extracted correctly, and I believe I've got bindValue implemented correctly. However, upon submitting the form, nothing shows up in the table. I know the SQL statement is correct as well, as I've run it directly in MySQL and gotten the results I'm looking for.
Here's my code currently:
echo '<form align="center" method="post">';
echo '<select name="flightSelect">';
$flightstmt = $conn->query('select * from flight');
$flightstmt->execute();
while($row = $flightstmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value='".$row['flightnum']."'>";
echo $row['origination']."->".$row['destination'];
echo '</option>';
}
echo '</select>';
echo '<table>';
if (isset($_POST['flightSelect']))
{
$flightSelect = $_POST['flightSelect'];
$flightPassengers = $conn->prepare('select * from passenger where passnum in (select passnum from manifest where flightnum=:flightSelect)');
$flightPassengers->bindValue(':flightSelect', $flightSelect, PDO::PARAM_INT);
$flightPassengers->execute();
while($row = $flightPassengers->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>';
echo $row['lastname']." ".$row['firstname'];
echo '</td>';
echo '</tr>';
}
}
echo '</table>';
echo '<input type="submit" name="submit" value="Find passengers on this flight">';
echo '</form>';
Thanks in advance for any feedback!
<form align="center" method="post"> Form lacks action attribute.
Open the Network Panel in Chrome DevTools and check if the HTTP status code is 500
if yes, then check the error log, you'll find the stack trace atleast.
You need to verify that the passenger table should have flight data you select while submitting.
Debug the query by removing flight condition and see are you get the result for flight.
Rest of the code is correct

How can I echo this value?

All I need to do is echo array pocket $row[0].
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
}
echo $row[0];
I have googled, but results haven't helped. I know I'm missing something stupid, but I'd appreciate the help!
I'm trying to echo the database column, 'ID'. An example of the data I want to echo would be '3'.
Copy $row[0] as you go.
$lastZero = "";
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
$lastZero = $row[0];
}
echo $lastZero;
For debugging the whole row, write this:
var_dump($row)
To output the column ID, write this:
while ($row = mysqli_result::fetch_array($result)) {
var_dump($row); // This will output all values for each row as they're looped through
echo '<br>' . $row['ID'];
}
var_dump($row); // dumps the last row of the returned results, or false if no rows.
echo $row['ID']; // echos the ID of the last row. However if there are no rows, this will not work.
Be aware, as #Daedalus pointed out, $row is an array, so the var_dump line is really just for debugging. Because an array has multiple values, PHP doesn't know how you want to display it. You'll need to program how each element of $row is displayed.

Dynamic dropdown menu don't display the rest of the html codes, Whats wrong?

Hello again codes masters,
I'm stuck at this piece of codes for dropdown menu. Here is the codes
echo '<h3>Select Supplier</h3>';
$deliver_sql = mysql_query("SELECT supplier_name FROM delivery") or die(mysql_error());
echo '<div align="left">';
echo '<form class="forms" action="returns.php" method="post" name="companyform">';
echo "<select class=\"input\" name=\"companyNames\" onChange=\"this.form.submit()\">";
while($row = mysql_fetch_array($deliver_sql) or die(mysql_error()))
{
echo '<option value="'.$row['supplier_name'].'">'.$row['supplier_name'].'</option>';
}
break;
echo '</select>';
echo '</form>';
echo '</div>';
My question is, Is there something wrong with this code? Because when I open this particular page, the footer aint displaying.
Its like there is something that is breaking the whole html codes that causes the footer to doesnt display, even if I used $_POST['companyform'] cannot also detected.
Can someone please find what causes this error.
The problem is in this line
while($row = mysql_fetch_array($deliver_sql) or die(mysql_error()))
when there are no more rows in the $deliver_sql, mysql_fetch_array will return false and die(mysql_error()) will be executed. mysql_fetch_array returning false is not an error so you should not call die in this case
Just use
while($row = mysql_fetch_array($deliver_sql))
try echo '<div style="float:left">'; instead of echo '<div align="left">';
or remove break;
and remove or die(mysql_error()) from while($row = mysql_fetch_array($deliver_sql))

Display image with URL from MySQL

I am using this code to display image from URL, but it is not working,
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++){
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src="<?php echo $row[$i]; ?>" width="60" height="60" alt="word" />';
echo '</td>';
}
?>
The result is, I get alt text only, and image is not displayed. also, I get error
Notice: Undefined offset: 1 in D:\wamp\www\demo\login\flashcard.php on
line 31
In my file
What I am trying is, to get 5 img url from database and display them in columns of a table..and what I guess is I am getting same img URL again and again...for 5 times..
Please give me guideline and tell me what I could be missing...
i have never seen someone loop through a query that way, i do it like this:
print "<table>";
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch LIMIT 5';
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
print '<tr>
<td>
<img name="myimage" src="'.$row[column_name_here].'" width="60" height="60" alt="word" />
</td>
</tr>';
}
print "</table>";
change column_name_here to the name of the column which store the image file name
edit: changed mysql_fetch_row to mysql_fetch_array <- that is why u got the same image all 5 times.
With mysql_fetch_row() your fetching the results one row at a time, since you only specified url_imgsrch in the SELECT statement, it will be an array with one single element, the value for url_imgrch. This is the reason for your error message. The for() loop tries to in turn read the first, second, etc up to fifth value of the array, which never gets updated with new information and always has only one element.
mysql_fetch_row() will return false when there is no more data to be read, you need to call it to fetch each new row of data, so what you want is to rewrite your code to something along the lines of this:
$sql = 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
while (false !== ($row = mysql_fetch_row($result))
{
echo '<td>';
echo '<img name="myimage" src=' . $row[0] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
The first part is just as you've written, setting up the SQL query and fetching a resource pointer ($result) to with mysql_query().
In the next part the while() loop will run for as long as $row is not false, updating $row with new data for each run of the loop. Since mysql_fetch_row() fetches an numerically indexed array, you want to retrieve $row[0], it's the first (and only) column you requested in the SQL query. There are many ways of writing the while() loop, but this way quite common, and easy to read for other developers.
try this:
<?php
echo 'me'.'<br/>';
$sql= 'SELECT url_imgsrch FROM p_url_imgsrch';
$result = mysql_query($sql);
echo $result;
$row = mysql_fetch_row($result);
for ($i=0; $i<6; $i++)
{
//calling rows
echo '<td>';
//calling rows value for debugging purpose so that i can learn the process and check the output
echo $row[$i].'<br/>';
echo '<img name="myimage" src=' . $row[$i] . ' width="60" height="60" alt="word" />';
echo '</td>';
}
?>

mysql query giving incorrect result in for loop

The code belows gives me only 18 records
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
while the select statement
select Distinct Country from trendsmtable where WHORegionAC='Europe -
all countries'
returns 22 rows while I execute it in mysql which is correct!
Please help me to found the error.
Well, you have an extra $k++ in there that you don't need:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
Edit
I've gone through your code and I've made some edits. Hopefully they'll clean your issue along the way:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';
I think the PHP looks a little odd, it looks like you are looping from 0 to (22 / 5)
then in the inner loop 4 times.
The group by should not make any difference as you are doing a select distinct
Your SQL code in the PHP file contains a GROUP BY clause, which can reduce the number of rows returned, if you have a country more than once in the db.

Categories