How to represent a PHP array as a comma-delimited string? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP/MYSQL using an array in WHERE clause
I have an array with ID values [1,5,2,6,7...] and I need to use that in a MySQL item_id IN (1,5,2,6,7...) statement to select only rows with an ID listed in the array. How can I go about converting the $arrIDs to something that I can insert into my SQL query?
EDIT- context of the call:
if(!IsNullOrEmptyString($_GET["view_playlist"])) {
session_destroy();
}
$id_list = implode(",", $_SESSION("playlist"));
$sql = 'SELECT t.track_id, t.track_title, t.track_num, al.album_title, g.genre_name, a.artist_name, t.length, t.track_rating '.
'FROM track t, genre g, artist a, album al '.
'WHERE t.track_id IN('.$id_list.' AND t.genre = g.genre_id AND t.artist = a.artist_id AND t.album = al.album_id';

Use implode();
$ids = implode(',', $your_array);

If you're using PDO or mysqli (which you should, as the mysql_ functions are antiquated and should be abandoned), then you'll want to construct a parameterized query using the number of elements in your array to match the number of ?'s in your SQL.
Here's an example in PDO:
$ids = array(1, 2, 3, 4);
try {
$dbh = new PDO("mysql:host=localhost;dbname=mydbname", 'username', 'password');
} catch(PDOException $e) {
die($e->getMessage());
}
$inClause = trim(str_repeat('?, ', count($ids)), ', ');
$stm = $dbh->prepare('SELECT * FROM mytable WHERE id IN ('.$inClause.')');
$stm->execute($ids);
// resulting SQL: SELECT * FROM mytable WHERE id IN (?, ?, ?, ?)

Related

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

How to avoid escape character "\" in PDO prepared statement? [duplicate]

This question already has answers here:
PHP - Using PDO with IN clause array
(9 answers)
Closed 7 years ago.
I have this SQL query:
$sql = "SELECT ac.id AS target_id FROM account AS ac JOIN
address_vod__c AS ad
ON (ad.account_vod__c = ac.id AND ad.primary_vod__c = 1)
WHERE ac.id IN (?)";
And I am trying to add values for IN clause from a array as follow:
// $values is a huge array containing values
$params = [implode("','", $values)];
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll();
Code is working but I am getting the wrong SQL:
SELECT
ac.id AS target_id
FROM
account AS ac
JOIN
address_vod__c AS ad ON (ad.account_vod__c = ac.id
AND ad.primary_vod__c = 1)
WHERE
ac.id IN ('00180000017rkSfAAI\',\'0018000001GgXTtAAN\',\'0018000001GgXTYAA3')
I expect and I am looking something like:
SELECT
ac.id AS target_id
FROM
account AS ac
JOIN
address_vod__c AS ad ON (ad.account_vod__c = ac.id
AND ad.primary_vod__c = 1)
WHERE
ac.id IN ('00180000017rkSfAAI','0018000001GgXTtAAN','0018000001GgXTYAA3')
How do I avoid PDO from escape the strings?
You are doing ac.id IN (?). This is telling the database that you want to bind one parameter to the query. If you have multiple elements, you need multiple ?s: ac.id IN (?,?,?).
What you can do is dynamically add the ?s and then bind each parameter that you need.
$params = implode(',', array_fill(0, count($values), '?'));
$sql = "SELECT ac.id AS target_id FROM account AS ac
JOIN address_vod__c AS ad ON (ad.account_vod__c = ac.id AND ad.primary_vod__c = 1)
WHERE ac.id IN ({$params})";
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
$result = $stmt->fetchAll();
You should implode the placeholders and let pdo do the work
$inArray = array_fill(0, count($values), '?');
$inExpr = implode(',', $inArray);
$sql = "... WHERE id IN ($inExpr)";
And then just pass $values - pdo will do the rest for you

How to insert an array into database [duplicate]

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.

PDO Select form MYSQL db [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
There are many hints for this topic, I tried this: How to create a secure mysql prepared statement in php?
and many others, but nothing is working. If I want to select something from the database and query without parameters, it's ok. But if I want data for a column and table with parameters, it doesn't work, it returns empty array. Any hints?
There is my code:
function getDataByColumn($column, $table) {
try {
$connection = new PDO("mysql:dbname=vydap;charset=utf8;host=127.0.0.1", "...","...");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = "SELECT ? FROM ?";
// $query = "SELECT :column FROM :table";
$stmt = $connection->prepare($query);
// $stmt->bindParam(':column', $column);
// $stmt->bindParam(':table', $table);
$stmt->bindParam(1, $column);
$stmt->bindParam(2, $table);
$stmt->execute();
$result = $stmt->fetchAll();
var_dump($result);
}
This is flat-out wrong:
$query = "SELECT ? FROM ?";
placeholders can represent only VALUES. You cannot use placeholders for field/table/db names - those aren't values - they're idenfifiers.
SELECT foo FROM bar WHERE foo = 'baz'
a b c d e f g h
a- sql keyword
b- field identifier
c- sql keyword
d- table identifier
e- sql keyword
f- field identifier
g- operator
h- value
Of that entire query, only the h portion is a candidate for using a placeholder.
You can't use PDO placeholders on table or columns names. Those are only used for values:
$query = "SELECT * FROM yourTable WHERE someCol = ?";
$stmt->bindParam(1, $value);

Categories