PHP: Mysqli prepared statement with “select *”

情到浓时终转凉″ 提交于 2019-12-01 10:31:11

问题


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

回答1:


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.




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


来源:https://stackoverflow.com/questions/29309453/php-mysqli-prepared-statement-with-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!