Jump to content

Archived

This topic is now archived and is closed to further replies.

earl_dc10

Insert Query loops

Recommended Posts

Im creating an admin page where I can edit all of my tables and stuff like that. I use 1 form for everything and just apply it to seperate tables with radio buttons (selecting the different tables). anyway, if I want to add a new row or update a new row, I update the form with the number of text fields that correspond with the number of fields in the table, this is stored in an array. since the number of fields can vary, how would I right an Insert/Update query to accomodate that?

I thought of having just 1 Insert and then the rest Update off of that Insert, but if I have 2 that are the same it would do both rows instead of the new one.

Thanks!

EDIT -> Inspiration just struck, but I'll ask anyway to see if there are any better ideas than mine
this is my idea but we'll see what you come up with, since all my tables have id's I'll just insert the new id and run the updates off of that

Share this post


Link to post
Share on other sites
I'm not sure if I understood your post 100%, but what I gained from it was, that you want to build a query but it could have any number of fields - which are stored in an array. Hope I got that correct... Heres what I would do:

[code]<?php
//Assuming field names and data are stored in seperate arrays but with the same keys
$fields = array("name","address","telephone");
$data = array("Kris","1 High St.","123123");

$query = "INSERT INTO `table` (";
for($i=0; $i<count($fields); $i++) {
    $query .= "`$fields[$i]`,";
}
$query = substr($query,0,-1).") VALUES (";
for($i=0; $i<count($data); $i++) {
    $query .= "'$fields[$i]',";
}
$query = substr($query,0,-1).")";
mysql_query($query) or die(mysql_error());
?>[/code]

Share this post


Link to post
Share on other sites
looks good, but Im a little confused why you want to shop off the end of $query
[code]
$query = substr($query,0,-1).") VALUES (";
[/code]

also minor change
[code]
$query = substr($query,0,-1).") VALUES (";
for($i=0; $i<count($data); $i++) {
    $query .= "'$fields[$i]',"; // for values should be $data[$i], correct?
[/code]

Thanks for the input!

Share this post


Link to post
Share on other sites
Sorry, yes, that should be $data[$i] - I really shouldn't copy and paste...
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]looks good, but Im a little confused why you want to shop off the end of $query[/quote]Its to get rid of the trailing comma.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.