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();
Related
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.
i have an issue gettin' the value from a query:
public static function sa() {
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result);
$res = $got['MAX(id)'] + 1;
$rs='SA'.$res;
return "{$rs}";
}
it always return SA1, but i want get the last id and after plus 1 so in this case i have the next autoincremental id from my id column.
For example: i am creating a new registry with the field SA0000005. This number is calculated getting the last autoincremental value plus 1.
thanks for your valuable help
$resul = Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->execute();
$got = mysql_query($result); // what are you even doing here
Apart from typos, that's not how you are supposed to use the query builder. Have you read the documentation on the query builder?
The probable reason why you always get SA1, is because the $got['MAX(id)'] expression is NULL. You add 1 to that. You want something like this.
// returns false on no-result, MAX('id') otherwise
Yii::app()->db->createCommand()->select('MAX(id)')->from('yii_availability')->queryScalar();
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 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
The scipt should subtract 1 from the primary key (auftrag_id) from a table. But somehow it's not working. The variable $preauftrag_id is not getting decreased. The type of the variable is integer. I tried several subtraction-methods, but none is working. Someone have an idea?
$auftrag_id = $db->insert_id;
$preauftrag_id = $auftrag_id;
$preauftrag_id--;
echo "$preauftrag_id"; // Turns out the same value as $preauftrag_id = $auftrag_id;
Just another thought, if $db->insert_id returns an object, PHP variables assigned by reference.
Therefore, you've essentially assigned another way to access $auftrag_id, but you haven't taken its value:
$auftrag_id $preauftrag_id
\ /
------memory------
(sorry for the terrible graphics)
Therefore, decrementing $preauftrag_id would actually be decrementing the same reference as $auftrag_id, which may not be allowed because its a STATIC variable of the DB class?
Assuming you want the id of the second to last row (the one before the one that was just inserted), the only reliable way is to run a query. Try this:
$query = 'SELECT id
FROM table
WHERE id < '.(int) $db->insert_id.'
ORDER BY id DESC
LIMIT 1';
That should fetch the id of the row prior to the one in question.
In case of, try with integer casting :
$auftrag_id = (int) $db->insert_id;
$preauftrag_id = $auftrag_id;
$preauftrag_id--;
echo "$preauftrag_id"; // Turns out the same value as $preauftrag_id = $auftrag_id;