i would like to know on how to convert an array so that the variable can be used to store in database table...
How to convert from array to variable to be stored in database?
Collapse
X
-
Tags: None
-
You've got a bunch of options depending on your application.
If you need to keep the array together, try using serialize to store the array as a string.
If you want to store the values in separate fields, you could name indexes of your array to match the fields in your database table, and then replace them into your database:
[code=php]
$theArray = array(
'name' => 'James',
'dob' => '1988-04-12',
'gender' => 'yes, please'
);
$query = "REPLACE INTO `myTable` (`" . implode('`, `', array_keys($the Array)) . "`) VALUES ('" . implode("', '", $theArray) . "')";
mysql_query($qu ery);
if($err = mysql_error())
throw new Exception(array ('query' => $query, 'err' => $err));
[/code]
If your array indexes didn't (or couldn't) match your database field names, you'd have to create a map:
[code=php]
$data = array(
'n' => 'John',
'b' => '2000-01-01',
'c' => 'peacock'
);
$map = array(
'name' => 'n',
'dob' => 'b',
'gender' => 'c'
);
$theArray = array_combine($ map, $data);
// Or, if you don't have PHP 5, or if you can't be sure of the order of the indexes in $data:
$theArray = array();
foreach($map as $idx => $val)
$theArray[$idx] = $data[$val];
$query = "REPLACE INTO `myTable` (`" . implode('`, `', array_keys($the Array)) . "`) VALUES ('" . implode("', '", $theArray) . "')";
mysql_query($qu ery);
if($err = mysql_error())
throw new Exception(array ('query' => $query, 'err' => $err));
[/code]
-
I really cannot imagine about the way of your Array. how ever you can customize this as per your requirement.
[PHP]<?
$con = mysql_connect(' localhost', 'root', 'dba') or die ("Could not connect to the Database");
mysql_select_db ('test', $con) or die (mysql_error()) ;
$ARRAY =array(IBM,INTE L,DELL);
for($i=0;$i<cou nt($ARRAY);$i++ )
{
$query='insert into products (p_name) values("'.$ARRA Y[$i].'")';
$result=mysql_q uery($query)or die("Query failed : " . mysql_error());
}
if($result){
echo 'DATA INSERTED';
}else{
echo 'INSERTION FAILED';
}
?>[/PHP]Comment
Comment