I'm trying to insert two rows but the id of every row is in the same array, how can I insert correctly?
Because I tried by this way but only insert me the first id.
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (".$this->db->escape($ids).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id').")";
mysql_query($sql);
echo ($sql);
This is what I get:
INSERT INTO cars (car, price, createdDate, createdBy)
VALUES ('217450,217449', '15', NOW(), 150)
In car I want to insert the price, createdDate and createdBy on the two car Ids 217450,217449.
Thank you in advance.
$ids = "217450, 217449";
$id_explode = explode(",", $ids);
foreach($id_explode as $id)
{
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (".$this->db->escape($id).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id').")
";
mysql_query($sql);
echo ($sql);
}
But I recommend you not to use raw SQL queries as it is vulnerable to SQL injection.Hence, Use CI's active record:
$ids = "217450, 217449";
$id_explode = explode(",", $ids);
$insert_batch = array();
foreach($id_explode as $id)
{
$arr = array(
'car' => $id,
'price' => $price,
'createdDate' => NOW(),
'createdBy' => $this->session->userdata('admin_id'),
);
$insert_batch[] = $arr;
}
$this->db->insert_batch('cars', $insert_batch);
Documentation:
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Use PHP function explode:
$ids= explode(',', $ids);
foreach($ids as $id)
{
$sql = "INSERT INTO cars(car, price, createdDate, createdBy)
VALUES (" . $this->db->escape($id) . ", " . $this->db->escape($price)
. ", NOW(), " . $this->session->userdata('admin_id') . ")";
mysql_query($sql);
}
If you use ids as array like
$ids = array('217450','217449');
$sql = "
INSERT INTO cars(car, price, createdDate, createdBy)
VALUES ";
foreach($ids as $id){
$sql .=(".$this->db->escape($id).",
".$this->db->escape($price).",
NOW(),
".$this->session->userdata('admin_id')."),";
}
mysql_query($sql);
echo ($sql);
Now it will create query
INSERT INTO cars (car, price, createdDate, createdBy)
VALUES ('217450', '15', NOW(), 150),('217450', '15', NOW(), 150);
Related
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();
}
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');
where is error.....
Column count doesn't match value count at row 1
mysqli_select_db($conn, $data);
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat', "
. "'$sn', '$art', '$img', "
. "'$y', '$g', "
. "'$sl', '$time', '', '0')";
$success = mysqli_query($conn, $save) or die(mysqli_error($conn));
$page = "index.php";
$this->pageRedirect($page);
where is error.....
Column count doesn't match value count at row 1
remove '' from your query to be:
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat','$sn', '$art', '$img', '$y', '$g', '$sl', '$time', '', '0')";
Try this:
$save = "INSERT INTO SONG_AS(`ALBUM`, `CATEGORY`, `SUB_CATEGORY`,
`SONG_NAME`, `ARTIST`, `ART_LINK`,
`YEAR`, `GENRE`, `SONG_LINK`, `POST_ON`,
`POST_BY`, `TOTAL_DOWNLOAD`)
VALUES('".$albm."', '".$cat."', '".$scat."','".$sn."', '".$art."', '".$img."', '".$y."', '".$g."', '".$sl."', '".$time."', '', '0')";
$query = "INSERT INTO employee VALUES ($empno','$lname','$fname','$init','$gender','$bdate','$dept','$position','$pay','$dayswork','$otrate','$othrs','$allow','$advancesance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno','lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}
I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";
I want to create an INSERT statement using the columns of my table and NULL or blank values for the content except for the id, created_by .etc. I am trying to avoid duplicates. Right now I get:
INSERT INTO testimonials (id, created, created_by, id, quote, name, position, company, published, created, created_by, last_modified_by, last_modified) VALUES ('257927816', NOW(), '1', '')
and I would like to have blank values iterate in the VALUES section for everything but the first 3, which I define.
function insertBlankWithID($table, $postFxn) {
global $randomID;
$id = $randomID;
$resultInsert = mysql_query("SELECT * FROM " . $table);
if (!$resultInsert) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
include($cmsdir . FOOTER_EXIT);
exit();
}
$columns = array();
while ($row = mysql_fetch_assoc($resultInsert)) {
if (empty($columns)) {
$columns = array_keys($row);
}
}
//$sql = 'INSERT INTO `testimonials` (`id`, `quote`, `name`, `position`, `company`, `published`, `created`, `created_by`, `last_modified_by`, `last_modified`) VALUES ('.$id.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);';
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode("', '", ''));
mysql_query($sql);
/*
if (!$sql) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
exit();
}
*/
echo $sql;
}
// redirect(basename($_SERVER['PHP_SELF'], ".php").'?s=output&id='.$id
insertBlankWithID('testimonials', $postFxn);
Looking at your code, you should limit the select to 1, (ie $resultInsert = mysql_query("SELECT * FROM " . $table. " limit 1"); as you don't need the information, just the keys. That removes the need for the while loop.
Now, to get all the keys except the first three, for your $columns variable, use array_slice such as $columns = array_slice($columns, 3); Or, if it isn't the first three when you select *, you can do $columns = array_diff($columns, array('id', 'created', 'created_by') );
Now, to insert null after the first three, you are imploding a string - which won't work, instead you can make an array of null values matching the count of the new $columns such as:
$blanks = array_fill(0, count($columns), 'null');
and when creating your statement, do implode(", ", $blanks), which would make your $sql look like:
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode(", ", $blanks));
And that should fix the issue you've described.
Also, while I'm here, it should be noted that you should not use mysql_ functions anymore and move to mysqli_ for the same type of procedure-oriented MySQL access.