Reputation: 15
Currently I'm developing a mobile library app, which will need to check out books. I would like to be able to check how many books are checked out compared to the total available. I am struggling to covert the mysqli_query
result into an integer to compare to the amount of total books available. I apologize if this is an easy answer (I'm very new), as I did quite a bit of digging and could't find an answer that I could adapt to fit my scenario.
<?php
require "conn.php";
$userID = "2";
$book_id = "1";
$mysql_qry = "select COUNT(*) from books_checked_out where bookID=$book_id";
$result = mysqli_query($conn, $mysql_qry);
//Somewhere here convert the $result into $quantity, which would be an int
if($quantity >= 2) {
echo "more books checked out than in stock";
}
else if($quantity < 2) {
echo "less books checked out than in stock";
}
?>
Any help is appreciated, thank you!
Upvotes: 1
Views: 9053
Reputation: 13
This should work. Please be aware of SQL Injection. Also, I took a wild guess at the DB for in stock books, that will need to be changed.
require "conn.php";
$userID = "2";
$book_id = "1";
$mysql_qry = "SELECT
(SELECT COUNT(*) FROM books_checked_out WHERE bookID='" . $book_id . "') as num1,
(SELECT COUNT(*) FROM books_in_stock WHERE bookID='" . $book_id . "') as num2";
$result = mysqli_query($conn, $mysql_qry);
$quantity = mysqli_fetch_assoc($result);
if($quantity['num1'] >= 2) {
echo "more books checked out than in stock";
}
else {
echo "less books checked out than in stock";
}
//If you want to see the difference you can do something like this.
echo "Checked Out" . $quantity['num1'] . '<br/>';
echo "In Stock" . $quantity['num2'] . '<br/>';
Upvotes: 0
Reputation: 11
try using
intval("0".$row['quantity'])
This which will convert your quantity to integer.
Upvotes: 0
Reputation: 725
This will work
$result = $result->fetch_array();
$quantity = intval($result[0]);
Upvotes: 3
Reputation: 1043
You can do something like this:
$userID = "2";
$book_id = "1";
$mysql_qry = "select COUNT(*) as quantity from books_checked_out where bookID=$book_id";
$result = mysqli_query($conn, $mysql_qry);
$row = mysqli_fetch_array($result, 'MYSQLI_ASSOC'); // Use something like this to get the result
$quantity = $row['quantity'];
if($quantity >= 2) {
echo "more books checked out than in stock";
}
else if($quantity < 2) {
echo "less books checked out than in stock";
}
?>
Upvotes: 0