How to combine MULTIPLE INSERTS into database? - php
My submission form works fine but there are 3 insert queries in the code.
Let me explain why.
Insert Query 1 allows the selected value of the dropdown menu on the form to be inserted into the database table.
Insert Query 2 allows the values inside of a text area box to be inserted into individual separate rows
Insert Query 3 allows all other data to be inserted.
The HTML looks like this (it is wrapped inside of a code but I'll just include a few snippets)...
The dropdown menu:
<select name="Name" id="">
<?php
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['Name']; ?>"><?php echo $row['Name']; ?> </option>
<?php
} ?>
</select>
Yes, I know....it's not using mysqli or PDO at the moment....I've been told that numerous times....
The textarea which will hold multiple lines of values:
<textarea rows="10" cols="35" name="BachelorsDegrees"> </textarea>
Everything else on the form is just <input>. Pretty simple.
The PHP...
Inserting the text area values into the database:
//Writes the information to the database
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $BachelorsDegrees) {
mysql_query("INSERT INTO Colleges (BachelorsDegrees) VALUES ('$BachelorsDegrees')") or die(mysql_error()) ;
}
Inserting the selected drop down menu value:
//if (isset ($_POST['upload']))
//{
$Name=trim($_POST['Name']);
$ins=mysql_query("INSERT INTO Colleges (Name) VALUES ('$Name')") or die(mysql_error()) ;
if($ins)
{
echo "<br>".$Name."inserted";
}
else
{
echo mysql_error();
}
//}
And inserting everything else:
mysql_query("INSERT INTO Colleges (schoollogo,Motto,Description,Type,ReligiousAffiliation,OtherPartnerships,GenderAdmission,TermType,EntranceExam,EntranceExamDate,TotalEnrolled,collegewebsite,ContactInfo,CampusLocations,Certifications,Diplomas,AssociateDegrees,MastersDegrees,DoctorateDegrees,SpecialDegreePrograms,Accreditation,CostofTuitionLocal,CostofTuitionForeign,Housing,AcceptanceRate,CoE,CoD) VALUES ('$schoollogo', '$Motto', '$Description', '$Type', '$ReligiousAffiliation', '$OtherPartnerships', '$GenderAdmission', '$TermType', '$EntranceExam', '$EntranceExamDate', '$TotalEnrolled', '$collegewebsite', '$ContactInfo', '$CampusLocations', '$Certifications', '$Diplomas', '$AssociateDegrees', '$MastersDegrees', '$DoctorateDegrees','$SpecialDegreePrograms','$Accreditation','$CostofTuitionLocal','$CostofTuitionForeign','$Housing','$AcceptanceRate','$CoE','$CoD')") or die(mysql_error()) ;
When inserted into the database, multiple rows of data are shown.
1 row = College Name (from the drop down menu)
2nd row = the degrees from the text area
3rd row = all other data
How do I combine all insert queries into one query so that I only have 1 row?
Generally you build a single query.
Take each of the values and add them to the query (probably as parameters).
However you appear to have a single table, rather than multiple tables. You would expect to have a table of colleges, and then another table that has a row for each course each college does.
An alternative would be for your first query to return the unique id of the inserted row, and then all your other inserts also insert this id with an ON DUPLICATE KEY UPDATE clause. But this would be messy and slow
EDIT.
Example of a single query. Note that I have just used the deprecated mysql_* functions as that is what you are using, but you should switch to either the mysqli_* functions or to PDO . Either way escaping the data or using parameterised queries is VERY important.
This inserts one record for the college, then uses mysql_insert_id() to get the id field of the inserted field (assuming you have one). This id is then used to insert each of the courses to another table listing the courses for each college:-
<?php
$Name = mysql_real_escape_string(trim($_POST['Name']));
$schoollogo = mysql_real_escape_string(trim($_POST['schoollogo']));
$Motto = mysql_real_escape_string(trim($_POST['Motto']));
$Description = mysql_real_escape_string(trim($_POST['Description']));
$Type = mysql_real_escape_string(trim($_POST['Type']));
$ReligiousAffiliation = mysql_real_escape_string(trim($_POST['ReligiousAffiliation']));
$OtherPartnerships = mysql_real_escape_string(trim($_POST['OtherPartnerships']));
$GenderAdmission = mysql_real_escape_string(trim($_POST['GenderAdmission']));
$TermType = mysql_real_escape_string(trim($_POST['TermType']));
$EntranceExam = mysql_real_escape_string(trim($_POST['EntranceExam']));
$EntranceExamDate = mysql_real_escape_string(trim($_POST['EntranceExamDate']));
$TotalEnrolled = mysql_real_escape_string(trim($_POST['TotalEnrolled']));
$collegewebsite = mysql_real_escape_string(trim($_POST['collegewebsite']));
$ContactInfo = mysql_real_escape_string(trim($_POST['ContactInfo',
$CampusLocations = mysql_real_escape_string(trim($_POST['CampusLocations']));
$Certifications = mysql_real_escape_string(trim($_POST['Certifications']));
$Diplomas = mysql_real_escape_string(trim($_POST['Diplomas']));
$AssociateDegrees = mysql_real_escape_string(trim($_POST['AssociateDegrees']));
$MastersDegrees = mysql_real_escape_string(trim($_POST['MastersDegrees']));
$DoctorateDegrees = mysql_real_escape_string(trim($_POST['DoctorateDegrees']));
$SpecialDegreePrograms = mysql_real_escape_string(trim($_POST['SpecialDegreePrograms']));
$Accreditation = mysql_real_escape_string(trim($_POST['Accreditation']));
$CostofTuitionLocal = mysql_real_escape_string(trim($_POST['CostofTuitionLocal']));
$CostofTuitionForeign = mysql_real_escape_string(trim($_POST['CostofTuitionForeign']));
$Housing = mysql_real_escape_string(trim($_POST['Housing']));
$AcceptanceRate = mysql_real_escape_string(trim($_POST['AcceptanceRate']));
$CoE = mysql_real_escape_string(trim($_POST['CoE']));
$CoD = mysql_real_escape_string(trim($_POST['CoD']));
$ins = mysql_query("INSERT INTO Colleges (Name, schoollogo, Motto, Description,Type, ReligiousAffiliation, OtherPartnerships, GenderAdmission, TermType, EntranceExam, EntranceExamDate, TotalEnrolled, collegewebsite, ContactInfo, CampusLocations, Certifications, Diplomas, AssociateDegrees, MastersDegrees, DoctorateDegrees, SpecialDegreePrograms, Accreditation, CostofTuitionLocal, CostofTuitionForeign, Housing,AcceptanceRate, CoE, CoD)
VALUES ('$Name',
'$schoollogo',
'$Motto',
'$Description',
'$Type',
'$ReligiousAffiliation',
'$OtherPartnerships',
'$GenderAdmission',
'$TermType',
'$EntranceExam',
'$EntranceExamDate',
'$TotalEnrolled',
'$collegewebsite',
'$ContactInfo',
'$CampusLocations',
'$Certifications',
'$Diplomas',
'$AssociateDegrees',
'$MastersDegrees',
'$DoctorateDegrees',
'$SpecialDegreePrograms',
'$Accreditation',
'$CostofTuitionLocal',
'$CostofTuitionForeign',
'$Housing',
'$AcceptanceRate',
'$CoE',
'$CoD')") or die(mysql_error()) ;
if($ins)
{
echo "<br>".$Name."inserted";
$CollegeId = mysql_insert_id();
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
foreach ($textAr as $BachelorsDegrees)
{
mysql_query("INSERT INTO Colleges_Courses (CollegeId, BachelorsDegrees)
VALUES (".(int)$CollegeId.", '".mysql_real_escape_string(trim($BachelorsDegrees))."')") or die(mysql_error()) ;
}
}
else
{
echo mysql_error();
}
If you wanted to use multiple inserts, updating each field in turn (which would be very slow and serves no useful purpose here), then you can insert multiple times with a column value and insert it if the row already exists. In this case assuming you have an auto increment id field:-
<?php
$Name = mysql_real_escape_string(trim($_POST['Name']));
$schoollogo = mysql_real_escape_string(trim($_POST['schoollogo']));
$Motto = mysql_real_escape_string(trim($_POST['Motto']));
$Description = mysql_real_escape_string(trim($_POST['Description']));
$Type = mysql_real_escape_string(trim($_POST['Type']));
$ReligiousAffiliation = mysql_real_escape_string(trim($_POST['ReligiousAffiliation']));
$OtherPartnerships = mysql_real_escape_string(trim($_POST['OtherPartnerships']));
$GenderAdmission = mysql_real_escape_string(trim($_POST['GenderAdmission']));
$TermType = mysql_real_escape_string(trim($_POST['TermType']));
$EntranceExam = mysql_real_escape_string(trim($_POST['EntranceExam']));
$EntranceExamDate = mysql_real_escape_string(trim($_POST['EntranceExamDate']));
$TotalEnrolled = mysql_real_escape_string(trim($_POST['TotalEnrolled']));
$collegewebsite = mysql_real_escape_string(trim($_POST['collegewebsite']));
$ContactInfo = mysql_real_escape_string(trim($_POST['ContactInfo',
$CampusLocations = mysql_real_escape_string(trim($_POST['CampusLocations']));
$Certifications = mysql_real_escape_string(trim($_POST['Certifications']));
$Diplomas = mysql_real_escape_string(trim($_POST['Diplomas']));
$AssociateDegrees = mysql_real_escape_string(trim($_POST['AssociateDegrees']));
$MastersDegrees = mysql_real_escape_string(trim($_POST['MastersDegrees']));
$DoctorateDegrees = mysql_real_escape_string(trim($_POST['DoctorateDegrees']));
$SpecialDegreePrograms = mysql_real_escape_string(trim($_POST['SpecialDegreePrograms']));
$Accreditation = mysql_real_escape_string(trim($_POST['Accreditation']));
$CostofTuitionLocal = mysql_real_escape_string(trim($_POST['CostofTuitionLocal']));
$CostofTuitionForeign = mysql_real_escape_string(trim($_POST['CostofTuitionForeign']));
$Housing = mysql_real_escape_string(trim($_POST['Housing']));
$AcceptanceRate = mysql_real_escape_string(trim($_POST['AcceptanceRate']));
$CoE = mysql_real_escape_string(trim($_POST['CoE']));
$CoD = mysql_real_escape_string(trim($_POST['CoD']));
$ins = mysql_query("INSERT INTO Colleges (Id, Name)
VALUES (NULL, '$Name')";
if($ins)
{
echo "<br>".$Name."inserted";
$CollegeId = mysql_insert_id();
$ins = mysql_query("INSERT INTO Colleges (Id, schoollogo)
VALUES (".(int)$CollegeId.", '$schoollogo') ON DUPLICATE KEY UPDATE schoollogo = VALUES(schoollogo)";
$ins = mysql_query("INSERT INTO Colleges (Id, Motto)
VALUES (".(int)$CollegeId.", '$Motto') ON DUPLICATE KEY UPDATE Motto = VALUES(Motto)";
$ins = mysql_query("INSERT INTO Colleges (Id, Description)
VALUES (".(int)$CollegeId.", '$Description') ON DUPLICATE KEY UPDATE Description = VALUES(Description)";
$ins = mysql_query("INSERT INTO Colleges (Id, Type)
VALUES (".(int)$CollegeId.", '$Type') ON DUPLICATE KEY UPDATE Type = VALUES(Type)";
//etc
$text = trim($_POST['BachelorsDegrees']);
$textAr = explode("\n", $text);
foreach ($textAr as $BachelorsDegrees)
{
mysql_query("INSERT INTO Colleges_Courses (CollegeId, BachelorsDegrees)
VALUES (".(int)$CollegeId.", '".mysql_real_escape_string(trim($BachelorsDegrees))."')") or die(mysql_error()) ;
}
}
else
{
echo mysql_error();
}
You can use multi-query to combine multiple sql queries into one single query.
Example with Multi-Query
$mysqli = new mysqli("example.com", "user", "password", "database");
$sql = "INSERT INTO table VALUES ('My First Table'); ";
$sql.= "INSERT INTO table VALUES ('My Second Table'); ";
$mysqli->multi_query($sql);
Related
Facing problem in insert value into multiple row
I am writing a PHP script where it takes data from a database table where there are more than ten rows. After taking all the rows' input from the database it adds with a variable. After that those sum value is inserted to all the rows of another database. My code is working fine in fetching all the rows' data from the database and add a number to that value. But it does not insert new data into another database. I am not getting any error messages. My code: <?php include("dbconnect.php"); $query = "SELECT * FROM down_value"; $down_value_db = $conn->query($query); /*Time Deference Variable*/ $td1=1; $date = date("Y-m-d"); while ($row = mysqli_fetch_assoc($down_value_db)) { /*Value from db*/ $s_data1=$row['TGI_R']; /* Simulated Data*/ $e_data1=$s_data1+$td1; //Insert Data into database $insert = $conn->query("INSERT into down_simulation (TGI_R,date) VALUES ('$e_data1', '$date')"); if($insert){ echo "$e_data1 <br/>Successfully data Recorded <br/>"; }else{ echo "Error"; } } ?>
you must add your select values to array and then with for loop insert this values to another table. $query = mysqli_query($conn,"select tgi_r from down_value"); $tgi_r_array = array(); $date_time = date("Y-m-d H:i:s"); while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){ $tgi_r_array[] = $row['tgi_r']+1; } for ($i = 0; $i < count($tgi_r_array); $i++){ $insert = mysqli_query($conn, "insert into down_simulation(tgi_r,date) values ('" . $tgi_r_array[$i] . "', '" . $date_time . "')"); } print_r($tgi_r_array);
Prevent Form from inserting data multiple times into database
Trying to insert form data into mysql database, my issues is as the user submits the form the data gets inserted twice into database. I know that I am doing something wrong with my 2nd query $query_file = "INSERT INTO upperbit_files... statment as when I remove the whole if loop if(mysqli_query($dbc, $query_info)){...} the form gets submitted once as expected. Basically I need to insert data into 2 tables. One is for general product info and the other one is to store photos relating to that product both the table are connected via a global variable $advert_id. I am using 2 separate queries Table1: advert_sell_category1, is for general product info Table2: upperbit_files, is to store details of the images uploaded But for some reason the 1st query relating to general product info is getting inserted twice into database and the irony is both the time the $advert_id is the same. Below is my code and a screenshot of the database for your understanding, if(isset($_POST['postad'])){ $adtype = $_POST['offering_type']; $manufacturer = mysqli_real_escape_string($dbc, $_POST['manufaturer']); $mediafile = mysqli_real_escape_string($dbc,$_POST['mediafile']); $GLOBALS['advrt_post_id'] = crypto_rand_secure(10, 100000); $query_info = "INSERT INTO advert_sell_category1(advert_id,manufacturer,image_file) VALUES('$advrt_post_id','$manufacturer','$mediafile')"; $result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc)); if(mysqli_query($dbc, $query_info)){ $last_id = mysqli_insert_id($dbc); $query_link_id = "SELECT advert_id FROM advert_sell_category1 WHERE id = '$last_id' "; $result_id = mysqli_query($dbc, $query_link_id); while ($row = mysqli_fetch_assoc($result_id)) { $link_id = $row['advert_id']; if(!empty($mediafile)){ $media_file = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafile'])); $media_file = array_filter($media_file); $media_file_size = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafilesize'])); $media_file_size = array_filter($media_file_size); $media_file_type = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafiletype'])); $media_file_type = array_filter($media_file_type); for ($var = 0; $var < sizeof($media_file); $var++){ $query_file = "INSERT INTO upperbit_files(file,size,type,link_id) VALUES ('$media_file[$var]','$media_file_size[$var]','$media_file_type[$var]','$link_id')"; $result_file = mysqli_query($dbc, $query_file) or die(mysqli_error($dbc)); } } } }
/********** Your Code ************/ $result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc)); if(mysqli_query($dbc, $query_info)){ /**********************/ See here in if statement you are calling mysqli_query() second time so same data is inserted twice. Use following code to solve your problem /********** Suggested Code ************/ $result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc)); if(mysqli_affected_rows()>0){ /**********************/
Insert data array in SQL after searching from another SQL table
I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array. foreach($members as $key=>$value){ $res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'"); if ($res === false) { echo mysql_error(); die; } $row = mysql_fetch_assoc($res); if($row['id']) { $members_name[]=$row['name'];//array for name } } Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format: (The left side are the rows in my TABLE register) mem_0_id-->$members[0] mem_0_name-->$members_name[0] mem_1_id-->$members[1] mem_1_name-->$members_name[1] mem_2_id-->$members[2] mem_2_name-->$members_name[2] mem_3_id-->$members[3] mem_3_name-->$members_name[3] mem_4_id-->$members[4] mem_4_name-->$members_name[4] How can I insert in this way? using just a single INSERT statement?
haven't tried this, but here is my answer anyway :) $query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])"; for($i=1; $i<count($members); $i++) { $query .= ", ($members[$i], $members_name[$i])"; } then try to execute the query..
Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another? If so then you can do the whole thing like this. $memberIds = implode(',', $members); // comma separated list of member ids $query = "insert into register (id, name) select id, name from users where id in ($memberIds)"; mysql_query($query); // this will select and insert in one go If you do need to keep the array in memory, then it's still a good idea to get it all out at once $memberIds = implode(',', $members); // comma separated list of member ids $query = "select id, name from users where id in ($memberIds)"; $res = mysql_query($query); while ($row = mysql_fetch_assoc($res)) { $memberData[] = $row; } That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times. Then you can build a statement to insert multiple rows: $sql = "insert into register (id, name) values "; $sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")"; for($i = 1; $i < count($memberData); $i++) { $sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')"; } mysql_query($sql); It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do echo $sql; you should get something like insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice'); You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.
Inserting array data using mysql insert id and if statements
Ok so whilst I have been working on my PHP and MySQL skills I am new to inserting data into multiple tables in one go. I have done some reading around the subject and I appreciate the basics and the importance of normalised data etc and as such the need to put the information into various tables. I have pieced the code below together from some of my previous work as well as the tutorial offered at http://www.desilva.biz/mysql/insertid.html . The issue I currently face is that the tutorial I learnt the code from for inputting into various tables was not based around an array of data and whilst I have got it to almost work I cannot use my fuelrecords_id because where I have to call it in my current code it has not yet been defined. Therefore to make my code work at present I just have to use a comma for the column. Finally I would like to perfect a way to make the if statements work correctly with the array data so if a 0 or blank is submitted as part of the array a new row is not inserted with just 0's in my database tables for that respective row of data <?php $wedrf=trim($_POST['FR_WE']); list($d, $m, $y) = explode('/', $wedrf); $mk=mktime(0, 0, 0, $m, $d, $y); $wed_refor=strftime('%Y-%m-%d',$mk); $con = mysql_connect("ip","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("jbsrint", $con); //New Code $row_data = array(); foreach($_POST['VEH_LIST_REG'] as $row=>$VEH_LIST_REG) { $WEDATE=$wed_refor; $VEH_LIST_REG=mysql_real_escape_string($VEH_LIST_REG); $FR_DIE_L=mysql_real_escape_string($_POST['FR_DIE_L'][$row]); $FR_DIE_C=mysql_real_escape_string($_POST['FR_DIE_C'][$row]); $FR_PET_L=mysql_real_escape_string($_POST['FR_PET_L'][$row]); $FR_PET_C=mysql_real_escape_string($_POST['FR_PET_C'][$row]); $FR_OIL_L=mysql_real_escape_string($_POST['FR_OIL_L'][$row]); $FR_OIL_C=mysql_real_escape_string($_POST['FR_OIL_C'][$row]); $row_data[] = "(',', '$VEH_LIST_REG', '$WEDATE')"; $row_data1[] = "(',','$FR_DIE_L', '$FR_DIE_C', ',')"; $row_data2[] = "(',', '$FR_PET_L', '$FR_PET_C', ',')"; $row_data3[] = "(',', '$FR_OIL_L', '$FR_OIL_C', '$FR_OIL_C')"; } if (!empty($row_data)) { $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data); #$result = mysql_query( $query); # get fuelrecord id $fuelrecords_ID = mysql_insert_id(); # if the user submitted diesel information if( isset($FR_DIE_L) ) { # and insert the diesel details $sql = "INSERT INTO fuelrecords_die(FRD_ID,FR_DIE_L,FR_DIE_C,fuelrecords_ID) VALUES ".implode(',', $row_data1); $result = mysql_query( $sql); } # if the user submitted petrol information if( isset($FR_PET_L) ) { # and insert the diesel details $sql = "INSERT INTO fuelrecords_pet(FRP_ID,FR_PET_L,FR_PET_C,fuelrecords_ID) VALUES ".implode(',', $row_data2); $result = mysql_query( $sql); } # if the user submitted oil information if( isset($FR_OIL_L) ) { # and insert the oil details $sql = "INSERT INTO fuelrecords_oil(FRO_ID,FR_OIL_L,FR_OIL_C,fuelrecords_ID) VALUES ".implode(',', $row_data3); $result = mysql_query( $sql); } if (mysql_query($query)) echo '<font color=\"FFFFFF\" size=\"3px\">Successful inserted</font>'; else echo '<font color=\"FFFFFF\" size=\"3px\">Insert failed</font>'; } ?> <?php mysql_close($con) ?> Tables are as follows: fuelrecords FR_ID (Auto increment) VEH_LIST_REG FR_WE fuelrecords_die FRD_ID (AUTO INCREMENT) FR_DIE_L FR_DIE_C fuelrecords_ID (foreign ID from fuelrecords) fuelrecords_pet FRP_ID (AUTO INCREMENT) FR_PET_L FR_PET_C fuelrecords_ID (foreign ID from fuelrecords) fuelrecords_oil FRO_ID (AUTO INCREMENT) FR_OIL_L FR_OIL_C fuelrecords_ID (foreign ID from fuelrecords) Basically the purpose is to log vehicle fuel usage and cost. As there wont always be data for petrol, diesel and oil hence the separate tables so only needed dat is logged. Hope this clarifies A always all help and assistance is much appreciated.
If I understand your code correctly you have 4 tables: fuelrecords, fuelrecords_die, fuelrecords_pet, fuelrecords_oil. The 3 tables fuelrecords_die, fuelrecords_pet, fuelrecords_oil each have a foreign key fuelrecords_id to fuelrecords.fr_id. You now want to insert multiple tuples into fuelrecords and, if additional data is provided, multiple tuples into the other 3 tables. I assume the fuelrecords.fr_id column is a auto incrementing primary key. To insert multiple tuples into fuelrecords and to have them each have a new fr_id, you just don't pass a value for the column fr_id. This is equivalent to passing NULL as value. MySQL will then automatically insert unique consecutive numbers for each tuple. After that you can call mysql_insert_id() to get the first inserted id. Using mysql_affected_rows() you can get the number of inserted tuples. This is enough information to get the id for all lastly inserted tuples. The first is mysql_insert_id()+0 the second is mysql_insert_id()+1, ..., the last is mysql_insert_id()+(mysql_affected_rows()-1). In the next step you iterate over your input data again and insert the fuelrecords_id into each of the tuples for the other 3 tables, using the above mentioned method. If $i is the index of your input data $_POST['FR_DIE_L'][$i] (starting at $i==0), the fuelrecords_id will be mysql_insert_id()+$i. You are only allowed to iterate to mysql_insert_id()+mysql_affected_rows()-1, but you will probably have the same count of POST-data anyways. A much simpler but slightly less efficient way is to just do one insert into fuelrecords and then one insert into the other 3 tables for each single POST-data object. You won't have to calculate the fuelrecords_id as mysql_insert_id() will give you the correct id after each insert. <?php $wedrf=trim($_POST['FR_WE']); list($d, $m, $y) = explode('/', $wedrf); $mk=mktime(0, 0, 0, $m, $d, $y); $wed_refor=strftime('%Y-%m-%d',$mk); $row_data = array(); // shorthand for mysql_real_escape_string function esc($value) { return mysql_real_escape_string($value); } // all tuples for fuelrecords to be inserted foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) { $row_data[] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')"; } if (!empty($row_data)) { $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data); $result = mysql_query($query); # get first fuelrecord id $first_fuelrecords_id = mysql_insert_id(); // all tuples for the other 3 tables. insert only if data is givin. $die_data = array(); $pet_data = array(); $oil_data = array(); foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) { // calculate the right fuelrecords_id for this tuple $fuelrecords_id = (int)($first_fuelrecords_id + $row); // insert for fuelrecords_die if (isset($_POST['FR_DIE_L'][$row])) { $die_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_DIE_L'][$row])."', '".esc($_POST['FR_DIE_C'][$row])."')"; } // insert for fuelrecords_pet if (isset($_POST['FR_PET_L'][$row])) { $pet_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_PET_L'][$row])."', '".esc($_POST['FR_PET_C'][$row])."')"; } // insert for fuelrecords_oil if (isset($_POST['FR_OIL_L'][$row])) { $oil_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_OIL_L'][$row])."', '".esc($_POST['FR_OIL_C'][$row])."')"; } } // insert the tuples into fuelrecords_die if (!empty($die_data)) { $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data); $result = mysql_query( $sql); } // insert the tuples into fuelrecords_pet if (!empty($pet_data)) { $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data); $result = mysql_query( $sql); } // insert the tuples into fuelrecords_oil if (!empty($oil_data)) { $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data); $result = mysql_query( $sql); } } ?> A small off-topic addition: Try not to use upper case variable names. Upper case identifiers are usually preserved for constants: define("MY_SHORT_PI", 3.14159265); define("MY_CONST", "foobar"); $my_variable = "bat"; echo "I am a constant ".MY_SHORT_PI; echo "Me too ".MY_CONST; echo "I am a variable ".$my_variable; This won't have any effect on the PHP interpreter. It's just a common notation to make your code readable for others. There are many style guides out there like the one from PEAR. Second Example (see comments) <?php $wedrf=trim($_POST['FR_WE']); list($d, $m, $y) = explode('/', $wedrf); $mk=mktime(0, 0, 0, $m, $d, $y); $wed_refor=strftime('%Y-%m-%d',$mk); // VALUES strings for fuelrecords $row_data = array(); // temporary storage for just _L and _C values $die_data_tmp = array(); $pet_data_tmp = array(); $oil_data_tmp = array(); // VALUES strings for the three tables $die_data = array(); $pet_data = array(); $oil_data = array(); // shorthand for mysql_real_escape_string function esc($value) { return mysql_real_escape_string($value); } // all tuples for fuelrecords to be inserted foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) { // check if diesel values are greater than 0 if (0 < (int)$_POST['FR_DIE_L'][$row] && 0 < (int)$_POST['FR_DIE_C'][$row]) $die_data_tmp[$row] = array($_POST['FR_DIE_L'][$row], $_POST['FR_DIE_C'][$row]); // check if petrolium values are greater than 0 if (0 < (int)$_POST['FR_PET_L'][$row] && 0 < (int)$_POST['FR_PET_C'][$row]) $pet_data_tmp[$row] = array($_POST['FR_PET_L'][$row], $_POST['FR_PET_C'][$row]); // check if oil values are greater than 0 if (0 < (int)$_POST['FR_OIL_L'][$row] && 0 < (int)$_POST['FR_OIL_C'][$row]) $oil_data_tmp[$row] = array($_POST['FR_OIL_L'][$row], $_POST['FR_OIL_C'][$row]); // check if at least one of the 3 tables will get tuples. if not just continue // with the next and don't assign this fuelrecord tuple to $row_data if (! isset($die_data_tmp[$row]) && ! isset($pet_data_tmp[$row]) && ! isset($oil_data_tmp[$row])) continue; // all values are at least 1, so add this tuple to our inserts $row_data[$row] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')"; } if (!empty($row_data)) { $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data); $result = mysql_query($query); # get first fuelrecord id $current_fuelrecords_id = mysql_insert_id(); // all tuples for the other 3 tables. insert only if data is givin. foreach($row_data as $row => $VEH_LIST_REG) { // insert for fuelrecords_die if (isset($die_data_tmp[$row])) { $die_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($die_data_tmp[$row][0])."', '".esc($die_data_tmp[$row][1])."')"; } // insert for fuelrecords_pet if (isset($pet_data_tmp[$row])) { $pet_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($pet_data_tmp[$row][0])."', '".esc($pet_data_tmp[$row][1])."')"; } // insert for fuelrecords_oil if (isset($oil_data_tmp[$row])) { $oil_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($oil_data_tmp[$row][0])."', '".esc($oil_data_tmp[$row][1])."')"; } // increment the fuelrecords_id for the next tuple. ++$current_fuelrecords_id; } // insert the tuples into fuelrecords_die if (!empty($die_data)) { $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data); $result = mysql_query( $sql); } // insert the tuples into fuelrecords_pet if (!empty($pet_data)) { $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data); $result = mysql_query( $sql); } // insert the tuples into fuelrecords_oil if (!empty($oil_data)) { $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data); $result = mysql_query( $sql); } } ?>
inserting values from a loop
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'"; $result1 = mysql_query($sql1); while ($row1 = mysql_fetch_assoc($result1)){ $IDno = $row1["SIDno"]; $sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')"; } this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?
You’re probably executing the query after the loop so only the last record is being inserted. Try to execute the insertion query at the end of the loop: while ($row1 = mysql_fetch_assoc($result1)) { $IDno = $row1["SIDno"]; $sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')"; mysql_query($sql2); } Or you first collect all data and then do one query to insert all records: $values = array(); while ($row1 = mysql_fetch_assoc($result1)) { $IDno = $row1["SIDno"]; $values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')"; } if (!empty($values)) { $sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values); mysql_query($sql2); } But don’t forget to prepare the values for the query (see mysql_real_escape_string function).
If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement. Example: INSERT INTO registered (ServiceID, IDno, Stype) SELECT field1, field2, field3 FROM class WHERE SubjID='$SubjName' and SecID='$SecName'" And like written before me, escape your variables...
Note: make sure you're escaping your variables with mysql_real_escape_string. $sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'"; $result1 = mysql_query($sql1); $sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES "; $addComma = false; while ($row1 = mysql_fetch_assoc($result1)){ $IDno = $row1["SIDno"]; $sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')"; $addComma = true; }
Change this line: $sql2="INSERT INTO registered..." to this: $sql2 .= "INSERT INTO registered..." inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.