1

This is how I presently fetch from the DB:

if ($stmt = $mysqli->prepare ( "SELECT fname,lname from $table_name 
where cno >=? LIMIT 50" ))
    {
        $stmt->bind_param ( "i", $cno); 
        $stmt->execute ();
        $stmt->bind_result ($fname,$lname); 
        $arrayUsers = array();

        while ($stmt->fetch())
        {
            if (isset ($fname))
            {
                $arrayUsers[] = array(
                        "fname" => $fname,
                        "lname" => $lname);

}
}
$stmt->close ();
        }
        $mysqli->close ();

and it works great. But if I change my select to SELECT * from... my bindings fail. Does that mean if I have a large number of fields, I will still have to specify each and every field or is there a way to use select *?

---- updated ---

if (empty($arrayUsers))
    {
        return 0;
    }
    else
    {
        return $array;
    }
Ryan
  • 9,821
  • 22
  • 66
  • 101

2 Answers2

2

SELECT * is never a good idea.

It's better to be explicit.

If you had only 2 columns it would have worked.

That's how bind_result works the number variable needs to match the columns.

In addition to that it needs to be in the same order

Edit: Example in pdo:

if ($stmt = $pdo->prepare ("SELECT * from `$table_name` where cno >=:cno LIMIT 50" )){
    $stmt->execute([':cno'=>$cno]);
    $arrayUsers = $stmt->fetchAll();
    $stmt->close();
}
$pdo->close();
meda
  • 45,103
  • 14
  • 92
  • 122
  • Thanks for replying! If just have a few columns I don't care, I have some tables with a lot more than 2 or 10 and I'm just curious as to how I can get a `select *` instead of explicitly calling each column. Not sure if its even possible... – Ryan Mar 27 '15 at 20:23
  • 1
    Its possible if you know in advance how many column you are fetching and bind all variables. This is dangerous your code will break if you ever add or drop column – meda Mar 27 '15 at 20:29
  • Voted your answer up. I realize the pitfalls of a `select *` but I just wanted to know how it could be done / if it could be done and Jay answered my question. Thanks again :) – Ryan Mar 27 '15 at 20:33
  • 1
    @Ryan yeah thats what you need to achieve it, also PDO can do it easily if you dont mind switching good luck – meda Mar 27 '15 at 20:34
  • Thanks! Got an example with PDO? – Ryan Mar 27 '15 at 21:43
2

If you need to perform a selection of all of the columns:

SELECT * FROM `table`

You would use PHP's get_result() rather than bind_result().

bind_result() is better when you're specifying each column that you're retrieving where get_result() will allow you to work with a more generic return of data from your tables.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119