John Beasley
John Beasley

Reputation: 3071

MYSQLi PHP function fetch array

I am trying to retrieve a zone by running a PHP function based off of a place that has already been submitted.

Using FORM method GET, after submission, the variable that I am retrieving is:

 $place = mysqli_real_escape_string($_GET['place]);

The variable immediately after is zone:

 $zone = getZone($pol);  // here is the PHP function call

Above both of these variables is the function getZone, which looks like this:

 function getZone($place)
 {
   $searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
   $result = mysqli_query($dbc, $searchZone);
   $row = mysqli_fetch_array($result);
   return $row['ZONE'];  
 }

I can run the query in the database, and it returns the ZONE.

Now, the mysqli_fetch_array, which normally works for me, is failing to produce the result from the query.

Does anyone see what is wrong?

Upvotes: -2

Views: 96

Answers (3)

John Beasley
John Beasley

Reputation: 3071

I figured it out, thanks to the assistance of Marc B. I took into account that I was not providing my connection string, so I added it to the file. Problem is, I needed to add it to the actual function, like so:

 function getZone($place)
 {
   include ("../include/database.php");
   // then the rest of the code

After I included the database connection, I am now able to retrieve the zone.

Upvotes: 0

user2801966
user2801966

Reputation: 468

This might help

  //Assuming $dbc as connection variable
  function getZone($dbc,$place)
   {
     $searchZone = "SELECT ZONE FROM zones WHERE PLACE = '".$place."'";
     $result = mysqli_query($dbc, $searchZone);
     $row = mysqli_fetch_array($result);
     return $row['ZONE'];  
   }
   include 'path/to/connectionfile';//Only if you haven't  already  done  that 
   $zone = getZone($dbc,$pol); 

Upvotes: 2

Marc B
Marc B

Reputation: 360702

You've forgotten about PHP's variable scope rules:

$result = mysqli_query($dbc, $searchZone);
                       ^^^^---- undefined

Since $dbc is undefined in the function, you're using a local null handle, which is invalid. If you'd had ANY kind of error handling in your code, you'd have been told about the problem.

Try

global $dbc;
$result = mysqli_query(...) or die(mysqli_error($dbc));

instead. Never assume success. Always assume failure, check for that failure, and treat success as a pleasant surprise.

Upvotes: 1

Related Questions