jasonp128 Posted May 12, 2008 Share Posted May 12, 2008 I am fairly new to PHP and have hit a roadblock that any help would be much appreciated. I have a nested array whose values I need to update into a single MySQL table. The table field names are the same as the nested array. Each instance of the parent array would be a row in the mySQL table. The output of the array when I use print_r($variable) looks like this: Array ( [0] => Array ( [id] => LB8053 [name] => test [firstName] => test [middle] => L. ) [1] => Array ( [id] => R86321 [name] => test [firstName] => test [middle] => ) [2] => Array etc... Any help would be much appreciated. Thanks in advance. Quote Link to comment https://forums.phpfreaks.com/topic/105303-solved-stumped-on-nested-array-issue/ Share on other sites More sharing options...
wildteen88 Posted May 12, 2008 Share Posted May 12, 2008 Loop through your array using a foreach loop <?php $data = array(); $data[0]['id'] = 'LB8053'; $data[0]['name'] = 'test'; $data[0]['firstName'] = 'test'; $data[0]['middle'] = 'L.'; $data[1]['id'] = 'R86321'; $data[1]['name'] = 'test2'; $data[1]['firstName'] = 'test2'; $data[1]['middle'] = 'A.'; // connect to mysql first here foreach($data as $key => $qry_arr) { $keys = array_keys($qry_arr); $values = array_map('mysql_real_escape_string', array_values($qry_arr)); $qry = 'INSERT INTO tbl_name ('; $qry .= '`' . implode('`, `', $keys) . '`) VALUES ('; $qry .= "'" . implode("', '", $values) . "')"; echo '<p>Running query: <pre>' . $qry . '</pre>'; mysql_query($qry) or die(mysql_error()); echo 'Success!</p>'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/105303-solved-stumped-on-nested-array-issue/#findComment-539269 Share on other sites More sharing options...
Barand Posted May 12, 2008 Share Posted May 12, 2008 try <?php $variable = Array ( 0 => Array ( 'id' => 'LB8053', 'name' => 'test', 'firstName' => 'test', 'middle' => 'L.' ), 1 => Array ( 'id' => 'R86321' , 'name' => 'test' , 'firstName' => 'test', 'middle' => '' ) ); foreach ($variable as $data) { $fields = join ("','", $data); $sql = "INSERT INTO mytable VALUES ('$fields')"; echo $sql, '<br/>'; // view output } ?> Oops, beaten to it (didn't spot a previous post notice) Quote Link to comment https://forums.phpfreaks.com/topic/105303-solved-stumped-on-nested-array-issue/#findComment-539275 Share on other sites More sharing options...
jasonp128 Posted May 12, 2008 Author Share Posted May 12, 2008 I got it to work. Thank you both for your responses. Quote Link to comment https://forums.phpfreaks.com/topic/105303-solved-stumped-on-nested-array-issue/#findComment-539441 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.