June 18, 2013

Fetching result isn't working after prepared statement

Jskidd3’s Question:

I’m struggling to write this myself so I will say what I know I need to do and what I have already.

Based on two $_GET[] variables I need to query a database. The values provide me with the table name and the name of the location. From this location field name, I need to extrapolate the whole row.

So, I query the database with this data, however when I try and fetch and print it nothing happens. I need the whole row’s data (in an array?).

I understand my code is ugly. And probably vulnerable to MySQL injection, but I would rather get my PHP right in terms of getting the row into an array before I worry about that.

Rough code I have so far:

$company = strtolower($_GET['company'] . '_a_in_m2f');
$company = mysqli_real_escape_string($mysqli, $company);

$stmt = $mysqli->prepare("SELECT * FROM " . $company ." WHERE `name` = '?'");
$stmt->bind_param('s', $stop);

$stop = $_GET['stop'];

$stmt->execute();

$stmt->bind_result($therow);

while ($stmt->fetch()) {
    printf("%s %s n", $therow);
}

Thanks

There are a few problems here:

  1. You don’t quote the variable you are going to bind (as mentioned before…);
  2. You don’t escape the table name, instead you should check it against a white-list and quote it in backticks if necessary;
  3. You don’t bind the results to an array but to individual variables. You would be better of just fetching rows from the result using fetch_row() in this case.

You do not need to bind the ? with quotes. Remove quotes from '?' to simply ?

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!