By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,871 Members | 2,337 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,871 IT Pros & Developers. It's quick & easy.

How to convert from array to variable to be stored in database?

P: 5
i would like to know on how to convert an array so that the variable can be used to store in database table...
May 23 '07 #1
Share this Question
Share on Google+
2 Replies


pbmods
Expert 5K+
P: 5,821
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:

Expand|Select|Wrap|Line Numbers
  1. $theArray = array(
  2.     'name' => 'James',
  3.     'dob' => '1988-04-12',
  4.     'gender' => 'yes, please'
  5. );
  6.  
  7. $query = "REPLACE INTO `myTable` (`" . implode('`, `', array_keys($theArray)) . "`) VALUES ('" . implode("', '", $theArray) . "')";
  8. mysql_query($query);
  9.  
  10. if($err = mysql_error())
  11.     throw new Exception(array('query' => $query, 'err' => $err));
  12.  
If your array indexes didn't (or couldn't) match your database field names, you'd have to create a map:

Expand|Select|Wrap|Line Numbers
  1. $data = array(
  2.     'n' => 'John',
  3.     'b' => '2000-01-01',
  4.     'c' => 'peacock'
  5. );
  6.  
  7. $map = array(
  8.     'name' => 'n',
  9.     'dob' => 'b',
  10.     'gender' => 'c'
  11. );
  12.  
  13. $theArray = array_combine($map, $data);
  14.  
  15. //    Or, if you don't have PHP 5, or if you can't be sure of the order of the indexes in $data:
  16. $theArray = array();
  17. foreach($map as $idx => $val)
  18.     $theArray[$idx] = $data[$val];
  19.  
  20. $query = "REPLACE INTO `myTable` (`" . implode('`, `', array_keys($theArray)) . "`) VALUES ('" . implode("', '", $theArray) . "')";
  21. mysql_query($query);
  22.  
  23. if($err = mysql_error())
  24.     throw new Exception(array('query' => $query, 'err' => $err));
  25.  
  26.  
http://php.net/array_combine
May 23 '07 #2

ak1dnar
Expert 100+
P: 1,584
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,INTEL,DELL);

for($i=0;$i<count($ARRAY);$i++)
{
$query='insert into products (p_name) values("'.$ARRAY[$i].'")';
$result=mysql_query($query)or die("Query failed : " . mysql_error());
}

if($result){
echo 'DATA INSERTED';
}else{
echo 'INSERTION FAILED';
}

?>[/PHP]
May 23 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.