473,811 Members | 3,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Insert into table using arrays for field names and values

8 New Member
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("IN SERT 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 3897
ronverdonk
4,258 Recognized Expert Specialist
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 Recognized Expert Specialist
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($array 1);$i++) {
$fields=implode (',', $array1[$i]);
$values="'".imp lode("','", $array2[$i])."'";
$sql="INSERT INTO table_name ($fields) VALUES ($values)";
$res=mysql_quer y($sql)
or die("Insert error: ".mysql_error() );
}[/php]
Ronald
Mar 29 '08 #3
Maarten
8 New Member
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 Recognized Expert Specialist
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
Maarten
8 New Member
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 Recognized Expert Specialist
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 Recognized Expert Specialist
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
Maarten
8 New Member
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 Recognized Expert Specialist
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

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

Similar topics

3
13227
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: Hunter_69. Here is what the form looks like. I have the difficulty of inserting the multiple items selected by the user the first time he visits and uses the screen and then using an UPDATE when he visits later. Model | Original Price | Reduced Price...
1
8754
by: PT | last post by:
I got a problem. And thats..... First of all, I got these three tables. ------------------- ------------------ ---------------------- tblPerson tblPersonSoftware tblSoftware ------------------- ------------------ ---------------------- PID PName PID* SID* SID SWName --- ----- --- --- --- ------ 1 Thomas 1 1 ...
25
11111
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 keep the single users. My question is, how do I get the "Id"-value of a newly inserted address to store it in the referencing user table:
7
21128
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 way of expressing this, but I have a problem with the way lists are represented when converted to strings. Lets say my dictionary is
3
2164
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 where clause is the part I am having trouble with. I want to only insert
1
5252
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 other table. How do I do it? I get error messages when trying different approaches. In the end, I removed the unique key/autoincrement, inserted and ID field in the source and then did copy&append records in the edit menu and changed it all back....
16
3504
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 in a hidden field) I wish the user to be able to edit the data in the table, so I have extracted the records into hiddenfield, textareas, dropdown list and checkbox so that they can make changes. I named these elements as arrays and wish to run an...
0
2157
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 file="../Connections/conn.jsp" %> <% // *** Edit Operations: declare variables // set the form action variable String MM_editAction = request.getRequestURI(); if (request.getQueryString() != null && request.getQueryString().length() > 0) {
4
38388
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 VALUES (Value1, Value2, ...); If (say) the first field (Value1) is an AutoNumber, what value can you put that will preserve the auto-increment function?
0
9726
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
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
10384
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10130
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
9204
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7667
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6887
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
5553
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.