Error with php function in "mysqli select" prepare statement - php

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;

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
}

Return the result of Mysqli execute()

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

Alternate query using if statement in PHP

I'm trying to run an alternate query if the initial query fails (it does because the id I'm searching for in this instance only exists in one of the databases being joined) using an if statement and I've constructed it like so:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php/link_costreport_2013.php');
$id = $_GET['id']; //ID # For page/query
if($query = $link->prepare("SELECT locale.id, locale.provider_num, locale.provider_name, locale.state, locale.city,
finstat_ca.coh_and_banks, finstat_ca.temp_investments, finstat_ca.notes_receivable, finstat_ca.accounts_receivable, finstat_ca.other_receivables,
finstat_ca.afun_and_ar, finstat_ca.inventory, finstat_ca.prepaid_expenses, (finstat_ca.other_cur_assets + finstat_ca.due_from_other_funds) as other_cur_assets, finstat_ca.total_current_assets,
finstat_fa.total_fixed_assets,
finstat_olta.investments, (finstat_olta.dep_on_leases + finstat_olta.due_from_owners_officers + finstat_olta.other_assets) as all_olta, finstat_olta.total_other_assets, finstat_olta.end_assets,
finstat_cl.accounts_payable, finstat_cl.salaries_wages_fees_payable, finstat_cl.payroll_taxes_payable, finstat_cl.notes_loans_payable, finstat_cl.deferred_income, finstat_cl.total_current_liabilities,
(finstat_cl.total_current_liabilities - (finstat_cl.accounts_payable + finstat_cl.salaries_wages_fees_payable + finstat_cl.payroll_taxes_payable + finstat_cl.notes_loans_payable + finstat_cl.deferred_income)) as all_other_cl,
finstat_ltl.mortgage_payable, finstat_ltl.notes_payable, finstat_ltl.unsecured_loans, finstat_ltl.other_long_term_liabilities, finstat_ltl.total_long_term_liabilities,
finstat_talfb.total_fund_balance, finstat_talfb.total_lia_plus_fb
FROM `locale`
INNER JOIN `finstat_ca`
ON locale.id = finstat_ca.id
INNER JOIN `finstat_fa`
ON locale.id = finstat_fa.id
INNER JOIN `finstat_olta`
ON locale.id = finstat_olta.id
INNER JOIN `finstat_cl`
ON locale.id = finstat_cl.id
INNER JOIN `finstat_ltl`
ON locale.id = finstat_ltl.id
INNER JOIN `finstat_talfb`
ON locale.id = finstat_talfb.id
WHERE locale.id = :id
LIMIT 1")){
} else {
$query = $link->prepare("SELECT id, provider_num, provider_name, state, city
FROM `locale`
WHERE id = :id
LIMIT 1");
}
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
Basically it defaults to the single table where the ID does exist and only pulls a couple fields as opposed to the large statement above it. My only issue is that my code here is not working. My JSON only says false when I echo it. It obviously should not.
Is there an error in my code here?
Thanks in advance
:edit: I should note that when I enter an ID that exists in all the tables joined, the correct result (json) is displayed on the page.
I believe the problem is that even if ID does not exist in the first query, the $query variable still has a proper query in it and there is nothing false about it. That's not what you should be if-testing.
I think you should be testing $results.
This shows you the logic.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql_1 = "SQL CODE FOR QUERY 1";
$sql_2 = "SQL CODE FOR QUERY 2";
$query = $link->prepare($sql_1);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if (!$results)
{
$query = $link->prepare($sql_2);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
}
echo json_encode($results);
However as you can see there are a few lines of code that are repeated inside the if-statement that very similar to code that was just before the if-statement. Perhaps with a loop that loops twice but breaks out if $results is not false would be neater.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql[] = "SQL CODE FOR QUERY 1";
$sql[] = "SQL CODE FOR QUERY 2";
foreach ($sql as $sql_query)
{
$query = $link->prepare($sql_query);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if ($results)
{
break;
}
}
echo json_encode($results);
The world is your oyster.

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

Fetching data from database into array

I am using mysqli to fetch data from the database and put it into an array with a while loop. When i echo out the array i get an empty array however in a function i previously did this code worked but it had a different result from the database. I know that the database is giving out good data because when i echo out the result $idGroup it gives me 2 which is correct.
Ps i know it will keep replacing itself because i don't specify an index
private function Groups()
{
$functionRun = 0;
$i = 0;
$helperArray = array();
$this->grouplist = array();
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
echo $helperArray;
}
Use print_r when dealing with arrays. Use echo on strings.
Try this
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
$helperArray =array();
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
print_r($helperArray);
}

Categories