Return the result of Mysqli execute() - php

I have a DELETE query, and I want to return the result of the execution. How can I do it ?
My php code:
Function delete_cat($category){
$stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
$stmt->bind_param($category);
$stmt->execute();
$stmt->close();
//return should be here
}

So $stmt->execute(); => returns a bool value, whether your query was successfully executed or not, and you can do it simply like this:
function delete_cat($category){
$stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
$stmt->bind_param($category);
$result = $stmt->execute();
$stmt->close();
return $result;
}
If you needed to get the count of the deleted elements, you can use mysqli_stmt_affected_rows, something like this:
function delete_cat($category){
$stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
$stmt->bind_param($category);
$stmt->execute();
$result = $stmt->affected_rows;
$stmt->close();
return $result;
}

function delete_cat($category){
$stmt = $mysqli->prepare("DELETE category, products FROM category INNER JOIN products WHERE category.id = ? AND product_cat = category.category_name ");
$stmt->bind_param($category);
$result = $stmt->execute(); // store the return of the method into a variable here so we can return it later
$stmt->close();
return $result // would return if the rows have been deleted or not.
return $mysqli->affected_rows; // would return the amount of rows deleted
}
If you want to get the amount of rows that have been deleted you use affected_rows, if you want to just get the result if the SQL query was performed succesfull, simply store the return of $stmt->execute into a variable and return that.
http://php.net/manual/en/mysqli-stmt.affected-rows.php
http://php.net/manual/de/mysqli-stmt.execute.php

Related

Need help in mysql RIGHT join

here is mytable structure?
table:category
id name
1 x
2 y
table:subproduct
id cat_id name myval
1 1 xyz test
2 1 abc test2
So basically i want to select all values from subproduct for each id of category table and show it in array in php?
here is my PHP code
$sqlnew = "SELECT c.cat_id,c.cat_title,s.sub_id,s.sub_title,s.store_cashback FROM category c JOIN subproduct s ON c.cat_id = s.pid";
$pdo = getDB();
$stmtnew = $pdo->query($sqlnew);
$resultnew = $stmtnew->fetchAll();
var_dump($resultnew);
I am using PHP PDO.
If you want to get all items with a particular category ID, you should do something like this:
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $category_id, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
You could use this to individually fetch each category ID and build an array like this:
$statement = $pdo->query("SELECT id FROM category;");
$ids = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
$data = array();
foreach($ids as $id)
{
$statement = $pdo->prepare("SELECT * FROM subproduct INNER JOIN category " .
"ON category.id = subproduct.cat_id WHERE category.id = :id");
$statement->bindValue(":id", $id, PDO::PARAM_INT);
$statement->execute();
$data[$id] = $statement->fetchAll();
}
print_r($data);
I am not crazy about this because it looks inefficient and I don't like looping through queries. You could also request all the data at once and then rearrange it:
$statement = $pdo->query("SELECT * FROM subproduct");
$data = array();
while($subproduct = $statement->fetch(PDO::FETCH_ASSOC))
{
$id = $subproduct['cat_id'];
if (!isset($data[$id])
$data[$id] = array();
array_push($data[$id], $subproduct);
}
print_r($data);
I don't really like this either because using PHP to sort MYSQL data feels wrong since that is MYSQL's job. I could have requested MYSQL sort the data, but then the data would still need to be broken up into a multi-dimensional array, so I am not sure that helps.

PHP inner join categories

I got stuck on something with PHP.,
I am trying to JOIN two tables
$statement = $database->prepare("SELECT categories.name as category_name ,pages.name as page_name FROM categories INNER JOIN pages ON categories.name = pages.category");
$statement->execute();
$fetch = $statement->fetchAll(PDO::FETCH_ASSOC);
$returnValues = '';
foreach($fetch as $item){
if(isset($returnValue[$item->category_name]){
array_push($returnValue[$item->category_name], $item->page_name);
}else{
$returnValue[$item->category_name][] = $item->page_name;
}
}
echo "<pre>";
print_r($returnValue);
Basically I want to get an array which got the category name and behind it all the pages that belongs to that category. now on this PHP code, I get plenty of array which everyone holds category name and one page.. and I can't sort it out , thanks.
Alias the category name so that you can tell it apart from the page name. This query will select the category name and all columns from table pages.
$statement = $database->prepare("SELECT categories.name AS category_name, pages.* FROM categories INNER JOIN pages ON categories.name = pages.category");
$statement->execute();
$fetch = $statement->fetchAll(PDO::FETCH_ASSOC);
Group each row by category name. Change $row['id'] to whatever you use as the primary ID for table pages.
$categoryPages = array();
foreach ( $fetch as $row ) {
$categoryPages[$row['category_name']][$row['id']] = $row;
}
print_r($categoryPages);
This is modifications to your original code, should basically do what you want, there might be some small syntax changes needed.
$statement = $database->prepare("SELECT categories.name as category_name ,pages.name as page_name FROM categories INNER JOIN pages ON categories.name = pages.category");
$statement->execute();
$fetch = $statement->fetchAll(PDO::FETCH_ASSOC);
$returnValues = '';
foreach($fetch as $item){
if(isset($returnValue[$item->category_name]){
array_push($returnValue[$item->category_name], $item->page_name);
}else{
$returnValue[$item->category_name][] = $item->page_name;
}
}
echo "<pre>";
print_r($returnValue);
Something like this might work for you... I know it is not perfect and there are something thing missing in the query prepare, but it should be enough to get you going.
The compiled array should be formatted the way you want.
$statement = $database->prepare("SELECT categories.name FROM categories");
$statement->execute();
$fetch = $statement->fetchAll(PDO::FETCH_ASSOC);
$compiled = '';
foreach($fetch as $category){
$statement = $database->prepare("SELECT page.name FROM pages WHERE pages.category = $category");
$statement->execute();
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($pages as $page)
array_push($compiled[$category], $page);
}
}
echo "<pre>";
print_r($compiled);

"SELECT * ..." mysqli parametrized query - how to store results without binding?

I want to store mysqli query results to array.
My code so far looks like this:
function get_nearby_users($Id, $MaxDistance, $RowLimit, $RowLimitOffset)
{
try
{
$query = "SELECT
others.*,
Distance(me.Latitude, me.Longitude, others.Latitude, others.Longitude) as Distance
from
Users me
join
Users others
where
me.Id = ?
and
others.Id != ?
having Distance < ?
limit ?,?
";
$stmt = $this->link->prepare($query);
$stmt->bind_param('iiiii', $Id, $Id, $MaxDistance, $RowLimitOffset, $RowLimit);
$stmt->execute();
// how to fill $rows_array?
}
catch(Exception $exc)
{
// ...
}
return $rows_array;
}
How can I put my results to array when my SQL contains something like "SELECT *"?
All tutorials with parametrized queries use bind_result function, but I don't want to create variables for all fields and bind them. There is no other way?
You do not need to use bind_result to store the record set.
Just use fetchAll() to store result set rows as an array.
$rows_array = $stmt->fetchAll();
I have modified your code. Use this:
function get_nearby_users($Id, $MaxDistance, $RowLimit, $RowLimitOffset)
{
try
{
$query = "SELECT
others.*,
Distance(me.Latitude, me.Longitude, others.Latitude, others.Longitude) as Distance
from
Users me
join
Users others
where
me.Id = ?
and
others.Id != ?
having Distance < ?
limit ?,?
";
$stmt = $this->link->prepare($query);
$stmt->bind_param('iiiii', $Id, $Id, $MaxDistance, $RowLimitOffset, $RowLimit);
$stmt->execute();
$rows_array = $stmt->fetchAll(); // store result set rows as an array
}
catch(Exception $exc)
{
// ...
}
return $rows_array;
}

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;

Mysqli select multiple queries

I'm trying to select one query by using the user_id to get the categories specific to the user and then from there use the results from the first query to select data from a second table in a second query. The data from the second query I would like to display in a drop down menu. Is there any easy way to do this? I'm new to using mysqli so please bear with me.
I have the following function but it's not displaying anything in the dropdown menu, it is showing the drop down menu though.
function get_classes($mysqli) {
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->prepare("SELECT category_id
FROM questions WHERE user_id = ?")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows>0) {
$stmt->bind_result($category_id);
$stmt->fetch();
if($result = $mysqli->prepare("SELECT category_id, category_name
FROM category WHERE category_id = ?")) {
$result->bind_param('s', $category_id);
$result->execute();
$result->store_result();
}
}
echo "<select id='classes' name='classes'>";
while ($row = $result->fetch_assoc()) {
unset($user_id, $category_name);
$category_id = $row['category_id'];
$category_name = $row['category_name'];
echo '<option value="'.$category_id.'">'.$category_name.'</option>';
}
echo "</select>";
}
}
}
I'm calling the function from another page with the following code:
<?php
get_classes($mysqli);
?>
You can make all via one sql query:
SELECT c.category_id, c.category_name
FROM questions q
INNER JOIN category c ON c.category_id = q.category_id
WHERE q.user_id = ?
Alternatively, you could join them instead, then the normal fetching. Example:
function get_classes($mysqli) {
if(!isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
return false;
}
$user_id = $_SESSION['user_id'];
$sql = '
SELECT
category.category_id,
category.category_name
FROM category
JOIN questions
ON questions.category_id = category.category_id
WHERE questions.user_id = ?
';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->bind_result($category_id, $category_name);
// printing
echo '<select name="classes" name="classes">';
while($row = $stmt->fetch()) {
echo '<option value="'.$category_id.'">'.$category_name.'</option>';
}
echo '</select>';
}

Categories