This question already has answers here:
PDO binding values for MySQL IN statement [duplicate]
(8 answers)
PreparedStatement IN clause alternatives?
(33 answers)
Closed 7 years ago.
I was trying to use IN with mysqli prepare statment
$user_in = "'28','22'";
$stmt = $this->connection->prepare("SELECT `id` FROM `$this->table_name` WHERE `user_id` IN (?) ");
if($stmt){
$stmt->bind_param('s',$user_in);
if($stmt->execute()){
$result = $stmt->get_result();
if($result !== false && $result->num_rows >= 1){
$row = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
var_dump($row);
}
}
}
echo $this->connection->error;
return false;
But the approach above is not able to fetch any result sets
Placeholders represent a SINGLE value. If you have a variable and placeholder-using query:
$var = '1,2,3';
SELECT ... WHERE foo IN (?)
then the query will be executed as the SQL had literally been
SELECT ... WHERE foo IN ('1,2,3')
and your 3 separate csv values will be treated as a single monolithic string.
IN clauses are one place where placeholders are somewhat useless, since you have dynamically build up a string with as many placeholders as you have values, e.g.
$vals = array(1,2,3);
$placeholders = '?' . str_repeat(',?', count($vals) - 1);
$stmt = $db->prepare("SELECT ... WHERE foo IN ($placeholders)");
foreach($vals as $i => $val) {
$stmt->bind($i, $vals[$i]);
}
and then
Related
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();
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
MySQLi Bind Param with an array for IN [duplicate]
(2 answers)
Closed 5 years ago.
I can not figure out how I can prepare my select statement.
$query = "SELECT name, art FROM table_one WHERE name LIKE ? AND art IN ?";
if ($stmt = $db_link->prepare($query)) {
$stmt->bind_param("ss", $name, $art);
$stmt->execute();
if ($stmt->errno){
//Deal with error
}
$name = "%Marc%";
$art = "('green', 'blue', 'red')";
$stmt->execute();
$stmt->bind_result($name, $art);
while ($stmt->fetch()){
//Output data
}
}
So the problem is, that something does not work with the syntax in the prepared statement. This is my first attempt at preparing statements.
I had the query working before without using a prepared statement, but I am forced to use that now.
The old query looked like this:
$query = "SELECT name, art FROM table_one WHERE name LIKE '%$name%' AND art IN ('$art')";
Thank you for your help.
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 5 years ago.
I have this code to get a COUNT DISTINCT data:
$param = 'email';
$stmt = $conn->stmt_init();
$stmt = $conn->prepare("SELECT COUNT(DISTINCT(?)) FROM contatos");
$stmt->bind_param('s',$param);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($count);
while ($stmt->fetch()) {
echo $count;
}
But echo $count always returns 1, but i have dozens of records...
What is wrong?
Thanks
Binding is not allowed for column names (or table names). Your query is not executing correctly. You need to directly pass the name of the field.
$stmt = $conn->prepare("SELECT COUNT(DISTINCT(email)) FROM contatos");
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();
}
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);