I'm trying to insert some data into a database via codeigniter but am getting some strange errors. Does anyone know the cause:
My insert array ($datainsert) is the following when printed:
Array ( [online_name] => Discount Store
[online_nameKey] => d
[storeGroup_ID] =>
[CJ_ID] => 123456
[online_tag] => Health and Medical
[online_businessType] => 0
[online_businessTypeSub] => 0
[online_homepage] => http://www.discountstore.com
[store_ChainID] =>
[savingsdotcom_ID] => 0 )
Trying to print the insert I use:
echo $DB1->_insert('stores_online', $datainsert);
Which results in:
INSERT INTO stores_online (Discount Store, d, , 123456, Health and Medical, 0, 0, http://www.discountstore.com, , 0) VALUES ()
I can't figure out why its not using the array keys for the first () and the values correctly.
Try this code
$datainsert=Array ( [online_name] => Discount Store,
[online_nameKey] => d,
[storeGroup_ID] => something,
[CJ_ID] => 123456 ,
[online_tag] => Health and Medical ,
[online_businessType] => 0 ,
[online_businessTypeSub] => 0 ,
[online_homepage] => http://www.discountstore.com ,
[store_ChainID] => ,
[savingsdotcom_ID] => 0
) ;
$this->db->insert('stores_online', $datainsert);
Use
$this->db->insert('stores_online', $datainsert);
instead of
echo $DB1->_insert('stores_online', $datainsert);
I know the question is over a year, but I had the same issue and I solve it by creating the query manually this way:
public function add($data)
{
$query = 'INSERT INTO myTable (';
// (Column1, Column2, Column3,
foreach($data as $key => $column)
$query .= $key . ',';
// Removes the last comma
// Column3, == Column3) VALUES(
$query .= rtrim($query, ',') . ') VALUES(';
// Value1, Value2, Value3,
foreach($data as $key => $column)
$query .= "'" . $column . "',";
// Removes the last comma and closes the query
$query .= rtrim($query, ',') . ')';
// Result: INSERT INTO (Column1, Column2, Column3) VALUES ('VALUE1', 'VALUE2', 'VALUE3')
return $query;
}
This needs to be done:
echo $DB1->_insert('stores_online', array_keys($datainsert), $datainsert);
P.S. This works for CI 2.X and I have not tested it for other version of CI.
Related
Array
(
[0] => Array
(
[emp_name] =>
[emp_title] => Senior Developer
[emp_master_id] => 0
[emp_designation] => TL
[emp_skills] => PHP, MySQL
[emp_experience] => 4-5
[emp_location] => Chennai
)
[1] => Array
(
[emp_name] =>
[emp_title] => Web Developer
[emp_master_id] => 0
[emp_designation] => Senior Developer
[emp_skills] => 10Base-T Switching, PHP
[emp_experience] => 4-5
[emp_location] => Chennai
)
)
I want Insert the array In Db by using Foreach.. Any Suggestions
let say your array name is $data
foreach($data as $key => $value){
$sql="Insert into table_name (empname,..... )values('".$value['empname']."',....);";
$result=$conn->query($sql);
}
This should do the work, Assuming that you have connection variable something like
$conn = new mysqli($servername, $username, $password, $dbname);
Give the column name as in your table in the sql query.
EDIT
The secure way of doing it
foreach($data as $key => $value){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO table_name(emp_name, title, ...) VALUES (?, ?, ..)");//No of question marks are equal to columns you have mentioed
$stmt->bind_param("sss", $empName, $title, ...);
// i - integer
// d - double
// s - string
// b - BLOB
// set parameters and execute
$empName= $value['empname'];
$title= $value['title'];
//continue to do it for all...
$stmt->execute();
$stmt->close();
}
$conn->close();
NOTE: You can use function also if you know how to do it, less code inside the foreach
Happy coding :)
foreach($arr as $v){
$sql = ') VALUES (';
foreach($v as $k => $value){
$sql = ",".$k.$sql.'"'.$value.'",';
}
$sql = 'Insert into table_name ('.trim($sql,',').';';
$result=$conn->query($sql);
}
this maybe working.
Is there any way where i can run Multiple semicolon separated query in Code Igniter without insert_batch() ?
e.g:
$a = 'INSERT INTO table (a,b,c) VALUES (1,2,3); INSERT INTO table1 (x,y,z) VALUES (1,2,3);';
$this->db->query($a);
Above code gives invalid query error.
If multiple tables with single data(Using Transactions) - (N table vs 1 Data)
Running Transactions Manually
$this->db->trans_begin();
$this->db->query('INSERT INTO table (a,b,c) VALUES (1,2,3)');
$this->db->query('INSERT INTO table1 (x,y,z) VALUES (1,2,3)');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
Running Transactions Automatically
$this->db->trans_start();
$this->db->query('INSERT INTO table (a,b,c) VALUES (1,2,3)');
$this->db->query('INSERT INTO table1 (x,y,z) VALUES (1,2,3)');
$this->db->trans_complete();
If inserting Single table with multiple data (1 table vs N Data)
$data = array(
array(
'a' => 'My title 1' ,
'b' => 'My Name 1' ,
'c' => 'My date 1'
),
array(
'a' => 'My title 2' ,
'b' => 'My Name 2' ,
'c' => 'My date 2'
)
);
$this->db->insert_batch('mytable', $data);
Im trying to insert the following array into my table to no avail. I tried several examples but none worked.
Each POST array contains two strings from an input form (each string from an input row) and the $data keys are of the same name of the columns in the table.
How do I insert this data into two rows with a single query?
$data = array(
'user_id' => $_POST['user_id'],
'order' => $_POST['order'],
'type' => $_POST['type'],
'series' => $_POST['series'],
'repetition' => $_POST['repetition'],
'load' => $_POST['load'],
'pause' => $_POST['pause']
);
EDIT.: Could swear I had copied the query.
$columns = implode(',',array_keys($data));
$values = implode(',',array_values($data));
$query = " INSERT INTO userdata ($columns) VALUES ($values)";
You can insert this type of array like this
$fields=" ".implode(",",array_keys($data))." ";
$data="'".implode ("','",$data)."'";
$query ="INSERT INTO table_name ($fields) VALUES ($data)";
if($query){
mysql_query($query);
}
I've recently starting using PDO in a rebuild of a client's taxi booking system.
I have a script called create_booking.php, which initially inserts the booking details into a bookings table in the MySQL database. After inserting the customers details it retrieves the lastinsertID to get the booking ref. It then creates a job in the jobs table and references the booking reference to relate the job/booking.
The first insert is working fine, but the second insert isn't . Any ideas?
if (isset($_POST['customer_title'])) {
include('../assets/db_connection.php');
$create_booking = $db->prepare("INSERT INTO bookings(customer_name, billing_address, contact_tel, contact_mob, contact_email, party_pax, party_cases, booking_notes, price, booking_agent, booking_date, booking_status, authorised)
VALUES(:customer_name, :billing_address, :contact_tel, :contact_mob, :contact_email, :party_pax, :party_cases, :booking_notes, :price, :booking_agent, :booking_date, :booking_status, :authorised );");
$create_booking->execute(array(
":customer_name" => $customer_title . ' ' . $customer_first_name . ' ' . $customer_last_name,
":billing_address" => $billing_address,
":contact_tel" => $customer_tel,
":contact_mob" => $customer_mobile,
":contact_email" => $customer_email,
":party_pax" => $passengers,
":party_cases" => $cases,
":booking_notes" => $booking_notes,
":price" => $price,
":booking_agent" => $booking_agent,
":booking_date" => $booking_date,
":booking_status" => $booking_status,
":authorised" => $authorised
));
$booking_ref = $db->lastInsertId('booking_ref'); // Takes Booking Ref generated in $create_booking
$create_job = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, return, scheduled)
(:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :return, :scheduled )");
$create_job->execute(array(
":booking_ref" => $booking_ref,
":pickup_date" => $pickup_date,
":pickup_time" => $pickup_time,
":pickup_address" => $pickup_address,
":destination_address" => $pickup_destination,
":return" => "N",
":scheduled" => "N"
));
}
Your second SQL query is missing VALUES.
INSERT INTO() ... VALUES()
$create_job = $db->prepare("INSERT INTO jobs(booking_ref, pickup_date, pickup_time, pickup_address, destination_address, return, scheduled)
VALUES (:booking_ref, :pickup_date, :pickup_time, :pickup_address, :destination_address, :return, :scheduled )");
Need your help.
I need to update the array data in the mysql table. my problem is that there are some array values which dont have "photo" coloum (check 4th field in the array) because of that my query is failing with error "Column count doesn't match value count at row 1"
below is what im trying.
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
$sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());
Array Data
array
0 =>
array
'dob' => string '01121978'
'name' => string 'Ram Avtar'
'role' => string 'Inspector'
'email' => string 'ramavtar#gmail.com'
'photo' => string ' '
1 =>
array
'dob' => string '15021978'
'name' => string 'Suresh Babu'
'role' => string 'Constable'
'email' => string 'ssbh1#mail.yahoo.com'
'photo' => string ' '
2 =>
array
'dob' => string '11111965'
'name' => string 'Dean'
'role' => string 'Inspector'
'email' => string 'ddepth#live.in'
'photo' => string ' '
3 =>
array
'dob' => string '10061979'
'name' => string 'Rohit Shette'
'role' => string 'Sergeant'
'email' => string ' '
'photo' => string ' '
4 =>
array
'dob' => string '15081979'
'name' => string 'Ian'
'role' => string 'warden'
'email' => string ' '
table structure
CREATE TABLE user(
id INT(5) NOT NULL AUTO_INCREMENT,
dob TEXT NOT NULL,
name TEXT NOT NULL,
role TEXT DEFAULT NULL,
email TEXT DEFAULT NULL,
photo TEXT DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET latin1
COLLATE latin1_swedish_ci;
The actual problem is that you missed a comma.
Change:
echo $sql[] = '('.$row['dob'].', "'.($row['name']).'", "'.($row['role']).'"
"'.$row['email'].'", "'.($row['photo']).'" )';
To:
$sql[] = "('{$row['dob']}', '{$row['name']}', '{$row['role']}',
'{$row['email']}', '{$row['photo']}')"; // ^^^ Here is the missing comma
The missing values will not cause a problem, they will just cause an empty string to be inserted, because the string is quoted. However, you may wish to test to make sure the key exists in the array array before you try to use it, to avoid any nasty E_NOTICEs.
Also, make sure you properly escape your data before you use it in a query - you don't want a visit from Bobby Tables...
First - if that's your real code I think you're missing a comma after $row['role']. Also - why not check if array key exists?
Try something like (not tested, just to give you an idea)
$dept = $job->user();
$sql = array();
foreach( $dept as $row ) {
echo $sql[] = '('
. (array_key_exists('dob', $row) ? $row['dob'] : 'null') . ', "'
. (array_key_exists('name', $row) ? $row['name'] : 'null') . '", "'
. (array_key_exists('role', $row) ? $row['role'] : 'null') . '", "'
. (array_key_exists('email', $row) ? $row['email'] : 'null') . '", "'
. (array_key_exists('photo', $row) ? $row['photo'] : 'null') . '" )';
}
mysql_query('INSERT INTO cast (dob, name, role, email, photo) VALUES '.implode(',', $sql)) or die(mysql_error());