Issues with mysqli select all

最后都变了- 提交于 2021-02-05 11:17:48

问题


I'm using MySQLi connection and I have the following code, i am trying to select all columns for a row defined by inventory id from a database table but i can't get this to work. Am i doing it the totally wrong way? I want to be able to use things like $row['general_cleanliness'] in my code following the select query.

$getScheduleCondition = $db->prepare("SELECT * FROM inventories WHERE inventory_id = ? LIMIT 1",)){
$getScheduleCondition->bind_param("i", $inventory);
$row = $getScheduleCondition->fetch_array();
$getScheduleCondition->close();

$inventory is defined as a number, i know this works. Any help is appreciated, sorry if this seems like a basic question, just a little confusing!

EDIT: For everyone telling me i'm using PDO, i'm not:

$db = new mysqli('localhost', 'cl52-system', 'PASS', 'cl52-system');
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

回答1:


You are forgetting two things. First you need to execute the query. You can do this with your_stmt_object->execute() (docs). Your stmt-object doesn't have a method fetch_array() though, so you first need to pull a mysqli_result out of it with ->get_result() (docs) and then you can use fetch_array() as you want.

$getScheduleCondition = $db->prepare("SELECT * FROM inventories WHERE inventory_id = ? LIMIT 1");
$getScheduleCondition->bind_param("i", $inventory);
$getScheduleCondition->execute(); //You need to execute the query
$row = $getScheduleCondition->get_result()->fetch_array(); //From stmt to mysql_result to array
$getScheduleCondition->close();

If you don't need to use the array, it might be easier to use ->fetch() (docs) and ->bind_result() (docs) instead.

$getScheduleCondition = $db->prepare("SELECT * FROM inventories WHERE inventory_id = ? LIMIT 1");
$getScheduleCondition->bind_param("i", $inventory);
$getScheduleCondition->bind_result( $column1, $column2, $column3, $etc );
$getScheduleCondition->execute(); //You need to execute the query
$getScheduleCondition->fetch(); //Now the first row is in the variables defined above
echo $column1; //<-- see?
$getScheduleCondition->close();



回答2:


The parameter your passing is identified as "i" (named parameter), but in your query only have ?, change your bind_param to ":i" and change the ? to :i in your query.

    $getScheduleCondition = $db->prepare("SELECT * FROM inventories WHERE inventory_id = :i LIMIT 1",)){
    $getScheduleCondition->bind_param(":i", $inventory, PDO::PARAM_INT);
    $getScheduleCondition->execute(); // based on Sumurai8 comment, this is missing
    $row = $getScheduleCondition->fetch_array();
    $getScheduleCondition->close();

also, the PDO:PARAM_INT explicitly sets the parameter to an integer.



来源:https://stackoverflow.com/questions/20933978/issues-with-mysqli-select-all

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