Reputation: 3
I am trying to insert an array in to MySQL using PHP. I followed the excellent advice given on here to use the implode command and it worked great for one array, but this one seems to be dying. This array is slightly different than the other, but I don't know how to explain the difference.
Here is my code:
$sql = array();
foreach( $ride_detail as $row ) {
$sql[] = '('.$row['id'].', "'.mysql_real_escape_string($row['name']).'",
"'.$row['version'].'")';
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES '.implode(',', $sql));
I'm getting this message over and over again.
Warning: Illegal string offset 'id' in ride_details.php on line 60
Warning: Illegal string offset 'name' in ride_details.php on line 60
Warning: Illegal string offset 'version' in ride_details.php on line 61
The content of my array (using print_r) is:
Array ( [id] => 21570117 [name] => Night ride home from work [start_date_local] => 1347302039 [elapsed_time] => 53:56 [moving_time] => 52:04 [distance] => 12.6 >>[average_speed] => 14.5 [elevation_gain] => 474 [location] => Englewood, CO [start_latlng] => Array ( [0] => 39.547792011872 [1] => -104.86300536431 ) [end_latlng] => Array ( [0] => 39.655485888943 [1] => -104.88656991161 ) [version] => 1355428869 [athlete] => Array ( >>[id] => 832001 [name] => Bob Kratchet [username] => bob_kratchet ) [bike] => Array ( [id] => 281303 [name] => Giant Allegre commuter ) [maximum_speed] => 29.3 [calories] => 372 >[average_power] => 107 [commute] => 1 )
I am a complete noob...
Upvotes: 0
Views: 306
Reputation: 37233
try this
foreach( $ride_detail as $row ) {
$sql = array( $row['id'], mysql_real_escape_string($row['name']), $row['version']) ;
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES ($sql[0] ,$sql[1] , $sql[2] ) ');
Upvotes: 0
Reputation: 324600
Since your $ride_detail
is just one array, $row
is 21570117
(integer), Night ride home from work
(string), and so on, one by one. The code then attempts to get the id
key of each element, then the name
key, and so on, generating a [expletive]-ton of error messages as it goes.
It looks like you're intending to have $ride_detail
be an array of arrays, or you don't actually want a foreach
loop at all.
Upvotes: 1