$stmt->fetch() not enter in while - php

I have write simple code in PHP, I'm a beginner in this language.
This is my code:
$id = "prova";
$query = "SELECT DISTINCT id_item FROM Users WHERE id = ? LIMIT 1 ";
if ($stmt = $conn->prepare($query))
{
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($result);
while ($stmt->fetch()) {
$id_item = (int) $result;
}
}
My problem is that the cycle while is never executed, but I don't understand why.
Thanks in advance.

Related

Replace value in array with result of mysqli_query

I'm having some trouble with php coding. What I want to do is following:
Create an array ($rows) and fil it with the results of a mysqli_query ($query1) --> OK
for each element in that array, replace the value of a certain key (pilot_rule_id) with the result of another mysqli_query ($query2). (the second query will return one row, since the id of the pilot table is the primary key).
So far I have
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$rows = array();
$query1 = mysqli_query($con, "SELECT * FROM pilot_time_schedule WHERE pilot_id='$id'");
while($r = mysqli_fetch_assoc($query1)) {
$rows[] = $r;
}
foreach($rows as $pilotRuleId) {
$pilotRuleId->$pilot_rule_id;
$query2 = mysqli_query($con, "SELECT name FROM pilot_rule WHERE id='$piloteRuleId'");
while($r = mysqli_fetch_assoc($query2)) {
$result[] = $r;
}
// Don't know how to continue from here
You can something like this:
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT * FROM pilot_time_schedule WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
$stmt = $con->prepare('SELECT name FROM pilot_rule WHERE id=?');
$stmt->bind_param('s', $row['pilot_rule_id']);
$stmt->execute();
// replace with the `name` returned from the above statement.
$row['pilot_rule_id'] = $stmt->get_result()->fetch_row()[0] ?? null;
}
However, you really should learn about SQL joins instead. Using SQL joins you can avoid N+1 queries to the database.
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT pilot_time_schedule.*, pilot_rule.name
FROM pilot_time_schedule
JOIN pilot_rule ON pilot_rule.id=pilot_time_schedule.pilot_rule_id
WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
echo $row['name']; // contains the name from pilot_rule
}

Populate an Array with Results from mySql Query

I am having a problem with creating an array from the values received from a mySql query. I have the following code but I can't populate the array with the returned values. I assume that there is a problem with the while statement. Can anybody help me out?
$return_arr = array();
$searchTerm=$_GET['searchTerm'];
$query = "SELECT Actor.FirstName, Actor.LastName FROM Actors WHERE Actor.ActorFirstName LIKE '%$searchTerm%' ";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($firstName, $lastName);
while($row = mysql_fetch_assoc($stmt) {
$return_arr[] = $row['FirstName'];
}
change your while loop
while($stmt->fetch())
{
$return_arr[] = $firstName;
}

Error with php function in "mysqli select" prepare statement

I create a function to call some data from database with left-join and prepare statement.
Here is the sketch of the php function:
function getStock()
{
global $mysqli;
$stmt = $mysqli->prepare
("SELECT products.`product_name`, product_category.`price`
FROM products
LEFT JOIN product_category
ON products.product_category_id = product_category.id
WHERE products.id = ?");
$id=3;
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->fetch();
return $stmt;
In the view page I do this:
$resultsTicket = getStock();
$results = $resultsTicket->num_rows;
var_dump($results);
if ($resultsTicket->num_rows > 0) {
while($resultsTicket->fetch()){
However in the var_dump I only get int(0)
I don't know anymore how to find the error there beside the var_dump. Please help me in the above code. Thank you!
[UPDATE]
$query = "SELECT products.`product_name`, product_category.`price`
FROM products
LEFT JOIN product_category
ON products.product_category_id = product_category.id
WHERE products.id = 3;
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($product_name, $price);
//$stmt->fetch();
while ($stmt->fetch()) {
printf ("%s (%s)\n", $product_name, $price);
}
$stmt->close();}
return $stmt;
}
In the code above I get one data/row from database.
The problem is that you are executing and fetching within the function but returning the statement. There are two possible changes you can make.
Execute and fetch within the function, then loop through the results and return an array representing the results.
Return the statement from the function and perform the execute and fetch where you are using the result of the function.
I think you got enough help with the guys, If you still not sure how to code it, here you go:
Single record
$query = "SELECT products.`product_name`, product_category.`price`
FROM products
LEFT JOIN product_category
ON products.product_category_id = product_category.id
WHERE products.id = 3";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($product_name, $price);
$row = array();
while ($stmt->fetch()) {
$row = array('product_name'=>$product_name, 'price'=>$price);
}
$stmt->close();
}
return $row;
Multiple Record:
$query = "SELECT products.`product_name`, product_category.`price`
FROM products
LEFT JOIN product_category
ON products.product_category_id = product_category.id
WHERE products.id = 3";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($product_name, $price);
$rows = array();
while ($stmt->fetch()) {
$rows[] = array('product_name'=>$product_name, 'price'=>$price);
}
$stmt->close();
}
return $rows;
Example in PDO:
$query = "SELECT products.`product_name`, product_category.`price`
FROM products
LEFT JOIN product_category
ON products.product_category_id = product_category.id
WHERE products.id = 3";
if ($stmt = $pdo->prepare($query)) {
$stmt->execute();
$rows = $stmt->fetchAll();
}
return $rows;

how do i implement update i pdo for the following mysql code?

here is my mysql code and equivalent pdo code i need to know what is wrong
$id = $_POST['id'];
$query1=mysql_query("SELECT Quantity,id FROM `yumyum`.`food` where `food`.`id` LIKE $id");
$r = array();
while($r = mysql_fetch_assoc($query1)) {
$output = $r['Quantity'];
echo $output;
$query2=mysql_query("UPDATE food SET Quantity = Quantity - 1 where `food`.`id` LIKE ".$r["id"]);
PDO code
$stmt = $db->prepare("SELECT * FROM yuymuym WHERE id=:id AND Quantity=:Quantity");
$stmt->execute(array($id, $Quantity));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
How about this. I don't know what $_POST['id'] is so you have to figure the rest youself. It updates every item with id in $ids array. So this updates items with id 1,2,3,4 and 5.
$db = new PDO('mysql:host=localhost;dbname=yumyum', 'username_here', 'password_here');
$ids = array(1,2,3,4,5);
foreach($ids as $id){
$stmt = $db->prepare("SELECT Quantity, id FROM `food` WHERE `food`.`id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
if($row){
//uncomment to see $row content
//var_dump($row);
$rowId = (int)$row['id'];
$rowQuantity = (int)$row['Quantity'];
echo $rowQuantity;
$ustmt = $db->prepare("UPDATE `food` SET `Quantity` = `Quantity` - 1 WHERE `food`.`id` = :id");
$ustmt->bindParam(':id',$rowId);
$ustmt->execute();
}else{
var_dump($stmt->errorInfo());
}
}
But PDO basics:
Query (Works with select, insert, update, everything else):
$id = (int)$_POST['id'];
$else = $_POST['string'];
// Connect to database
$db = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
// First we prepare our query
$stmt = $db->prepare("... WHERE `id` = :id AND `something` = :else");
// We bind values to our prepared query
$stmt->bindParam(':id',$id);
$stmt->bindParam(':else',$else);
// We execute our query
$success = $stmt->execute();
// If we want to fetch only one row:
$row = $stmt->fetch();
echo $row['id'];
// If we want to fetch all rows:
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo $row['id'];
}
These are very basics, if you don't understand what is really happening here, you should learn some more.

mysqli if result > 0 do something

How would i do this using mysqli?
$SQL = mysql_query("SELECT username FROM users WHERE username = '$new_username'");
$result = mysql_num_rows($SQL);
If(!$result > 0) {
echo...
I tried:
$SQL = $mysqli->query("SELECT username FROM users WHERE username = '$utilizator");
$rezultat->num_rows($SQL);`
But I dont get any result.
You have started the query with $SQL .. continue with it as the object will be in that variable:
$SQL = $mysqli->query("SELECT username FROM users WHERE username = '$utilizator'");
$num = $SQL->num_rows();
if($num){
// run your code here
}
you have to call store_result() after execution.
php.net has a wonderful php doc: http://www.php.net/manual/de/mysqli-stmt.num-rows.php
for example:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
$number_of_rows = $SQL->num_rows;

Categories