Query not returning in order - php

If you require any additional information for me to help you assist me please let me know. The project requires to be password protected, though.
I am utterly baffled at the moment because I have a functioning piece of code in this section of an uncompleted project, or so I thought. I am looking for any and all advice that will help solve this problem.
I am not getting a 'sane' result, I am doing the same thing twice and getting different results. Both pieces of code return ALL of the answers to the SAME question successfully, but one of them is displaying them in order 17, 18, 19, 16 within the exact block of code, while the second displays 16, 17, 18, 19 in proper order.
In the second piece of code as well, which is part of a more detailed view of a given question and all answers associated with it (just a more detailed view of the first code), the edit functions will edit the correct code, but the delete check boxes fail and delete the wrong item. This pattern does NOT coincide with the visual ordering of the malfunctioning code, either, and appears quite random. This may be the same or a different problem, and I am looking into this.
As follows with two sections of code, one of the sections is displaying rows of the data of all of the answers to a question:
$query2 = "SELECT * FROM ST_Answers
WHERE referencingQuestionID = '$permIDNum'
ORDER BY 'permanentAnsNumber'";
$result2 = mysql_query($query2);
$ret = "";
$letter = "a";
$ret .= "<div class='lq answerListItem'>";
$ret .= "<span class='lqh2 answerNumber'> </span>";
$ret .= "<span class='lqh2 answerTextBody'>Answer Text Body</span>";
$ret .= "<span class='lqh2 answerSummaryText'>Answer Summary Text</span>";
$ret .= "<span class='lqh2 answerNextQuestion'>Next Q#</span>";
$ret .= "<span class='lqh2 correct'>Correct?</span>";
$ret .= "</div>";
$i = 0;
$n = mysql_numrows($result2);
while( $i < $n ){
$permAID = mysql_result($result2,$i,"permanentAnsNumber");
$aText = mysql_result($result2,$i,"answerTextBody");
$aSummary = mysql_result($result2,$i,"answerSummaryText");
$nextQID = mysql_result($result2,$i,"nextQuestionID");
$correctA = mysql_result($result2,$i,"correctAnswer");
$ret .= "<div class='lq answerListItem'>";
if($letter != "a") { $ret .= "<br/>"; }
$ret .= "<span class='lq answerNumber'> </span>";
$ret .= "<span class='lq answerTextBody'>" . $letter . ") $aText </span>";
$ret .= "<span class='lq answerSummaryText'>" . $aSummary . "</span>";
$ret .= "<span class='lq answerNextQuestion'>" . $nextQID . "</span>";
$ret .= "<span class='lq correct'>" . $correctA . "</span>";
$letter++;
$ret .= "</div>";
$i++;
}
This second piece of code, is displaying the same data but a bit more using the SAME query, but instead of displaying items out of order, it displays them properly in the correct order, yet the code is almost exactly the same!
$query2 = "SELECT * FROM ST_Answers
WHERE referencingQuestionID='$permID'
ORDER BY 'permanentAnsNumber'";
$result2 = mysql_query($query2);
$ret .= "<div id='answerContainer'><h3>Associated Answers: </h3>";
$i = 0;
$n = mysql_numrows($result2);
// NOTE: This is displaying everything in correct order
// TODO: Reference this
while( $i < $n ){
$permAID = mysql_result($result2,$i,"permanentAnsNumber");
$aText = mysql_result($result2,$i,"answerTextBody");
$aSummary = mysql_result($result2,$i,"answerSummaryText");
$nextQID = mysql_result($result2,$i,"nextQuestionID");
$correctA = mysql_result($result2,$i,"correctAnswer");
$ret .= "<div class='answerRow'>";
$ret .= "<span class='perAID'>" . "<h5>Answer ID(Warning do not change):<textarea rows='1' cols='4' name='ids[]'>" . $permAID . "</textarea></span></h5>";
$ret .= "<span class='aText'>" . "Answer Text: <br /><textarea name='aTxt[]' rows='5' cols='40'>" . $aText . "</textarea></span><br />";
$ret .= "<span class='aSummary'>" . "Answer Summary: <br /><textarea name='aSum[]' rows='5' cols='40'>" . $aSummary . "</textarea></span><br />";
$ret .= "<span class='nextQID'>Question this leads to: <textarea name='nxtQID[]' rows='1' cols='4'>" . $nextQID . "</textarea></span><br />";
$ret .= "<span class='correctA'>" . "Answer point value: <textarea name='ansCorrect[]' rows='1' cols='2'>" . $correctA . "</textarea></span><br />";
$ret .= "<span class='del'><h6>Delete? <input type='checkbox' name='delete[]'></h6></span><br />";
$ret .= "</div><br />";
$i++;
}
Does anyone have any ideas on where to even begin with this? I'm entirely stumped.

Your problem is that you use quotes around a column name. Introducing that way a constant literal string to ORDER BY you effectively eliminate the ordering of the resultset.
Change
$query2 = "SELECT * FROM ST_Answers WHERE referencingQuestionID = '$permIDNum'
ORDER BY 'permanentAnsNumber'";
^ ^
to
$query2 = "SELECT * FROM ST_Answers WHERE referencingQuestionID = '$permIDNum'
ORDER BY permanentAnsNumber";
Here is SQLFiddle demo.
On a side note: learn and use prepared statements with either PDO or MySQLi. Mysql_* extension is deprecated.

I advice you change your style, try to use this
$query2 = "SELECT * FROM ST_Answers WHERE referencingQuestionID='$permID' ORDER BY permanentAnsNumber";
$result2 = mysql_query($query2);
$ret .= "<div id='answerContainer'><h3>Associated Answers: </h3>";
while($row = mysql_fetch_assoc($result2)) {
$ret .= "<div class='answerRow'>";
$ret .= "<span class='perAID'>" . "<h5>Answer ID(Warning do not change):<textarea rows='1' cols='4' name='ids[]'>" . $row["permanentAnsNumber"] . "</textarea></span></h5>";
$ret .= "<span class='aText'>" . "Answer Text: <br /><textarea name='aTxt[]' rows='5' cols='40'>" . $row["answerTextBody"] . "</textarea></span><br />";
$ret .= "<span class='aSummary'>" . "Answer Summary: <br /><textarea name='aSum[]' rows='5' cols='40'>" . $row["answerSummaryText"] . "</textarea></span><br />";
$ret .= "<span class='nextQID'>Question this leads to: <textarea name='nxtQID[]' rows='1' cols='4'>" . $row["nextQuestionID"] . "</textarea></span><br />";
$ret .= "<span class='correctA'>" . "Answer point value: <textarea name='ansCorrect[]' rows='1' cols='2'>" . $row["correctAnswer"] . "</textarea></span><br />";
$ret .= "<span class='del'><h6>Delete? <input type='checkbox' name='delete[]'></h6></span><br />";
$ret .= "</div><br />";
}

As Peterm stated, you can't have quotes in this code around the 'ORDER BY' specifier. Once fixed in this piece of code as well as a parent piece of code higher up, everything displays correctly.

Use string and variable concatenation methods while trying to use php variables inside your query or string. Quotes are not required after 'ORDERBY'. take care that too.. This changes may help you here.
change the query :
$query2 = "SELECT * FROM ST_Answers WHERE referencingQuestionID =
'".$permIDNum."' ORDER BY permanentAnsNumber";

Related

Capture the answers from form within while loop

I want to capture answers from forms within a big loop and then update the results into database. I am not sure how to do that, I have made a sample code as follows, and want to for each Save button save each question results. Say we have 5 questions, when I click save botton 1, save answers for question 1; when click save button , save answers for question 2..
Thanks very very much, this drove me crazy.....
<?php
$x=1;
$output="";
while($x<=5){
$output .= "<form action='index.php' id='" . $x . "' method='POST'>";
$output .="<h2>Question" . $x . "</h2>";
$output .= "<h3>selection</h3>";
$output .= "<ul><li><input type='radio' name='selection" . $x . "' value='1'>1</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='2'>2</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='3'>3</li></ul>";
$output .= "<h3>choice</h3>";
$output .= "<ul><li><input type='radio' name='choice" . $x . "' value='a'>a</li>";
$output .= "<li><input type='radio' name='choice" . $x . "' value='b'>b</li></ul>";
$output .= "<p><textarea rows='4' cols='50' name='commentory" . $x . "' form='usrform' placeholder='Enter text here...'></textarea></p>";
$output .= "<input type='submit' name='saveResult" . $x . "' value='Save'>";
$output .= "</form>";
$output .="<br>";
$x++;
}
echo $output;
if(isset($_POST['saveResult' .$x])){
$selection = $_POST['selection' . $x];
$choice = $_POST['choice' . $x];
$commentory = $_POST['commentory' . $x];
$result=$selection . $choice . $commentory;
echo "<script>alert($result])</script>";
// This part just a sample part as I dont know how to capture the results
}
?>
In your current file, you could change the first line in the while loop to this:
$output .= "<form action='index.php?question=" . $x . "' id='" . $x . "' method='POST'>";
What this does is sends a GET request with a number, from 1-5, based on what question was submitted. You can then do something like this to differentiate between your five (or however many) questions:
$questionNumber = $_GET['question']; // The ?question= parameter sent in the URL
if($questionNumber == 1) {
// Question 1 logic here
} else if($questionNumber == 2) {
// Question 2 logic here
} ...
Or do the same thing using a switch statement:
switch($questionNumber) {
case 1:
// Question 1 logic here
break;
...
}

cant display two image links from mysql php

function find_image_by_id() {
global $connection;
$query = "SELECT * ";
$query .= "FROM images ";
$query .= "WHERE page_id={$_GET["page"]}";
$image_set = mysqli_query($connection, $query);
confirm_query($image_set);
return $image_set;
}
function display_image_by_id(){
$current_image = find_image_by_id();
while($image=mysqli_fetch_assoc($current_image)){
$output = "<div class=\"images\">";
$output .= "<img src=\"images/";
$output .= $image["ilink"];
$output .= "\" width=\"72\" height=\"72\" />";
$output .= $image["phone_name"];
$output .= "</div><br />";
}
mysqli_free_result($current_image);
return $output;
}
This is the code I'm using to show the images stored as links in mysql
and the images are in a folder. But what happens after this code is executed only the second
value is displayed. I want both value/ images to be displayed.
Try something like that-
All you need to do is just initialize this variable outside the loop.
$output =''; //initialize before
SO your function look like this -
function display_image_by_id(){
$current_image = find_image_by_id();
$output =''; //initialize before
while($image=mysqli_fetch_assoc($current_image)){
$output .= "<div class=\"images\">";
$output .= "<img src=\"images/";
$output .= $image["ilink"];
$output .= "\" width=\"72\" height=\"72\" />";
$output .= $image["phone_name"];
$output .= "</div><br />";
}
mysqli_free_result($current_image);
return $output;
}

Display a table in while loop

I am trying to display a table in while loop with 3 rows and 3 td for each row. But I am confusing how to archived thit.
This is my code so far:
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output = "<table>\n";
$output .= " <tr>\n";
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
$output .= " </tr>\n";
$output .= "</table>\n";
echo $output;
}
The above code given me a table with multiple rows and 1 td for each row. But it is not my expecting result.
Can anybody tell me how can I display such a table in my While loop?
The current code creates a new table for every single entry. What you want is to move the <table> and </table> pieces outside of the loop, then you want a counter to keep track of how many cells you've handled. If it's even, start a new <tr>. Otherwise, end the current </tr>. Make sure you check at the end to see if you've finished a </tr>, and optionally add an empty <td></td> if needed.
this aught to do it
<?php
echo "<table>\n";
$cells = $total = 0;
$total_cells = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result))
{
$testimonial = nl2br($row['testimonial']);
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
if ($cells === 0)
echo "<tr>\n";
//Create new testimonial output
$output = " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
$cells++;
$total++;
if ($cells === 3 || $total === $total_cells)
{
echo "</tr>\n";
$cells = 0;
}
}
echo "</table>\n";
?>
Try this
$i = 0;
echo "<table>\n<tr>";
while($row = mysqli_fetch_array($result)){
$testimonial = $row['testimonial'];
$cityName = $row['city_name'];
$name = $row['name'];
$imageName = $row['image_name'];
$member = $row['membership_type'];
$testimonial = nl2br($testimonial);
//Create new testimonial output
$output .= " <td>\n";
$output .= " <p>\n";
$output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />";
$output .= " {$testimonial}";
$output .= " </p>\n";
$output .= " <p class=\"name\">{$name}<br />\n";
$output .= " <span>A Teacher - From {$cityName}</span></p>\n";
$output .= " </td>\n";
echo $output;
if( $i %2 == 1 )
echo "</tr><tr>\n";
$i++;
}
echo "</tr>\n</table>\n";
EDIT
In general, for displaying n cells per row, change the if statement to
if( $i % n == (n - 1) )

Adding strings to a list while in a while loop - not working?

I am trying to add strings to a variable, and for some reason, the only part that is taking is the "Services: " part.
Any idea why this might be the case?
$lists = "<br />Services: ";
$servicearray = mysql_query("select serv_id from org_serv_xref where org_id='".$orgid."'");
while ($servicearrayrow = mysql_fetch_array($servicearray)) {
$servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");
$lists . "<ul>";
while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
$lists . "<li>" . $servdescarrayrow['serv_desc'] . "</li>";
}
$lists . "</ul>";
}
Thats because when you want to concatenate strings, you have to still use the = sign, which makes the concat symbol like .=
Your code has to look like this:
while ($servicearrayrow = mysql_fetch_array($servicearray))
{
$servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");
$lists .= "<ul>";
while ($servdescarrayrow = mysql_fetch_array($servdescarray))
{
$lists .= "<li>" . $servdescarrayrow['serv_desc'] . "</li>";
}
$lists .= "</ul>";
}

How do i email data from a form built with a while loop?

As part of a project I have a form in which our clients can edit a list of the keywords in which we work on as part of their SEO.
This is the code I use to display the keywords we have for them on our database
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword". $counter .
"' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
What I don't know what do do is collect the data when the form is submitted into an email.
I have the PHP mail bit ready but struggling on this a bit.
Any help?
I'd recommend changing the code to this:
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword[]' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
You can then access all keywords in the target php file for your form (after submission) using $_POST['keyword'], eg
foreach($_POST['keyword'] as $key => $value) {
echo "Keyword #". $key." value: ". $value."<br />";
// or your code to build your message
}
Instead of naming the inputs like "keyword1", "keyword2", etc, just name them all "keyword[]". When the form is submitted, PHP will aggregate them all into an array.
To use the POST data (make sure your form is using POST):
<?php
$message = '<ol>';
foreach($_POST as $key => $post) {
$message .= "<li><strong>Keyword " . $key . ":</strong>";
$message .= " <span>" . $post . "</span>";
$message .= "</li>";
}
$message .= '</ol>';
// mail the message here.
?>
Brian and Ergo summary are right, but if you don't want to modify the code inside the while loop you could, at the end of that, insert an hidden input that holds the last $counter value. Then in the target php file (where you will send the email), you can load the POST fields (modifying what Stephen wrote):
<?php
$counter = (int)$_POST['counter'];
$message = '';
for($i = 1; $i <= $counter; $i++){
$key = $_POST['keyword'.$i];
$message .= "<p>";
$message .= "<strong>Keyword " . $key . " </strong></label>";
$message .= "<span> " . $post . "</span>";
$message .= "</p>";
}
// mail message here.
?>

Categories