I am trying to insert an array of row in database and every row of array contain 3 another rows.
foreach($type as $a=>$b)
{
$sql="INSERT INTO `actual_regular` (`employee`, `sex`, `caste`, `family`, `local`, `worked_month`, `incash`, `total_salary`) VALUES ('$type[$a]', '$sex_actual[$a]', '$caste_actual[$a]', '$family_actual[$a]', '$employee_actual[$a]', '$worked_month[$a]', '$cash_actual[$a]', '$salary_actual[$a]');";
mysql_query($sql);
Above will insert array of rows. Every rows contain 3 rows that will be inserted in new table
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]');";
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]');";
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]');";
mysql_query($insert);
} // above foreach ends here
I mean there are multiple rows need to be inserted in table actual_regular every rows contain 3 more rows. These 3 rows are inserted in table more_regular.
Use single insert query for three insert operations like this:
<?php
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ";
$values = array();
foreach ($type as $a=>$b) {
$values[] = "('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]')";
$values[] = " ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]')";
$values[] = " ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]')";
} // above foreach ends here
if (! empty($values)) {
$insert .= implode(', ', $values);
}
mysql_query($insert);
?>
Basically, the logic is:
INSERT INTO TABLE (ID, NAME) VALUES
(1,'Andrew'),
(2,'Glenn'),
(3,'Marvel');
Related
I have a form which inserts a unique code into the table generated through php. It works when there is a single one but when I insert two at the same time I got a duplicate error.
if (!empty($_SESSION["cart_item"])) {
$orderreference = $_SESSION['ref'];
foreach ($_SESSION["cart_item"] as $item) {
if($item['isVoucher'] == 1){
$insertQuery = ("INSERT INTO `bookings_css_codes`
(`id`, `code`, `price`, `per`, `status`,
`expiry_date`, `usage`, `is_used`)
VALUES ('', '$randomsA', '$item[ProductPrice]', 'amount', 'T',
'$oneYearOn', 'single', '0');");
if (!$db->query($insertQuery)) {
die('Error: ' . $db->error);
}
}
you can try
insert in "field name"("value1","value2",...."valuen");
I have inserted some strings with values in one table lets call it table_1 in my database, now I have arrays which I want to insert into separate rows in table_2 in my SQL database.
$sql = 'INSERT INTO ' . $table_1 . '(shipping_fee, waybill_status, pickup_fee, )
VALUES(:shipping_fee, :waybill_status, :pickup_fee)';
$stmt = $this->dbConn->prepare($sql);
$stmt->bindParam(':shipping_fee', $s_shipping_fee);
$stmt->bindParam(':waybill_status', $s_waybill_status);
$stmt->bindParam(':pickup_fee', $this->pickup_fee);
if($stmt->execute()){ //THIS INSERTED THE STRINGS PERFECTLY
//NOW ALL VALUES TO BE INSERT INTO $sqal is an array
$sqal = 'INSERT INTO ' . $table_2. '(id, waybill_number, client_id, item_name, item_weight, item_length, item_width, item_category, date_added) VALUES(null, :waybill_numberr, :client_idaa, :item_name, :item_weight, :item_length, :item_width, :item_category, :date_added)';
$stmtaaa = $this->dbConn->prepare($sqal);
$stmtaaa->bindParam(':item_name', $this->item_name); //ARRAY
$stmtaaa->bindParam(':item_weight', $this->item_weight); //ARRAY
$stmtaaa->bindParam(':item_length', $this->item_length); //ARRAY
$stmtaaa->bindParam(':item_width', $this->item_width); //ARRAY
$stmtaaa->bindParam(':item_category', $this->item_category); //ARRAY
$stmtaaa->execute(); //HoW do I go about this.
} else {
echo "Could not insert";
exit();
}
You had a syntax error in your first query, the trailing commas , should not be there in the column- or value-list.
You can insert an array by executing the prepare multiple times with different values. This example assumes that all your arrays are indexed by numbers (from zero and up).
The code example above also binds more columns than it binds, so you need to bind a value to each column. waybill_numberr, client_idaa and date_added are missing its binds (I just added some random placeholders).
$sql = "INSERT INTO $table_1 (shipping_fee, waybill_status, pickup_fee)
VALUES (:shipping_fee, :waybill_status, :pickup_fee)";
$stmt = $this->dbConn->prepare($sql);
$stmt->bindParam(':shipping_fee', $s_shipping_fee);
$stmt->bindParam(':waybill_status', $s_waybill_status);
$stmt->bindParam(':pickup_fee', $this->pickup_fee);
if ($stmt->execute()) {
$sqal = "INSERT INTO $table_2 (id, waybill_number, client_id, item_name, item_weight, item_length, item_width, item_category, date_added)
VALUES (null, :waybill_numberr, :client_idaa, :item_name, :item_weight, :item_length, :item_width, :item_category, :date_added)";
$stmtaaa = $this->dbConn->prepare($sqal);
foreach ($this->item_weight as $key => $value) {
$stmtaaa->execute(["waybill_numberr" => '1', // Change this to your actual value
"client_idaa" => '1', // Change this to your actual value
"item_name" => $value,
"item_weight" => $this->item_weight[$key],
"item_length" => $this->item_length[$key],
"item_width" => $this->item_width[$key],
"item_category" => $this->item_category[$key],
"date_added" => '1']);
}
} else {
echo "Could not insert";
exit();
}
What is the proper way to reference the array components from fetch_assoc() so that they can be inserted into another table?
Here is my current code:
$sql_read = "SELECT id, data1, data2, date FROM `table1`";
$result = $mysqli->query($sql_read);
if ($result !== false) {
$rows = $result->fetch_all();
}
while ($row = $result->fetch_assoc()){
$sql_write = "INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('.$row['id']', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
}
As suggested in my comment, first your select statement should be:
"SELECT id, data1, data2, date FROM `table1`";
Furthermore, the insert statement should be (see the use of concatenation of strings):
"INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."', NULL);";
There are some errors in your script, as already pointed out.
But you might also be interested in the INSERT INTO ... SELECT variant of the INSERT syntax.
<?php
$query = '
INSERT INTO
table2
(`id`, `data1`,`data2`,`date`)
SELECT
`id`, `data1`,`data2`,`date`
FROM
table1
';
$result = $mysqli->query($query);
if ( !$result ) {
trigger_error('error: ' . $mysqli->error, E_USER_ERROR);
}
else {
echo $mysqli->affected_rows, ' rows have been transfered';
}
You have an extra field in the VALUES that is not referenced in the INTO and the concatenation of the row data is incorrect;
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('.$row['id'].', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
should be:
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."');";
Or you need to update the INTO to include an extra column that accepts NULL
See also:
The PHP reference on mysqli_result::fetch_assoc
I am trying to insert multiple rows based on a loop.
This code inserts the first item from the loop only, then ignores the rest of the loop
I know the loop is counting correctly as echo'ing out the values outputs ok
$i = 1;
while ($i <= $count){
foreach($html->find('.markuptag a') as $mystring){
if(preg_match_all("|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i", $mystring, $matches)){
$a = $matches[2][0];
}
$query = "INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES ('$fistname', '$lastname', '$a')";
$mysqli->query($query);//<< is there a better way?
}
$i++;
}
Build an array of the rows to insert, then insert them all at once. Something like this:
$arr = []; // array() in PHP 5.3 and older
foreach(...) {
...
$arr[] = "('$fistname', '$lastname', '$a')";
}
$mysqli->query("INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES "
.implode(",",$arr));
I'm working on the website for a mmo-rpg game-based group, and I'm having trouble on the insert form for their 'hitlist'; my code is as follows:
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$Pri = check_input($_GET['Pri']);
$Pir = check_input($_GET['Pir']);
$Lvl = check_input($_GET['Lvl']);
$XCd = check_input($_GET['XCd']);
$YCd = check_input($_GET['YCd']);
$Nts = mysql_real_escape_string(check_input($_GET['Nts']));
$Opl = check_input($_GET['Opl']);
$Kwl = check_input($_GET['Kwl']);
$Ktl = check_input($_GET['Ktl']);
$Tty = mysql_real_escape_string(check_input($_GET['Tty']));
$Grp = check_input($_GET['Grp']);
$sql="INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error() . ' ' . $sql);
}
Yes, I've looked elsewhere, and yes, here is a printout of the query:
INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`) VALUES ('','1','Eri','13','13751','408','?','?','?','?','?','Coming Soon.','Sector 23')
I really don't understand what I'm doing wrong. The Id is auto-incremented, and this query works in phpMyAdmin
A new set of eyes would really be appreciated here.
You are only inserting 13 values, there are 14 columns. The 'KnownFltLvl' variable is missing.
INSERT INTO modattacklist (`Id`, `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('','$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')
If your table accepts nulls for this column, you can remove it from the INSERT all together.
If it still doesn't work, avoid the id.
INSERT INTO modattacklist ( `Priority`, `Pirate`, `Level`, `KnownFltLvl`, `XCoord`, `YCoord`, `Notes`, `BaseLevel`, `KnownWallLvl`, `KnownTurretLvl`, `TurretTypes`, `BasePicture`, `Group`)
VALUES ('$Pri','$Pir','$Lvl','$KnownFltLvl','$XCd','$YCd','$Nts','$Opl','$Kwl','$Ktl','$Tty','Coming Soon.','$Grp')