2

When I save a result of a SQL query in a variable (in the code in $test2), the variable is empty outside the while loop. Why?

Generally defining varibales inside that loop works (see $test1). And the SQL query works too.

$connection = new mysqli($servername,$username,$password,$dbname) or die("Error: " . mysqli_error($connection));
$query = "SELECT * FROM Table ORDER BY `id` ASC";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_object($result)) {
    $test1 = "some text";
    $test2 = $row->id;
    echo $row->id // Output is the id -> works
}
echo $test1; // Output is "some text" -> works
echo $test2; // Output is nothing -> doesn't work. Why?
1
  • If you want to use something outside a loop and not $tests, consider using an array $test = array(); created before the loop, then add whatever in your loop as $test[] = array("id"=>$row->id,"foo"=>"that"); Commented May 28, 2014 at 12:44

2 Answers 2

2

You are overwritting the variables in each loop itteration. Save them all to an array and look at the results:

while($row = mysqli_fetch_object($result)) {
    $test1[] = "some text";
    $test2[] = $row->id;
    echo $row->id // Output is the id -> works
}
print_r($test1); 
print_r($test2);
Sign up to request clarification or add additional context in comments.

Comments

2

$row = mysqli_fetch_array($result) return an array

and you are using $test2 = $row->id; as object

2 Comments

mysqli_fetch_object, as the name implies, returns an object.
@Marek OP edited question many times, before it was mysql_fetch_array

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.