0

Okay,
I don't know what exactly the problem is. So, I decided to post it here to discuss it with you.
The Problem is that, When I use php implode function in PDO execute(array(implode(",",$imploded)))); It doesn't work
When I use php implode function " the same function with the same variables " in the select statment, it works normally !
I've doubts that using it in the statment is a chance for SQL Injection.

Here's My Full Code :

$exCat = explode(",", $article['Category']);
$getCats = $con->prepare("SELECT * FROM `Categories` WHERE `ID` IN (?)");
if (is_array($exCat)) {
    $getCats->execute(array(implode(",", $exCat))); /* This Is only displaying the first element */
} else {;
    $getCats->execute(array($exCat));
}
$getCATS = $getCats->fetchAll();

This Works fine with me. However, I've doubts that using it in the statment is a chance for SQL Injection.

$exCat = explode(",", $article['Category']);
$anotherStmt = $con->prepare("SELECT * FROM `Categories` WHERE `ID` IN (" . implode(",", $exCat) . ")"); /* This Works fine */
$anotherStmt->execute();
$anotherCATS = $anotherStmt->fetchAll();
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Hema D.
  • 140
  • 2
  • 5
  • 17
  • 1
    *"So, I decided to post it here to discuss it with you.* - This isn't the place to discuss since it tends to fill up the comments area. I (for one) don't know what it is that you're asking or what the real question's about. If your code works as you placed comments in each of them and feel that you may still be open to injection and asking others if it's ok or not, then the post should be moved into a chatroom somewhere and/or posted in code review. It works or it doesn't? You're contradicting yourself. – Funk Forty Niner Jul 22 '18 at 22:16
  • Ok, thanks for the advice. My question is clear, why implode doesn't work probably on execute(); while it's working normally when putting it on the sql statment. I've no problem putting it on the sql statment, but won't that make sql injection problem ? – Hema D. Jul 22 '18 at 22:20
  • 1
    both of these should help https://stackoverflow.com/questions/14767530/php-using-pdo-with-in-clause-array --- https://stackoverflow.com/questions/26886026/how-use-an-array-implode-in-the-select-query-pdo – Funk Forty Niner Jul 22 '18 at 22:22

1 Answers1

2

explode returns an array in every instance so is_array is not needed.

You need to use a placeholder for every value you want bound. I'd use str_repeat and rtrim to generate your placeholders then just pass the exploded array to the execute.

$exCat = explode(",", 'non commaed list, commaed');
$placeholders = rtrim(str_repeat('?,', count($exCat)), ', ');
$getCats = $con->prepare("SELECT * FROM `Categories` WHERE `ID` IN ({$placeholders})");
$getCats->execute($exCat);
user3783243
  • 5,368
  • 5
  • 22
  • 41