How to get all inserted records ids in codeigniter ?? I am using insert_batch function in for inserting multiple records but codeigniter $this->db->insert_id() function returns only last record id.
//But i need all inserted records ids. If any one has idea please help.
//In codeigniter this function returns only last inserted record id.
function insertStudent(){
$data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');
$data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');
$result = $this->db->insert_batch( 'student', $data );
return $this->db->insert_id();
}
This can be achieved by using first id and count.
Get count of data that you are inserting. (e.g. 2 in your example)
Get first insert id by $this->db->insert_id() (e.g. say 30)
Now get last insert recorded id by = first record id - (count - 1) (e.g. 30 + (2-1) = 31)
Now you can query to get data between id's 30 and 31.
If you absolutely must have the insert_id for each inserted row, the simplest most failproof way would be to loop multiple inserts rather than making one big fat insert.
Looping through multiple inserts will allow you to get all insert_ids. It will also allow you to not loose all the data if one of the rows fails inserting and the database rejects them all because of that.
My best solution is to update the DB_driver.php.
From
public function is_write_type($sql)
{
return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql);
}
To:
public function is_write_type($sql)
{
return (bool) (preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s+/i', $sql) && !preg_match('/ RETURNING /i', $sql));
}
The really safest way is:
Add a column code in your table.
Create a code before batch inserting [id session user]-[current time stamp] should be enough.
Batch insert all elements with that code into code column
Query a Select searching for that code, you will have all elements inserted at batch insert
Here is an efficient method:
Since your records have result ID's, I'm going to assume they also auto-increment.
If this is the case, you do this and still use insert_batch.
Here is what you do:
You take a count of the items you are inserting:
$count = count($data);
Run your batch insert:
$this->db->insert_batch('student', $data);
Get the first inserted ID of your batch:
$first_id = $this->db->insert_id();
Add the count (minus 1) to your insert ID to get the last records ID.
$last_id = $first_id + ($count-1);
There you go! You now have first and last ID's of your inserted records, and by extension, everything else in between.
function insertStudent(){
$data[] = array('firstname'=>'firstname1','lastname'=>'lastname1');
$data[] = array('firstname'=>'firstname2','lastname'=>'lastname2');
$result = $this->db->insert_batch( 'student', $data );
$a= $this->db->get('student');
$data = $a->result_array();
echo($data[0]['id']);
}
Hope So this will help you.
Related
I have one problem here, and I don't even have clue what to Google and how to solve this.
I am making PHP application to export and import data from one MySQL table into another. And I have problem with these tables.
In source table it looks like this:
And my destination table has ID, and pr0, pr1, pr2 as rows. So it looks like this:
Now the problem is the following: If I just copy ( insert every value of 1st table as new row in second) It will have like 20.000 rows, instead of 1000 for example.
Even if I copy every record as new row in second database, is there any way I can fuse rows ? Basically I need to check if value exists in last row with that ID_, if it exist in that row and column (pr2 for example) then insert new row with it, but if last row with same ID_ does not have value in pr2 column, just update that row with value in pr2 column.
I need idea how to do it in PHP or MySQL.
So you got a few Problems:
1) copy the table from SQL to PHP, pay attention to memory usage, run your script with the PHP command Memory_usage(). it will show you that importing SQL Data can be expensive. Look this up. another thing is that PHP DOESNT realese memory on setting new values to array. it will be usefull later on.
2)i didnt understand if the values are unique at the source or should be unique at the destination table.. So i will assume that all the source need to be on the destination as is.
I will also assume that pr = pr0 and quant=pr1.
3) you have missmatch names.. that can also be an issue. would take care of that..also.
4) will use My_sql, as the SQL connector..and $db is connected..
SCRIPT:
<?PHP
$select_sql = "SELECT * FROM Table_source";
$data_source = array();
while($array_data= mysql_fetch_array($select_sql)) {
$data_source[] = $array_data;
$insert_data=array();
}
$bulk =2000;
foreach($data_source as $data){
if(isset($start_query) == false)
{
$start_query = 'REPLACE INTO DEST_TABLE ('ID_','pr0','pr1','pr2')';
}
$insert_data[]=implode(',',$data).',0)';// will set 0 to the
if(count($insert_data) >=$bulk){
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = array();
} //CHECK THE SYNTAX IM NOT SURE OF ALL OF IT MOSTLY THE SQL PART>> SEE THAT THE QUERY IS OK
}
if(count($insert_data) >=$bulk) // IF THERE ARE ANY EXTRA PIECES..
{
$values = implode('),(',$insert_data);
$values = substr(1,2,$values);
$values = ' VALUES '.$values;
$insert_query = $start_query.' '.$values;
$mysqli->query($insert_query);
$insert_data = null;
}
?>
ITs off the top off my head but check this idea and tell me if this work, the bugs night be in small things i forgot with the QUERY structure, print this and PASTE to PHPmyADMIN or you DB query and see its all good, but this concept will sqve a lot of problems..
I'm having a problem returning multiple rows dynamically.
I have an active record query that needs to return multiple rows from the same table.
//this will be a dynamic array of ids
$array = array('01','02','03');
//i need to have other where conditionals as well
$cond['userlevel'] = 5;
//then add the array of ids to the conditionals array
$cond['id'] = implode(',',$array);
//then build the active record query
$q = $this->db->select($col->where($cond);
It only ever seems to return the first item in the array of ids.
Try something like
"SELECT * FROM table_name WHERE userlevel IN(?,?,?,?)", array(0,1,2,3);
Please try this, it will help you.
$this->db->select('*');
$this->db->from('table_name');
$this->db->where_in('column_name',array(0,1,2,3));
Note:- Make sure where_in array value should not empty otherwise it will get MySQL Error.
I need to build a function that selects a random row of a field, but not any row.
Lets say the fields are called
id, user, one, two, three, four,five,six
1,'jack',0,0,0,1,0,0
When the function is called I need to update one of the following fields: one, two, three, four,five,six that has a value of '0' and set it to '1'. Therefore one field cannot be selected more than once. In reality there are over 10 fields that need this kind of handling. The order has to be random.
I'm still trying to figure out the logic without writing too many lines. Any suggestions?
how about:
function Z($id){
$array =array('one','two','three'); //field names
shuffle($array);//radnoise the array
$update='';
foreach($array as $k => $a){
if($k==0){
$update .="'$a'=1,";//first random field is 1
}else{
$update .="'$a'=0,";//all other fields are 0
}
}
$update=rtrim($update,",");//remove last comma
$q="update table set $update where id=$id";
return $q; //for testing, otherwise run query
}
echo Z('4'); //test it
//version 2
function ZZ($id){
$array =array('one','two','three'); //field names
$value=$array[array_rand($array)];
$q="update table set '$value'=1 where id=$id";
return $q; //for testing, otherwise run query
}
echo ZZ('4'); //test it
I have never heard of a way to select a random column in any database, but if the values are all either 1 or 0, why not just put them all into one? That way you would have a string like 101000100001001 where each digit represents a different "column". You could just use PHP to manipulate it and update your database.
I know there are a lot of topics with the same title. But mostly it's the query that's been inserted in the wrong place. But I think I placed it right.
So the problem is, that I still get 0 even when the data is inserted in the db.
Does someone knows an answer where I could be wrong?
here's my code:
mysql_query('SET NAMES utf8');
$this->arr_kolommen = $arr_kolommen;
$this->arr_waardes = $arr_waardes;
$this->tabel = $tabel;
$aantal = count($this->arr_kolommen);
//$sql="INSERT INTO `tbl_photo_lijst_zoekcriteria` ( `PLZ_FOTO` , `PLZ_ZOEKCRITERIA`,`PLZ_CATEGORIE`)VALUES ('$foto', '$zoekje','$afdeling');";
$insert = "INSERT INTO ".$this->tabel." ";
$kolommen = "(";
$waardes = " VALUES(";
for($i=0;$i<$aantal;$i++)
{
$kolommen .=$this->arr_kolommen[$i].",";
$waardes .="'".$this->arr_waardes[$i]."',";
}
$kolommen = substr($kolommen,0,-1).")";
$waardes = substr($waardes,0,-1).")";
$insert .=$kolommen.$waardes;
$result = mysql_query($insert,$this->db) or die ($this->sendErrorToMail(str_replace(" ","",str_replace("\r\n","\n",$insert))."\n\n".str_replace(" ","",str_replace("\r\n","\n",mysql_error()))));
$waarde = mysql_insert_id();
Thanks a lot in advance, because I have been breaking my head for this one for almost already a whole day. (and probably it's something small and stupid)
According to the manual mysql_insert_id returns:
The ID generated for an AUTO_INCREMENT column by the previous query on
success, 0 if the previous query does not generate an AUTO_INCREMENT
value, or FALSE if no MySQL connection was established.
Since it does not give you false and not the correct number it indicates that the queried table didn't generate an auto-increment value.
There are two possibilities I can think of:
Your table doesn't have an auto_increment field
Since you doesn't provide the link to the mysql_insert_id() but using a link with mysql_query() it might not be the correct table that's queried when retrieving the last inserted id.
Solution:
Make sure it has an auto_increment field
Provide the link aswell: $waarde = mysql_insert_id($this->db);
It is possible that your INSERT query was not successful - e.g., maybe you were trying to insert duplicate data on a column whose data must be unique?
If the id is indeed set to auto increment and still get '0' as your response do a column and value count i experienced this only later on I noticed a number of my column count did not match values count.
Codeigniter has an odd behaviourd when calling mysql_insert_id(). The function returns 0 after the first call. So calling it twice will return 0.
Use a variable instead of calling the function more times:
$id = mysql_insert_id();
I am using the following code to return the last insert id from the table employee kindly let me know what is wrong with the following code:
<?php
$temp_array = mysql_query("select last_insert_id() from employee");
//now you can display it, to test it
echo $temp_array;
?>
it return 0 value. Pls tell me the easy way to get this without using max(),
mysql_insert_id can be used to return the last ID generated for an auto increment column by the previous query (if the column is auto increment)
$temp_array is of type Resource, rather than integer. You need to do
$rslt = mysql_fetch_array($temp_array);
$id = $rslt[0];
See http://php.net/manual/en/function.mysql-fetch-array.php for details