(I've unsuccessfully tried for days every solution I can find at this and other sites - please help)
I collect an array from the user via html form { $locationreq = $_REQUEST; }, for which the var_dump($locationreq) is:
array (size=1)
'locationreq' =>
array (size=3)
0 => string 'New York' (length=8)
1 => string 'NY' (length=2)
2 => string 'USA' (length=3)
I need to feed this array to execute this prepared statement mysql query:
protected function getLocationList($Location) {
$sql = "SELECT *
FROM events
WHERE City = ?, State = ?, Country = ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$Location]);
$result = $stmt->fetchALL(PDO::FETCH_ASSOC);
return $result;
I have variously tried (and failed):
- Binding (but does not seem relevant)
- Imploding (again, does not seem relevant)
- And this:
foreach ($result as $row) {
$array = array(0 => $row[0], 1 => $row[1], 2 => $row[2]);
return $result;
The most common error message is "Warning: Array to string conversion". I know what I have collected from the user is an array but I can't figure out how to get it to populate each placeholder in my prepared statement query.
The most promising and relevant question/solution seems to be this (source: Replace prepared statement placeholders with array elements in PHP ). But I couldn't get it to work. I don't know how to translate this into my code, if it's even the right answer.
<?php
$sql = "SELECT * FROM table WHERE col1 = ? AND col2 = ?";
$array = array(0 => "TEST", 1 => "TEST2");
foreach ($array as $value)
$sql = preg_replace("#\?#", "'" . $value . "'", $sql, 1);
echo $sql;
Can you please help?