Skip to content
Advertisement

Array PDO to MYSQL

so i’m trying to get each amenity entered with fav_id but every time i get these two errors i tried with if before foreach() but still get the same two errors

 $inserted_id = $PDO->lastInsertId();
 $amenity_name = ['wifi', 'amenity kit'];

 $sql = "INSERT INTO user_fav (fav_id, amenity_name) VALUES (:LASTINSERTID, :AMENITY)";

 $stmt = $PDO->prepare($sql);
 $stmt->bindParam(':LASTINSERTID', $inserted_id);
 $stmt->bindParam(':AMENITY', $amenity_name);  --- line 54
     
 
 foreach($amenity_name as $item) { --- line 57
 $stmt->execute($item);
}

i get these two ERRORS

Notice: Array to string conversion on line 54
Warning: Invalid argument supplied for foreach() on line 57

Advertisement

Answer

This line

$stmt->bindParam(':AMENITY', $amenity_name);

changes $amenity_name from an array to a string:

Notice: Array to string conversion

you then can’t iterate over it (because it is a string, uniterable) so you also receive:

Warning: Invalid argument supplied for foreach()

you should bind in the foreach:

$inserted_id = $PDO->lastInsertId();
$amenity_name = ['wifi', 'amenity kit'];
$sql = "INSERT INTO user_fav (fav_id, amenity_name) VALUES (:LASTINSERTID, :AMENITY)";
$stmt = $PDO->prepare($sql);
foreach($amenity_name as $item) {
    $stmt->execute(array('LASTINSERTID' => $inserted_id, 'AMENITY' =>$item));
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement