简体   繁体   中英

PHP: Mysqli prepared statement with “select *”

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;
    }

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM