Burning Hippo
Burning Hippo

Reputation: 805

PHP mySQL variable access

Say I do something like this:

//get unit id
$query = "SELECT id FROM units WHERE unit_name = '".$unit."'";

$id = mysqli_query($con, $query);

$unit_id = 0;

while ($row = mysqli_fetch_array($id))
{
    $unit_id = $row['id'];
}

why is $unit_id not changed outside of the while loop?

What happens is this: I have a selection dropdown with a list of units and when on is clicked that php code is fired (along with other code in the file) and it makes a hidden input field with the id in it. I unhide the id and find that the id is not correct. What is displays, rather, is, say I click the first option, 1001, second option, 1002, third, 1003, etc. These ids do not correspond to my database at all, though the units begin at 1001 in the database. Because of all of that I assumed that my $unit_id just wasn't getting read properly and that somehow PHP didn't let one access the variable outside of a while loop in that way. I see now that assumption was premature. Thanks.

Upvotes: 0

Views: 110

Answers (3)

Burning Hippo
Burning Hippo

Reputation: 805

What happens is this: I have a selection dropdown with a list of units and when on is clicked that php code is fired (along with other code in the file) and it makes a hidden input field with the id in it. I unhide the id and find that the id is not correct. What is displays, rather, is, say I click the first option, 1001, second option, 1002, third, 1003, etc. These ids do not correspond to my database at all, though the units begin at 1001 in the database. Because of all of that I assumed that my $unit_id just wasn't getting read properly and that somehow PHP didn't let one access the variable outside of a while loop in that way. I see now that assumption was premature. Thanks.

Upvotes: 0

Actually it changes.

Two cases for this..

  • Maybe your $row['id'] value is also 0.

[or]

  • Your query returning (0 results) and it is not entering the loop.

Upvotes: 1

user399666
user399666

Reputation: 19879

Two possible explanations:

  1. Your query is failing but you have error reporting disabled (nor are you outputting/logging MySQL errors).
  2. There is no unit_name with that name.

If you don't have error reporting enabled by default, try putting:

ini_set('display_errors',1); 
error_reporting(E_ALL);

at the top of your script (in a dev enviornment, error reporting should be enabled by default, by the way). Also, you can try using:

$id = mysqli_query($con, $query) or trigger_error(mysqli_error($con));

to view any MySQL errors that may have occurred.

Upvotes: 1

Related Questions