How to insert an array into database [duplicate] - php

This question already has answers here:
How do I insert an array of values into different columns of a mysql table?
(3 answers)
Closed 7 years ago.
$rate=[10,20,40,50,70];
How do I insert the value in below query?
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
I tried below but it inserts same value in all column for a record and creates new record for each new value:
foreach($rate as $key->$value)
{
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)
VALUES('{$value}','{$value}', '{$value}','{$value}','{$value}')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
Edited based on answer given
public function rentalRate()
{
$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
unset($rate);
}

Simply use implode and that's it
$rate = [10,20,40,50,70];
$rate = implode("','",$rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
echo $sql;

Foreach is not useful in this case, because you want to integrate more than one array element in one query and you do not have a multidimensional array. Just use your first query:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('{$rate[0]}','{$rate[1]}', '{$rate[2]}','{$rate[3]}','{$rate[4]}')";
And - if you really want to use foreach:
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(";
foreach($rate as $value)
$sql .= "'$value', ";
$sql = rtrim($sql, ", ") . ")";

just simple (note implode will only work with integers, without need to quoate)
$rate=[10,20,40,50,70];
$r_sql = '';
foreach($rate as $r) {
$r_sql.="'$r',";
}
$r_sql = trim($r_sql,',');
$sql="INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES(".$r_sql.")";

Normally arrays are inserted into a different table and all tools are geared towards this. It is usually better not to fight the tools or it is likely to run into unforseen problems.
If we add a
table rental_day(id(int), rental_id(int,fk), rate(money))
Then for all the items in the array we just insert the item into one row in rental_day
later when we need the info back we can query for it like
select * from rental_day d inner join rental r on d.rental_id=r.id where r.id=something
and you will get all the info from rental_day and rental in one query.

Related

PDO fetch not working with INSERT, UPDATE then SELECT query [duplicate]

This question already has answers here:
PDO multiple queries
(1 answer)
PDO Transaction statement with insert and fetch output error
(1 answer)
Closed 1 year ago.
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');
SET #bookid = LAST_INSERT_ID();
INSERT INTO paper (papername) values('hhhhhhh');
SET #paperid = LAST_INSERT_ID();
UPDATE author SET bookid = #bookid, paperid = #paperid WHERE id = 11;
SELECT #bookid as bookid, #paperid as paperid FROM DUAL;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$numofnewParn =$stmt->rowCount();
if($numofnewParn>0){
$newParentDt = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($newParentDt);
}
I have set of inserts with LAST_INSERT_ID assigned to respective parameters.
Later, updating a table with the parameters.
until $stmt->execute(); is not problem.
My question is can I continue the query by adding SELECT and fetch the data like $stmt->fetch(PDO::FETCH_ASSOC)?
or does it not make sense? if so, is there any source?
because above code does not print out.
You need to use PDOStatement::nextRowset see here to move onto the next queries result in your multi statement... however a cleaner setup would be to break this down into single statement queries and use PHP variables to save your bookid and paperid values:
<?php
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$bookid = $pdoConnect->lastInsertId();
$sql = "INSERT INTO paper (papername) values('hhhhhhh');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$paperID = $pdoConnect->lastInsertId();
$sql = "UPDATE author SET bookid = $bookid, paperid = $paperid WHERE id = 11;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();

Update Table Iterating Array Using PHP / PDO [duplicate]

This question already has answers here:
How to avoid code repetition with PHP SQL prepared statements?
(2 answers)
Closed 3 years ago.
There are similar questions here and some rather complex answers. I don't believe it should be that complicated. Perhaps it is. I am new to PDO. I have an array of key-value pairs. I need to update a record with those values. Is there a more intelligent way to do this?
$sql = "UPDATE Table SET ? = ? WHERE ID = ?";
$stmt = $pdo->prepare($sql);
foreach($QueryString as $Key=>$Value)
{
$stmt->execute($Key, $Value, $RecordID);
}
You can't bind a value to a column name, so your current code won't work at all. It would also be more efficient to form that query to make all the updates at once, for example:
$sql = "UPDATE Table SET";
$v = 0;
foreach ($QueryString as $Key=>$Value) {
if ($v++ > 0) $sql .= ',';
$sql .= " `$Key` = ?";
}
$sql .= " WHERE ID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge(array_values($QueryString), array($RecordID)));
Note that this query is still vulnerable to injection if the keys of the $QueryString array come from an outside source. To avoid this issue, you should check that the columns actually exist, either using a manually specified whitelist e.g.
$colnames = ['col1', 'col2', 'col3'];
foreach ($QueryString as $Key=>$Value) {
if (!in_array($Key, $colnames)) {
// abort
}
if ($v++ > 0) $sql .= ',';
$sql .= " `$Key` = ?";
}
or by getting the list of the column names from the information_schema.columns table as described in this question and using the result of that query as your whitelist.

PHP Mysql Prepared statement different result [duplicate]

This question already has answers here:
I have an array of integers, how do I use each one in a mysql query (in php)? [duplicate]
(5 answers)
mySQL bind_param with IN(?) [duplicate]
(5 answers)
Closed 3 years ago.
I have this mysql query in php:
$sql2 = "SELECT id, nazev, poradi FROM system WHERE id IN($idIs) ORDER BY poradi";
$result2 = mysqli_query($conn, $sql2);
The variable $idIs is a string '2,3' (two ids of system).
When I try to fill array $nazevSystemu, there are two values (beacause of the two ids from $idIs)
$i = 0;
$nazevSystemu = [];
while($row2 = mysqli_fetch_assoc($result2)) {
$nazevSystemu[$i] = $row2['nazev'];
echo $row2['nazev'];
$i++;
}
Result of echo $row2['nazev'];:
Value1Value2
I want to make it safe, avert SQl inj., so I use prepared statement like this (instead of the first two rows of code on this page):
$stmt2 = $conn->prepare("SELECT id, nazev, poradi FROM system WHERE id IN(?) ORDER BY poradi");
$stmt2->bind_param("s", $idIs);
$stmt2->execute();
$result2 = $stmt2->get_result();
But now I get only this as result of echo $row2['nazev']; - just one value:
Value1
What did I do wrong in prepared statement?
You have to provide all id's as individual parameters.
So instead of IN(?) you have to write IN(?,?,?) and parse each parameter individual.
Code example:
$ids = explode(',', $idIs);
$stmt2 = $conn->prepare("SELECT id, nazev, poradi FROM system WHERE id IN(".trim(str_repeat('?,', count($ids)), ',').") ORDER BY poradi");
foreach ($ids as $id) {
$stmt2->bind_param("i", $id);
}
$stmt2->execute();
$result2 = $stmt2->get_result();

Prepared statement WHERE IN clause behaving unexpected [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I'm reworking some PHP code to use PDO for the database access, but I'm running into a problem with a "WHERE... IN" query.
I'm trying to delete some things from a database, based on which items on a form are checked. The length and content of the list will vary, but for this example, imagine that it's this:
$idlist = '260,201,221,216,217,169,210,212,213';
Then the query looks like this:
$query = "DELETE from `foo` WHERE `id` IN (:idlist)";
$st = $db->prepare($query);
$st->execute(array(':idlist' => $idlist));
When I do this, only the first ID is deleted. (I assume it throws out the comma and everything after it.)
I've also tried making $idlist an array, but then it doesn't delete anything.
What's the proper way to use a list of items in a PDO prepared statement?
Since you can't mix Values (the Numbers) with control flow logic (the commas) with prepared statements you need one placeholder per Value.
$idlist = array('260','201','221','216','217','169','210','212','213');
$questionmarks = str_repeat("?,", count($idlist)-1) . "?";
$stmt = $dbh->prepare("DELETE FROM `foo` WHERE `id` IN ($questionmarks)");
and loop to bind the parameters.
This may be helpful too:
https://phpdelusions.net/pdo#in
$arr = [1,2,3];
$in = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($arr);
$data = $stm->fetchAll();
I would make $idlist and array, then simply loop through the array using foreach to delete the specific item.
$idlist = array('260','201','221','216','217','169','210','212','213');
$stmt = $dbh->prepare("DELETE FROM `foo` WHERE `id` = ?");
$stmt->bindParam(1, $id);
foreach ($idlist as $item){
$id = $item;
$stmt->execute();
}

PDO query with dynamic column names [duplicate]

This question already has answers here:
Insert/update helper function using PDO
(11 answers)
Closed 6 years ago.
i am upgrading one application from MySql to PDo, now the application is big so i don't want to write query every time, instead i am creating some insert, update, select etc. functions which accept dyanamic table name, with column and its value in array.
can any one sugest me how i can create this .
so far i have done is
$connection = new PDO("mysql:host=$host;dbname=$database;charset=utf8", "$user", "$password");
for select
$field = array("column1","column2");
$sql = "SELECT ".$fields." FROM ".$table." ".$whereSQL." ";
for inser
$col_val = array("column1"=>value, "column2"=>2);
$query = "insert into ".$table." (".$fields.") values (".$values.")";
$query = $connection->prepare($sql);
$query->execute();
i try to do all this but for an example in insert query i want to pass array as
$col_val = array("column1"=>value, "column2"=>2);
some code and function here which make PDO query easy and insert all column and value correctly.
i am also looking same way to perform Update query.
as you can see here tabel, column and value are totally dynamic which will be pass to function.
for this moment i am using all odd query with
$query = $connection->prepare($sql);
$query->execute();
Thank you in advance.
This is not a complete solution but that's the idea I think you could use to get closer to fix your issue.
$columns = array('column1', 'column2', 'column3')
$comma_separated = implode(",", $columns);
$columns_values = array(
'column1' => 'text1',
'column2' => 'text2',
'column3' => 'text3',
)
$values_query = "";
$index = 0
foreach ($columns as $column_name) {
if ($index == 0){
$values_query .= "'". $columns_values[$column_name]."'"
}else{
$values_query .= ", '". $columns_values[$column_name]
}
}
$query = "INSERT INTO table (". $comma_separated . ") VALUES (".$values_query.");";
Before executing the query you can use PDO to escape the string ($query) to avoid SQL injection

Categories