简体   繁体   English

绑定参数和绑定结果不返回项目-PHP MySql

[英]Binding parameters and binding results does not return item - PHP MySql

The following function takes as a parameter 'device' of type string and uses it to query my stock table to see whats in stock for that device (UNIQUE constraint existed for each device). 以下函数将类型为string的参数“ device”用作参数,并使用它查询我的库存表以查看该设备的库存量(每个设备都存在UNIQUE约束)。 It SHOULD return an integer however keeps returning NULL. 它应该返回一个整数,但是始终返回NULL。 My IDE also underlines the $stock variable as undefined within bind_result, however I have followed online examples of this perfectly. 我的IDE也强调在bind_result中未定义的$ stock变量,但是我已经很好地遵循了在线示例。 Where am I going wrong? 我要去哪里错了?

function get_stock_level($device) {
GLOBAL $db;
$sql = 'SELECT in_stock
    FROM stock
    WHERE device = ?';
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $device);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($stock);
return $stock;
}

PS Ive also tried initially defining $stock but the function simply returns the initial assignment value rather than the binded result item. PS Ive也尝试过最初定义$ stock,但是该函数仅返回初始赋值而不是绑定的结果项。

In my view this could work (PDO not MySQLi): 我认为这可能有效(PDO不是MySQLi):

function get_stock_level($device) {
GLOBAL $db;
$sql = 'SELECT in_stock
FROM stock
WHERE device = :device';
$stmt = $db->prepare($sql);
$stmt->bindValue(':device', $device,PDO::PARAM_STR);
$stmt->execute();
$stock = $stmt->fetch();
return $stock;
}

I used prepare this way, you can store the result directly into a new var. 我使用这种方式进行准备,您可以将结果直接存储到新的var中。 If there is more than one result use fetchAll() instead of fetch(). 如果有多个结果,请使用fetchAll()而不是fetch()。

Additionally it's not: 此外,它不是:

$stmt->bind_param();

it has to be: 它一定要是:

$stmt->bindParam();

MySQLi: MySQLi:

function get_stock_level($device) {
GLOBAL $db;
$sql = 'SELECT in_stock
FROM stock
WHERE device = ?';
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $device);
$stmt->execute();
$stmt->bind_result($stock);//bind result variables
$stmt->fetch();
$stmt->close();//close statement
$db->close();//close connection
return $stock;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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