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.
Related
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
}
How would I get this to work, because I am just getting errors right now.
$_GET['providers'] is an array of DB column names, which I am checking if = 1 in the below query.
foreach ($_GET['providers'] as $providers) {
$statement = "AND ".$providers."= '1' ";
}
$sql = "select * from users where user_id ='1' ".$statement." ";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You should use a whitelist to check if the $providers are known column names. You then should concatenate the $statement, otherwise you overwrite that variable on every iteration.
$statement = '';
$columns = array('known', 'columns', 'go', 'here');
foreach ($_GET['providers'] as $providers) {
if(in_array($providers, $columns)) {
$statement .= " AND $providers = 1 ";
}
}
$sql = "select user_id from users where user_id =1 $statement limit 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
You also shouldn't use * unless you really want every column. If you just want to see if a row is returned you also can use limit 1 because you don't care about other rows.
You are overwriting $statement every time the loop is running.
$statement = "";
foreach ($_GET['providers'] as $providers) {
$statement .= "AND ".$providers."= '1' "; // note the ".=" to append
}
$sql = "select * from users where user_id ='1' ".$statement." ";
// to debug: echo "Query :: $sql";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if(isset($row['user_id'])){
echo "It worked";
}
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'];
}
This question already has answers here:
return one value from database with mysql php pdo
(3 answers)
Closed 3 months ago.
I'm trying to add some data to my database, but I'm getting the error Catchable fatal error: Object of class PDOStatement could not be converted to string in /var/www/mandje.php on line 114.
This is the code I'm using:
foreach($_SESSION["cart"] as $id => $value){
$query = $db->query('SELECT * FROM Producten WHERE ProductID ="'.$id.'" ');
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$price = $row['Prijs'];
$ProductID = $row['ProductID'];
}
$sql="INSERT INTO Bestellingsdetail( Bestelnummer, ProductID, Aantal, Prijs)
VALUES ($max,$ProductID,$value,$price)"; //<---- line 114
$count = $db->execute($sql);
I don't really get what's going wrong here. Any help would be much appreciated :)
In the comments, you show the following:
$query = $db->query('SELECT MAX( Bestelnummer ) FROM Bestellingsdetail');
$query->execute();
$max = $query;
$max++;
This is not how you get the result from a query. You are setting $max to a PDOStatement object. You need to fetch() the result in order to use it.
// I've added "AS maxval" to make it easier to get the row
$query = $db->query('SELECT MAX(Bestelnummer) AS maxval FROM Bestellingsdetail');
$max_row = $query->fetch(PDO::FETCH_ASSOC);
$max = $max_row['maxval'];
$max++;
Docs: http://www.php.net/pdo.query
P.S. $query->execute(); is only needed for prepared statements. query() will execute the query immediately.
foreach($_SESSION["cart"] as $id => $value)
{
$query = $db->query('SELECT * FROM Producten WHERE ProductID ="'.$id.'" ');
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$price = $row['Prijs'];
$ProductID = $row['ProductID'];
}
$array = array( $max, $ProductID, $value, $price );
$sql->prepare
("
INSERT INTO Bestellingsdetail (Bestelnummer, ProductID, Aantal, Prijs)
VALUES (?, ?, ?, ?)
")
$sql->execute($array);
}
Try:
foreach($_SESSION["cart"] as $id => $value){
$query = $db->query('SELECT * FROM `Producten` WHERE ProductID ="'.$id.'" ');
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$price = $row['Prijs'];
$ProductID = $row['ProductID'];
}
$sql="INSERT INTO `Bestellingsdetail`( `Bestelnummer`, `ProductID`, `Aantal`, `Prij`s)
VALUES ($max,$ProductID,$value,$price)";
$smtp = $db->prepare($sql);
$count = $smtp->execute();
However, try and use the prepared statements as you are defeating the reason of using PDO and could be at risk of injection:
foreach($_SESSION["cart"] as $id => $value){
$query = $db->query('SELECT * FROM `Producten` WHERE ProductID ="'.$id.'" ');
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$price = $row['Prijs'];
$ProductID = $row['ProductID'];
}
$sql="INSERT INTO `Bestellingsdetail`( `Bestelnummer`, `ProductID`, `Aantal`, `Prijs`)
VALUES (:max,:ProductID,:value,:price)";
$stmt = $db->prepare($sql);
$stmt->bindParam(':max', $max);
$stmt->bindParam(':ProductID', $ProductID);
$stmt->bindParam(':value', $value);
$stmt->bindParam(':price', $price);
$count = $smtp->execute();
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.