简体   繁体   中英

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). It SHOULD return an integer however keeps returning NULL. My IDE also underlines the $stock variable as undefined within bind_result, however I have followed online examples of this perfectly. 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.

In my view this could work (PDO not 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. If there is more than one result use fetchAll() instead of fetch().

Additionally it's not:

$stmt->bind_param();

it has to be:

$stmt->bindParam();

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

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