0

I just created a page that could get the name of the students in 2 schools using their school name(This is just for my practice). But when i execute the following code i don't get the name of the top student in each school whose name is at top in the database, But i get the rest of the list.

<?php
require 'connect.php';

if(isset($_GET['school']))
{
    $school = trim($_GET['school']);
    $people = $db->prepare("SELECT id, name FROM users WHERE school = ? ");
    $people->bind_param('s', $school);
    $people->execute();
    $people->bind_result($id, $name);

    if(!$people->fetch())
    {
        echo "Invalid School Name!!";       
    }   
    else
    {
        while($people->fetch())
        {
            echo 'ID. ',$id, ' ',$name,'<br>';
        }
    }
}
?>

This problem only occurs when i use if and else statements to output error message "Invalid School Name!!". If i just use the while loop to fetch data, i get the full list. Please tell me the why i miss the first name and a solution for this. Thank you.

2
  • 1
    @Prix No, if (!$people->fetch()) is correct (partially) Commented Sep 14, 2014 at 23:45
  • Can you choose an answer if you're problem is solved? Thx Commented Sep 18, 2014 at 10:02

2 Answers 2

2

Your first test does $people->fetch(). If the answer is not false, then it does it again and execute the code in the loop until the last element. So your if is the problem because it pass the first element while doing the test.

To solve this, just remove your if-condition: if the query doesn't find any people,

while( $people->fetch() ) {
 Do_something(); }

...will be jumped and everything will work as expected.

To add the error message, use a try/catch or check whether you entered the loop or not with a boolean (maybe there are other methods, though).

Sign up to request clarification or add additional context in comments.

1 Comment

Not a try/catch, because it wouldn't throw an exception (it would return false). Instead, just call fetchAll() once and test the count() of the resultant array. If it's zero, show the error, if it's nonzero, do a foreach over the array to output data.
0

Change the conditional to test against the result

$people->execute();
$people->store_result();
$people->bind_result($id, $name);

if($people->num_rows == 0)
{
    echo "Invalid School Name!!";       
}   
else
{
    while($people->fetch())
    {
        echo 'ID. ',$id, ' ',$name,'<br>';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.