473,379 Members | 1,330 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Insert into table using arrays for field names and values

I've found some answers to my problem on this forum, but not exactly the answer I was looking for. Sorry if I've missed something.

This is my situation:

I am trying to make an insertion into an MySQL table, using an array for the field list AND another array for the values. I know by know that you can't just use:
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO table_name ($array1) VALUES ($array2);
So i've stripped the arrays first. My problem however is that I can only strip one array at the time, so this:[php]foreach ($array as $value)
mysql_query("INSERT INTO table_name VALUES ($array)");[/php]would work, but how can I define the field names, wich are also in a array?

I tried the following, but it doesn't work (didn't really expect it to also)
[php]foreach ($array1 as $value)
foreach ($array2 as $value)
INSERT INTO table_name ($array1) VALUES ($array2);[/php]
I hope you understand this poor explanation. Also, I wasn't sure where to post it (PHP or MySQL), but since my problem seemed more of a PHP issue I thought i'd start here.
Mar 29 '08 #1
15 3821
ronverdonk
4,258 Expert 4TB
Welcome to The Scripts!

Please enclose your posted code in [code] tags (See How to Ask a Question).

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [code] tags in future.

MODERATOR
Mar 29 '08 #2
ronverdonk
4,258 Expert 4TB
Important question on this:
Are the entries of both arrays 1-1, i.e. do the indices of related entries have the same number in both arrays? E.g. is $array1[4] related to $array2[4]?

When this is true, you can just implode() each array and use the result in your select statement. Sample[php]for ($i=0; $i<count($array1);$i++) {
$fields=implode(',', $array1[$i]);
$values="'".implode("','", $array2[$i])."'";
$sql="INSERT INTO table_name ($fields) VALUES ($values)";
$res=mysql_query($sql)
or die("Insert error: ".mysql_error());
}[/php]
Ronald
Mar 29 '08 #3
Sorry about that, I will pay attention to it next time.

Thank you very much for your help Ronald, I'm going to try that right away and keep you posted!
Mar 30 '08 #4
ronverdonk
4,258 Expert 4TB
Important question on this:

Are the entries of both arrays 1-1, i.e. do the indices of related entries have the same number in both arrays? E.g. is $array1[4] related to $array2[4]?
But you can only test that sample when the answer to my question (see quote) is affirmative.

Ronald
Mar 30 '08 #5
But you can only test that sample when the answer to my question (see quote) is affirmative.

Ronald
I'm sorry, forgot to answer that. But the answer is indeed affirmative.

I'm trying to write a content management system, and I've got a form that sends 125 values at the same time. To keep things a bit organised and clear, I thought i'd put those values in 8 different arrays, than merge those arrays. but I didn't know you can't do an Insert from an array (I'm not that advanced yet).

So if I understand correctly, your code converts my array to a string, wich I CAN insert into the db. Genius, thank you very much.

A bit off-topic maybe, I've never quite understood why you have to place the dots in your MySQL statement. In your example:

[PHP]or die("insert error: ".mysql_error());[/PHP]

I mean the dot before mysql_error.

Thanks a lot for your help and patience so far, you really helped me out here
Mar 30 '08 #6
ronverdonk
4,258 Expert 4TB
First the dots. The dot is a concatenation character that connects fields, variables etc. Examples:[php]you want to print a string 'ABCDEF' from 2 different literals ABC and DEF:
echo 'ABC' . 'DEF';

You want to combine the content of 2 variables into 1 variable:
$new_var = $var1 . $var2;

You want to print out a constant value and a function result:
die ("MySQL error: " . mysql_error());

You want to append a string to the end of an existing string:
$string .= "new text";[/php]Ronald
Mar 30 '08 #7
ronverdonk
4,258 Expert 4TB
About your 125 form fields. Why do you store them in separate arrays? I.e. why don't you use the existing, and already used by your form, $_POST array?

E.g. when you have form fields with name 'myname1 , 'myname2'' and the values 'myvalue1' and 'myvalue2' this shows in the $_POST array like
Expand|Select|Wrap|Line Numbers
  1. Array {
  2.           [myname1] => myvalue1
  3.           [myname2] => myvalue2
  4.       }
And you can walk that $_POST array with[php]foreach ($_POST as $name => $value) {
// here you have the form field name and the value
// so you can build your SQL string here
}[/php]Ronald
Mar 30 '08 #8
I think the only appropriate answer would be; lack of knowledge. But thanks a lot for the lead. I'm not sure if I fully understand it yet, but I'm gonna look into it straight away!
Mar 30 '08 #9
ronverdonk
4,258 Expert 4TB
I think the only appropriate answer would be; lack of knowledge. But thanks a lot for the lead. I'm not sure if I fully understand it yet, but I'm gonna look into it straight away!
Any time you need help on this, don't hesitate to ask for mit and show the code here (within code tags please).

I propose this, becaus it seems a waste of a lot of lines of code with all these arrays you were talking about.

Ronald
Mar 30 '08 #10
Any time you need help on this, don't hesitate to ask for mit and show the code here (within code tags please).

I propose this, becaus it seems a waste of a lot of lines of code with all these arrays you were talking about.

Ronald
That sounds good of course, but I would still have to make a foreach statement for every field name if I understand correctly. So wouldn't I end up with 125 foreach statements?
Mar 30 '08 #11
That sounds good of course, but I would still have to make a foreach statement for every field name if I understand correctly. So wouldn't I end up with 125 foreach statements?
Nevermind, I get it! It's so simpleyet so clever and I'd never thought about it if you hadn't pointed it out for me. Learned a lot within a day!
Mar 30 '08 #12
Okay, so I tried what you said, and it works, but...

Now it's adding a new row for each value that I send with the form. This is my code:

[PHP]if (isset($_POST['submit'])) {

if ($dbc=@mysql_connect('localhost', 'x', 'x')){

print "Connected to db!<p />";

//select database
if (@mysql_select_db ('x')) {

print "db selected<p />";

}else {

die('Could not select that database because'.mysql_error().'<p />');
}

//Insert data from into the database
foreach ($_POST as $name => $value) {
mysql_query("INSERT INTO table ($name) VALUES ($value)");

}

mysql_close();
}else {

die('Could not connect to MySQL because:'.mysql_error.'<p />');
}
}[/PHP]


How can I make sure that the values per submitted form will all be inserted in one row?
Mar 30 '08 #13
ronverdonk
4,258 Expert 4TB
No, that way you have 125 inserts. Just do as was shown in the beginning, but now you make

1. an array of the keys in the $_POST array and implode them
2. an array of the values in the $_POST array and implode them

See this sample:[php]$fields=implode(',', array_keys($_POST));
$values="'".implode("','", array_values($_POST))."'";
$sql="INSERT INTO table_name ($fields) VALUES ($values)";
$res=mysql_query($sql)
or die("Insert error: ".mysql_error());[/php]All field names and corresponding values inserted in one statement. Try it out.

Ronald
Mar 30 '08 #14
Works like a charm!

My question has totally been answered. Just have to figure out a way to filter the submit value out of the array_keys, since my script now wants to have a column for submit.

But I'll manage to do that. Thanks again for your help! (and patience), I really learned a lot!
Mar 30 '08 #15
ronverdonk
4,258 Expert 4TB
Welcome any time. See you around.

Ronald
Mar 30 '08 #16

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

Similar topics

3
by: jason | last post by:
How does one loop through the contents of a form complicated by dynamic construction of checkboxes which are assigned a 'model' and 'listingID' to the NAME field on the fly in this syntax:...
1
by: PT | last post by:
I got a problem. And thats..... First of all, I got these three tables. ------------------- ------------------ ---------------------- tblPerson tblPersonSoftware ...
25
by: Andreas Fromm | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, Im building an user database with many tables keeping the data for the Address, Phone numbers, etc which are referenced by a table where I...
7
by: David Bear | last post by:
I have a dictionary that contains a row of data intended for a data base. The dictionary keys are the field names. The values are the values to be inserted. I am looking for a good pythonic...
3
by: Mike Charney | last post by:
I have a two part question: First I want to insert data into a table and I am using the following command: INSERT INTO tblmain SELECT field1, field2, etc... FROM tblimport WHERE ?????? The...
1
by: Jan | last post by:
I have a table with autoincrement unique ID plus name (required not to be blank) and other fields. I have a list of names in another table and would like to do insert to the name field of the...
16
by: Ian Davies | last post by:
Hello Needing help with a suitable solution. I have extracted records into a table under three columns 'category', 'comment' and share (the category column also holds the index no of the record...
0
ak1dnar
by: ak1dnar | last post by:
There is a Error getting while i am entering records using this jsp file. <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %> <%@ include...
4
by: Lyn | last post by:
Hi, Is there an "easy" way to write a full record (all fields) using "INSERT INTO..." into a table which has an AutoNumber field? Normally, to write a full new record I would use: INSERT INTO...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.