473,803 Members | 3,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

5 New Member
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
2 1929
pbmods
5,821 Recognized Expert Expert
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
1,584 Recognized Expert Top Contributor
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]
May 23 '07 #3

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

Similar topics

14
3785
by: Kevin Knorpp | last post by:
Hello. I need to be able to extract the data from the attached file (or any file in the same format) so that I can work with the data in PHP. I'm fairly comfortable with using PHP with databases, arrays, etc. but have not worked with binary data files. http://www.performancecentral.net/C...3Loop/3Loop.php click on "Download Performance".
11
2548
by: Colin Steadman | last post by:
Hope this makes sense! I'm building an ASP page which allows uses to add items to an invoice via a form, ie: Item No Part No Order No Quanity Units Price VAT ------- ------- -------- ------- ----- ----- --- .... ... ... ... ... ... ... <Add item> <Submit>
32
6526
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains on the "bit = false;" stating that bit is read-only.
4
3966
by: MrBiggles | last post by:
Here's the sitch: I read in a csv file with 60000 lines (20 fields per record), and store the data to a local array. The file is read in and stored just fine and pretty quick. Now, if I try to assign that array to a session variable it chokes. e.g. create array and load each element with a row from the file (btw, each row is an array as well, using fgetcsv()). When local array is loaded, I assign to session var as so: $_SESSION =...
10
2862
by: Jaye | last post by:
Hi. I am a relative newbie to ASP and I am working on an application that uses ASP and an Oracle 9i database. I have a form that allows the user to query the database by selecting a client name(s) from a listbox and also set a time period for the search by selecting a start date and end date. Once the query is executed a form letter(s) is (are) generated to the client(s) that details the products that have been purchased during the time...
3
8753
by: mrajanikrishna | last post by:
Hi Friends, I am accepting a number from the user entered in a textbox. I want to assign to a variable in my code and assignt this to that variable. double num1 = (double)txtNum1.text; this produced an error
6
3006
by: dawnerd | last post by:
Hello everyone. I have a question, or problem if you will, that I'm sure someone knows the answer to. I have a database that stores information on a given user. The information is stored in a serialized array. This works flawlessly when using only single line text. When I tried to store multiline text, the problem arose. When the serialized data is deserialized, the array breaks. Any suggestions?
10
4971
by: cmdolcet69 | last post by:
Public ArrList As New ArrayList Public bitvalue As Byte() Public Sub addvalues() Dim index As Integer ArrList.Add(100) ArrList.Add(200) ArrList.Add(300) ArrList.Add(400) ArrList.Add(500)
12
13569
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} System.Text.UTF8Encoding str = new System.Text.UTF8Encoding(); string s = new string((char)107, 1); s += new string((char)62, 1);
0
9564
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6841
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.