Jump to content

How to show multiple records with the same name on the same page?


Go to solution Solved by ginerjm,

Recommended Posts

15 minutes ago, ginerjm said:

Because people do it all time on these forums.

Well, I don't do that kind of thing. It's counter intuitive to ask for help, to get that help, then sabotage it. 

Hey,

I got a question about your code. I forgot that I wanted to add an image for each question, but I had some code in the book which I've used before so I thought I'd be alright. But your code is in a different format. If I wanted to add an image, would I have to change:

while(list($q, $c) = $results->fetch(PDO::FETCH_NUM))

to accommodate the image?

I did that, changed it to:

while(list($q, $c, $i) = $results->fetch(PDO::FETCH_NUM))

after adding the SQL In: 

SELECT q.question, o.choice, q.image 
    FROM questions q 
    JOIN quiz_options o 
      ON q.qid = o.qid 
    WHERE q.qid = 1;

And print_r($results); gives me just the SQL:

PDOStatement Object ( [queryString] => SELECT q.question, o.choice, q.image FROM questions q JOIN quiz_options o ON q.qid = o.qid WHERE q.qid = 1;

I was expecting array data.

var_dump($i); gives me:

NULL 

and echo $i; does not print anything

Hey,

Got a minor problem. I edited your code, firstly to add images and secondly to replace the PK in the WHERE clause to a placeholder which grabs the value using GET and then to display the correct question. E.g (www.domain.com/index.php?question=5) to display question 5. All is well and it's working. Then I did some error handling such that if the question number is not in the URL (e.g www.domain.com/index.php?question= ) then it will echo an error message , which is also fine.

Now I am trying to add an error message so that if the user edits the url and puts for example: 20 (which does not exist as there are only 15 questions (1-15) then I want an error message. Again this works, but the same error also shows for a valid question id. Here is the revised code:

  <?php

include 'includes/db.php';

$questionId = $_GET['question'] ?? '';
$idError = '';

$sql = "SELECT q.question, o.choice, q.image 
    FROM questions q 
    JOIN quiz_options o 
      ON q.qid = o.qid 
    WHERE q.qid = :id;";
$results = $pdo->prepare($sql);



if ($questionId) {
    $results->execute(['id' => $questionId]);
   
} else {
    $idError = 'No matching id';
}



// this produces rows that contain a question and a choice for that question.
// That means you have to handle the multiple choices by NOT showing the same question over and over.

$last_q = 'x';    // a non-existent value
$choice_num = 0;
while(list($q, $c, $i) = $results->fetch(PDO::FETCH_NUM))
    // retrieve the contents of a single row as 2 vars
{
  if($q <> $last_q) // starting a new question so close the last div and begin a new one
  {
    if ($last_q <> 'x') // is this the first question? If not, close the last question's box
      echo "</div>";
    echo "<div class='quizContent'>";  // start the new question box
        echo "<p>$q</p>"; // show the question  - figure out later how to prevent repetition (which I did earlier)

         
         $pathx = "images/db_images/";
       
           
        echo '<img class="picture" src="'.$pathx.$i.'">';
         

    $choice_num = 0;  // new question; new choice count


  }


  $choice_class = 'choice' . $choice_num; // setup the appropriate choice class
  $last_q = $q;   // remember the current question
  //echo "<p>$q</p>"; // show the question  - figure out later how to prevent repetition (which I did earlier)
  echo "<div class='$choice_class'>";   // a box for this choice
   echo "<p>$c</p>"; 
  echo "</div>";    // close this choice's box
  $choice_num++;    // bump the choice cnt


}
echo "</div>";    // close the last question box
if ($q === NUll && $c === NULL && $i === NULL) {
     $errorAnswer = 'Question does not exist';
 } else {
    $errorAnswer = '';
}


?>


<?= $idError ?>
<?= $errorAnswer ?>

I tried the above if statement which is checking for NULLS with == as well and I get the same thing. I also tried this:


  if (!$results) {
   
 $errorAnswer = 'That Id was not found';
} else {
    $errorAnswer = '';
}

Which doesn't work. Doesn't echo anything

Many thanks

Edited by webdeveloper123

You're checking if questionid exists but then saying 'no matching id' instead of 'Id is required'.  That s/b changed

Then you continue to run the script and try to work with the query results that YOU NEVER RAN.  That s/b changed.

In your second block of code you are showing us something BUT WHERE IS IT LOCATED IN THE FIRST BLOCK???

 

3 minutes ago, ginerjm said:

You're checking if questionid exists but then saying 'no matching id' instead of 'Id is required'.  That s/b changed

 

Ok, a minor grammar edit

6 minutes ago, ginerjm said:

Then you continue to run the script and try to work with the query results that YOU NEVER RAN.  That s/b changed.

 

are you referring to $questionId?

7 minutes ago, ginerjm said:

In your second block of code you are showing us something BUT WHERE IS IT LOCATED IN THE FIRST BLOCK???

 

I don't understand. Are you referring to the if statement that checks for NULL

19 minutes ago, ginerjm said:

In your second block of code you are showing us something BUT WHERE IS IT LOCATED IN THE FIRST BLOCK???

 

Oh I think I know what you mean. Your referring to:


  if (!$results) {
   
 $errorAnswer = 'That Id was not found';
} else {
    $errorAnswer = '';
}

Well, it's right there in the first block, You wrote the code:

while(list($q, $c, $i) = $results->fetch(PDO::FETCH_NUM))

 

I wrote that code but I wasn't sure it would work, but I tried it anyway just for completion. The reason I thought it wouldn't work was because I did a print_r($results) and it gave me the sql statement. In other PDO examples it would normally print out the array data. But this just said something like PDO Object. So I thought it wouldn't work because it's an object instead of an array

Instead of showing us two unrelated (?) blocks of code show us the whole script - as much of it that pertains to this conversation - instead of breaking it apart and making us figure it out.   

It'd be easier to handle this if you restructure the code to separate gathering the query results, and displaying your output.  The problem you have currently is trying to determine whether or not you displayed anything after the loop.  That could be done somewhat easily by just adding an extra variable, but it's messy.  Much cleaner to check before trying to output stuff, and that also gives you greater control over the output.

//Assume no results.
$results = [];
$questionId = $_GET['question'] ?? '';
if ($questionId){
    //Only run the query if we have an id.
    $sql = "SELECT q.question, o.choice, q.image 
        FROM questions q 
        JOIN quiz_options o 
          ON q.qid = o.qid 
        WHERE q.qid = :id;";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['id' => $questionId]);

    //Fetch all the result rows
    $results = $stmt->fetchAll(PDO::FETCH_NUM);
}

//If we have any results
if ($results){
    //Display them
    $last_q = 'x';    // a non-existent value
    $choice_num = 0;
    foreach ($results as [$q, $c, $i]){
        if ($q <> $last_q) // starting a new question so close the last div and begin a new one
        {
            if ($last_q <> 'x') // is this the first question? If not, close the last question's box
            {
                echo "</div>";
            }
            echo "<div class='quizContent'>";  // start the new question box
            echo "<p>$q</p>"; // show the question  - figure out later how to prevent repetition (which I did earlier)

            $pathx = "images/db_images/";

            echo '<img class="picture" src="' . $pathx . $i . '">';

            $choice_num = 0;  // new question; new choice count
        }

        $choice_class = 'choice' . $choice_num; // setup the appropriate choice class
        $last_q = $q;   // remember the current question
        //echo "<p>$q</p>"; // show the question  - figure out later how to prevent repetition (which I did earlier)
        echo "<div class='$choice_class'>";   // a box for this choice
        echo "<p>$c</p>";
        echo "</div>";    // close this choice's box
        $choice_num++;    // bump the choice cnt
    }
    echo "</div>";    // close the last question box
} else {
    //Display an error
    $errorAnswer = 'Question does not exist';
}

This does not distinguish between 'ID not passed' and 'ID not found' errors, and I see little reason to do so.  If you wanted to do so though, you could by checking $questionId again in the error code.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.