Replace value in array with result of mysqli_query - php

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
}

Related

Insert a mysqli_result Object

I have a mysqli_result:
$stmt = $db->prepare("SELECT * FROM customer");
$stmt->execute();
$result = $stmt->get_result();
Is it possible to directly do an INSERT with this result? (Data needs to be transferred in another database) like $another_db->insert($result) or at least to convert the whole result Object to a simple Mysql Insert String without iterating over the result.
I do a workaround like this:
$stmt = $db->prepare("SELECT * FROM customer");
$stmt->execute();
$result = $stmt->get_result();
$newsql="";
while($row = $result->fetch_object())
{
$newsql = "INSERT INTO customer VALUES (";
foreach($row as $key => $value)
{
$newsql .= "'".mysqli_real_escape_string($db,$value)."',";
}
$newsql = substr($newsql,0,-1);
$newsql .="); ";
}
// $newsql can be inserted.

How to nest 2 SQL statements with a foreach loop inside each other

Okay I try with the first query to get all names of the computers from the table psComputers. Now I need in the second query a variable from the first query to iterate over all entries which are assigned to the respective computer in the table psTest. I wonder if such a thing is possible at all?
Table psComputer contains ID, name
Table psTest contains ID, computername, category, value
index.php
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if ($statement->rowCount() > 0) {
foreach ($statement->fetchAll() as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = $name");
$statement2->execute();
$result2 = $statement2->fetchAll();
if ($statement2->rowCount() > 0) {
foreach ($statement2->fetchAll() as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
You need quotes around $name in the second query, since it's a string.
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = '$name'");
But since you're using a prepared query, you should use a parameter instead of substituting a variable.
You also shouldn't call $statement->fetchAll() twice. The first call will read all the rows, and the second won't have anything left to read (it doesn't reset the cursor).
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if (count($result) > 0) {
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = :name");
$statement2->bindParam(':name', $name);
foreach ($result as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2->execute();
$result2 = $statement2->fetchAll();
if (count($result2) > 0) {
foreach ($result2 as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
But even better is to just join the two queries:
$statement = $pdo->prepare("
SELECT c.id AS computerID, c.name AS computerName, t.id AS testID, t.category, t.value
FROM psComputers AS c
JOIN psTest AS t ON c.name = t.computerName
ORDER BY c.id");
A couple things to note,
When using strings in queries, they must be quoted.
You are already preparing the statement - bind the value instead, and the note above becomes irrelevant.
You can use a JOIN instead of running a query in a loop. This will also remove the variable in the name, making both notes above irrelevant! (You should take note of both, but they become irrelevant for the code in question).
Its rarely a good idea to run a query within a loop.
$statement = $pdo->prepare("SELECT pt.*
FROM psTest pt
JOIN psComputers pc ON pt.computerName=pc.name");
$statement->execute();
$result = $statement->fetchAll();
if (count($result)) {
foreach ($result as $row) {
$id2 = $row['ID'];
$computerName = $row['computerName'];
$category = $row['category'];
$value = $row['value'];
}
}

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

Adding to the same array with two different foreach loops PHP/SQL

I have seperate tables full of data and I require the same data from each table. For example the first table I am selecting from has the value 3623 and the second table has the value 3852.
I am trying to get both of these values into an array to then be plotted on a graph later down the line. The code I am using can be seen below, the issue is that on the value from the first foreach loop gets added and not the second one. so I end up with just 3623 and not the 3852 as well which is an issue.
$datay1 = array();
$yes = "not-set";
$sql = "SELECT * FROM `0530-0605` WHERE SearchTerm = :yes";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}
$sql = "SELECT * FROM `0606-0612` WHERE SearchTerm = :yes";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}
print_r($datay1);
You can use UNION ALL to merge result of two query as
$sql = "SELECT * FROM `0530-0605` WHERE SearchTerm = :yes
UNION ALL
SELECT * FROM `0606-0612` WHERE SearchTerm = :yes1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->bindParam(":yes1", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}

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.

Categories