I am really stuck with this one.
I am trying to pass a list of codes to a MySql statement, but not in the right format for it to work.
My list comes from a form textarea called "uniquecode"
Example codes (all on a new line) from the text area would be:
fg3456 tg7844 de3902 .. etc
I attempt to explode and implode the list with:
$ar = $_POST['uniquecode']
$in = "'".implode("','", explode("\n", $ar))."'";
The result of $in then gets passed to a Mysql statment:
$sql = "SELECT code, size, price from stock WHERE code IN ($in)";
When I echo the $sql, I get the following:
SELECT housecode, name, cost, size, price FROM stock where code IN ('fg3456 ','tg7844 ', ','de3902')
As you can see only the LAST item, 'de3902' is formatted correctly. Notice the first item in the list has a space then a single quote then a comma: 'fg3456 ',
Because of this issue, when I attempt to loop through the result set from the query, only the last item is returned:
$result = $mysqli->query($sql);
if ($result = mysqli_query($mysqli, $sql)) {
while($row = $result->fetch_array()) {
$code = $row['code'];
$name = $row['name'];
$size = $row['size'];
$price = $row['price'];
}
echo $code; //returns last item in the list: de3902
So my question is how to explode/implode the list into the correct format for the IN clause of the Mysql query so it reads correctly and returns all the codes???
SELECT code, name, size, price from stock WHERE code IN ('fg3456','tg7844','de3902')
Kind regards
var_dump($_POST['uniquecode'])as copied from the browser page source, not as rendered on screen. You have something spurious in there (not an extra line break, I think) that is breaking yourimplode(), maybe correctable witharary_filter(). But steps need to be taken to protect this from SQL injection.preg_split()instead to explode on multiple spaces or new-line characters as well.