MySQL where in (array) [duplicate] - php

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Reference — frequently asked questions about PDO
(3 answers)
Closed 8 years ago.
function delete_group($db) {
$ids = Parameters::get('ids');
$ids = implode(',', $ids); // now a string like '5,6,7'.
add_to_log($ids);
try {
$stmt = $db->prepare("DELETE FROM mytable WHERE id IN (:ids)");
$stmt->bindParam(':ids', $ids, PDO::PARAM_STR);
$stmt->execute();
response('success', 'success', NULL);
}
catch (PDOException $e) {
response('error', 'Delete group failed.', NULL);
}
}
This code doesn't work: only the first row is deleted. But if I do
$stmt = $db->prepare("DELETE FROM mytable WHERE id IN ($ids)");
instead (just insert the string), it works, though the code has the SQL injection security issue. How to make it work and keep secured?

$ids = Parameters::get('ids');
$ids = array_map('intval', $ids);
$ids = implode(',', $ids);
Now you don't have to worry about injection.

Related

PDO Prepare used in a function [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
(1 answer)
Closed 7 months ago.
My sql request doesn't work if I use a function paramater to choice the column.
My goal is to have one function for all request.
Thanks in advance.
$dbh = Connection::getPdo();
try {
$sth = $dbh->prepare('SELECT users_id, nom, prenom, password, role, email, users_login FROM users where ? = ? ');
$value="'".$value."'";
$sth->execute(array($parameter,$value));
$data = $sth->fetch(PDO::FETCH_ASSOC);
$user = new Users();
$user->setUserFromArray($data);
} catch (PDOException $e) {
die("ERROR: Could not able to execute query " . $e->getMessage());
}
return $user;
}

pdo not binding param properly [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been stuck on this for about 3 days now and asked multiple people about this and no one seems to have an answer to me why this is not working. I cannot figure out why they aren't binding because the bindings work on the select statement but not the update. I know for a fact that $sessCheck['userid'] and $sessCheck['hwid'] are being set because I already printed them out to check if they were null or something.
The request inbound from slim
{"userid": "1000","hwid":"TESTING"}
The function
function updateHWID(){
$request = Slim::getInstance()->request();
//$bsreq = utf8_encode();
$sessCheck = json_decode($request->getBody(), true, 9 );
$db = getConnection();
$sql = "SELECT userid,hwID FROM accounts WHERE userid = :userid";
$stuff = $db->prepare($sql);
$stuff->bindParam("userid", $sessCheck['userid']);
$stuff->execute();
$db = null;
$rows = $stuff->fetch(PDO::FETCH_ASSOC);
if ($rows['hwID'] != $sessCheck['hwid']) {
$sql2 = "UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid';";
try {
$db2 = getConnection();
$stmt = $db2->prepare($sql2);
//these two param's are not binding
$stmt->bindParam("userid", $sessCheck['userid']);
$stmt->bindParam("hwid", $sessCheck['hwid']);
$stmt->execute();
//$rt = $stmt->fetch(PDO::FETCH_ASSOC);
//$stmt->debugDumpParams();
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
This is the result incoming on the sql log
1372 Query UPDATE accounts SET hwID=':hwid' WHERE userID = ':userid'
I've also tried this as well as using the which also didn't work
$stmt->bindParam(":userid", $sessCheck['userid']);
$stmt->bindParam(":hwid", $sessCheck['hwid']);
Then I tried this too and it didn't work
$stmt = $db2->prepare("UPDATE accounts SET hwID='?' WHERE userID = '?';");
$stmt->bindParam(1, $sessCheck['hwid'], PDO::PARAM_STR);
$stmt->bindParam(2, $sessCheck['userid'], PDO::PARAM_INT);
Take the binded parameter names out of their single quotes.
so:
$sql2 = "UPDATE accounts SET hwID=:hwid WHERE userID = :userid;";

How to use IN dynamically with mysqli prepare statement [duplicate]

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

Issue using grammar with PDO [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
Have a minor issue when updating records in MySQL using PDO. It fails to update when I use grammar so for an example, if I use: ' it fails me. I am using my prepare, but it's just the apostrophe that fails to work?
if($_POST['ourstory']) {
foreach($_POST['ourstory'] as $id => $ourstory) {
$sql = "UPDATE our_story SET content = '$ourstory' WHERE id = '$id'";
$q = $db->prepare($sql);
$q->execute(array($id,$ourstory));
}
}
That's not how you use prepared statements. You want to use a ? in your query.
$sql = "UPDATE our_story SET content = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($ourstory, $id));

Selecting rows where ids are provided in a list [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 9 years ago.
I want to get all the list of registered players from an array
here is my function
function UpdateContact()
{
try {
$conn = $this->GetDBConnection();
$linkedInId = trim($_REQUEST['linkedInId']);
$statement = $conn->prepare('UPDATE users SET linkedInId = :linkedInId WHERE linkedInId = :linkedInId');
$statement->bindParam(':linkedInId', $linkedInId, PDO::PARAM_STR);
$statement->execute();
//$updatedTime = time() - 120;
$ids = implode(",",$_POST['ids']);
// $ids = (abc,def,geh,ijk,lac);
$statement = $conn->prepare('SELECT * FROM users WHERE linkedInId IN (:ids)');
$statement->execute($ids);
$conn = null;
if (!($row = $statement->fetchAll(PDO::FETCH_ASSOC)))
return false;
else
return $row;
} catch(PDOException $e) {
throw $e;
}
}
Just return false
Maybe because i am not able to bind the array with PDO Statement?
How can I fix this solution, i might want to add more binding parameters too later on, so i don't want to do execute($ids) either.
I have tried bindParam(':ids',$ids) too but of no avail
$items = array();
//$statement->bindParam(':updatedTime', $updatedTime, PDO::PARAM_STR);
foreach ($id as $ids)
{
$statement = $conn->prepare('SELECT * FROM users WHERE id = :id');
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
if(($row = $statement->fetch(PDO::FETCH_OBJ)))
$items[] = $id;
}
I think it would make more sense to parse the array/list and perform the select for each id in the array/list.
Pseudo code:
init resultArray;
For x in List
select * from database where ids =: x
if result
add result to resultArray
return resultArray
But that's just the basic way of doing it, I'm not sure if you can do it more advanced.

Categories