I want to store the data from several curl calls to an initial table, but last insert id is inserting wrong info
Query 1 inserts data into table
table1
id name email valuereturn
1 val val#email.com 0
I then post data 3 times to my system and log it
table2
id name system valuereturn
1 val 5 0
2 val 0 0
3 val 0 0
the max value returned from my system i want to update table 1
update table1
set valuereturn = '5'
where id = LAST_INSERT_ID()
does not work because last insert id is 3 from table2, how can I use something like last_insert_id(Table1)?
i want to update my
Well, you can't. You have to retrieve and remember it in a PHP variable.
Or go for Saharsh's solution and remember it in a MySQL variable.
Store that LAST_INSERT_ID() of table1 in a variable and than use that variable in update query.
INSERT INTO table1(name) values ('Saharsh');
SELECT LAST_INSERT_ID() INTO #table1Id;
INSERT INTO table2(name, table1id) values ('Saharsh', #table1Id);
UPDATE table1 SET valuereturn = '5' WHERE id = #table1Id;
In PHP I assume you use the following code:
<?php
connect_db();
insert_first_query_to_table1();
insert_second_query_to_table2();
update_query_setting(last_insert_id());
?>
If that's the case, I suggest you to use a temp variable to store the last_insert_id.
<?php
connect_db();
insert_first_query_to_table1();
$setVal = last_insert_id();
insert_second_query_to_table2();
update_query_setting($setVal);
?>
Hope this helps.
PS: This is a pseudo code!
Related
Following is my database in mysql:
Id Username Password
1 admin admin
2 jay jay1
3 suman xyza
4 chintan abcde
This is my code in php:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
$user= $_POST['username'];
$pass= $_POST['password'];
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."'
);");
Problem:
Now if I delete row with Id=1 and then re-enter the data then it should use ID=1 then Again I reinsert the data it use ID=5
It works like this:
if I delete row with Id=1 and then re-enter the data the Id it gets is 5 but then 1 is free so,
What should I write to perform that task.
First, if you set your Id column to AUTO_INCREMENT you don't need the following part in your code at all:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
Because AUTO_INCREMENT will automatic add new value to your ID colume.
But if you don't set it to AUTO_INCREMENT, the above code will grab the MAXIMUM ID value (in this case, 4).
When you re-enter your data again after you delete the row 1, the MAXIMUM ID still 4, so your new ID value will be 5 (from $largest++;).
.....
If you really need to use consecutive ids as you PK, you need to re-write you code but I suggest you to use UUID for you ID column instead.
You can easily generate UUID by using uuid().
How about the UUID performance? Refer to Dancrumb's answer about this:
A UUID is a Universally Unique ID. It's the universally part that you should be considering here.
Do you really need the IDs to be universally unique? If so, then UUIDs
may be your only choice.
I would strongly suggest that if you do use UUIDs, you store them as a
number and not as a string. If you have 50M+ records, then the saving
in storage space will improve your performance (although I couldn't
say by how much).
If your IDs do not need to be universally unique, then I don't think
that you can do much better then just using auto_increment, which
guarantees that IDs will be unique within a table (since the value
will increment each time)
see. UUID performance in MySQL?
EDIT: I don't suggest you run query on the whole table just to find the MAX ID value before inserting new value everytime, because it will give you a performance penalty (Imagine that if you have million rows and must query on them everytime just to insert a new row, how much workload causes to your server).
It is better to do the INSERT just as INSERT, no more than that.
EDIT2:
If you really want to use consecutive ids, then how about this solution?
Create new TABLE just for store the ids for insert (new ids and the ids that you deleted).
For example:
CREATE TABLE cons_ids (
ids INT PRIMARY KEY,
is_marker TINYINT DEFAULT 0
);
then initial ids with values from 1-100 and set marker to be '1' on some position, e.g. 80th of whole table. This 'marker' uses to fill your ids when it's nearly to empty.
When you need to INSERT new Id to your first table, use:
$result = mysql_query("SELECT ids, marker FROM cons_ids ORDER BY ids ASC LIMIT 1;");
$row = mysql_fetch_row($result);
and use $row[0] for the following code:
INSERT INTO yourtable (Id, Username, Password)
VALUES ($row[0], $username, $password);
DELETE FROM cons_ids
WHERE ids = $row[0];
This code will automatically insert the lowest number in cons_ids as your Id and remove it from the cons_ids table. (so next time you do insert, it will be the next lowest number)
Then following with this code:
if ($row[1] == 1) {
//add new 100 ids start from the highest ids number in cons_ids table
//and set new marker to 80th position again
}
Now each time you delete a row from your first table, you just add the Id from the row that you deleted to cons_ids, and when you do INSERT again, it will use the Id number that you just deleted.
For example: your current ids in cons_ids is 46-150 and you delete row with Id = 14 from first table, this 14 will add to your cons_ids and the value will become 14, and 46-150. So next time you do INSERT to your first table, your Id will be 14!!.
Hope my little trick will help you solve your problem :)
P.S. This is just an example, you can modify it to improve its performance.
First of all, as I understand, you are selecting highest column ID which should be always the last one (since you set auto-increment on ID column).
But what are you trying to do is actually filling up holes after delete query, right?
If you are really looking for such approach, try to bypass delete operation by making new boolean column where you flag record if it is active or not (true/false).
SQL table change:
Id Username Password Active
1 admin admin false
2 jay jay1 true
3 suman xyza false
4 chintan abcde true
PHP request:
$fetchid = mysql_query(" SELECT MIN(Id) As min FROM user WHERE active = false;");
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
`Active`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."', 'true'
);");
I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement
I have this id number in one column of my table,
0907003
0907004
0907005
1008005
1008006
1008007
1009001
1009002
1009003
When I add new value of 1009, it will add last three number of 004 because the last number begin with 1009 (10-09) is 003.
Or if I add new value of 1008, it will add last three number of 008
because the last number begin with 1008 (10-08) is 007.
Or if I add new value of 0907, it will add last three number of 006
because the last number begin with 0907 (09-07) is 007.
How to do this?
Many thanks in advance!
$front_id = $this->input->post('gameid'); //09
$middle_id = $this->input->post('netid'); //07
//$last_id will be generate automatically by sql
$forID = $front_id.$middle_id;
$sql = "INSERT INTO table ('colum') VALUES (".$forID.")"
You have to insert new id manually
$max_of_letsay1009 = mysql_result(mysql_query("select MAX(id) from table where id like '1009%'"),0);
// get the last 3 digits
$new_number = (int)substr($max_of_letsay1009,-3) + 1;
or you can try this too:
$new_id_of_letsay1009 = mysql_result(mysql_query("select MAX(id)+1 from table where id like '1009%'"),0);
this is just my idea, not yet tested and no error checking
You try this below query
If your value is 1009
SELECT MAX(RIGHT(ID,4))+1 FROM TableName WHERE LEFT(ID,4) = '1009'
It will return the max number of that series.
Try this query for dynamic ID length
SELECT MAX(RIGHT(ID,len(id)-LEN('1009')))+1 FROM #TEMP WHERE LEFT(ID,LEN('1009')) = '1009'
You can also use this query as sub query for the insert statement's ID column.
It is possible if it is not Auto_Increment coulmn.
Just need to write logic on insert time.
How would this be done? I would like to search the database row by row. I might even print out the entire list of the database row by row. But I would also like to show record 1400 for example and determine the info on that row - such as name, gender and country.
Is it possible to use the rownum function to get this done? Or would I need to use a where in the query? But even so how would I determine the row number? Thanks.
Make one column as ID, make it PK and auto_increment. Then your query shell be something like this for #1400 row:
$pdo
->prepare(
"SELECT `name`, `gender`, `country`
FROM `foo_table` WHERE `id` = :id"
)
->execute([':id' => 1400]);
You can use user defined variables to get your rownumber in MySQL
set #nr = 0;
Now you can use this variable (same connection!) in your query
SELECT
#nr := (#nr + 1) rownumber,
*
FROM
table
see: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
do your select and add
LIMIT n,1
this will skip to n-th element(1400) and show just one result
I want to be able to add an array of strings to a table so that each string is a new row (in PHP).
This is it in psuedo-code:
$Array = "10000,10001,10002,10003";
$Data = "ImportantData";
mysqli_query($db, "INSERT INTO MyTable(`id`,`data`) VALUES($Array, $Data)");
So that a previously empty table would look like:
id | data
------------------------
10000 | ImportantData
10001 | ImportantData
10002 | ImportantData
10003 | ImportantData
In an update script, with those rows already established, I could just say:
mysqli_query($db, "UPDATE MyTable SET data = $Data WHERE `id` IN($Array));
However I want it to create rows, not just update old ones.
Is there any way I can do this?
Just create a foreach loop on $Array, and insert the data. I assume you want to update it if it exists as it makes little sense to create a new record with the same PK, so use the following (assumes you are using PHP PDO
INSERT INTO MyTable (id,data) VALUES (:id,:data) ON DUPLICATE KEY UPDATE data=:data;
Use REPLACE INTO:
REPLACE INTO table SET id = 10001, data = 'new important data';
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/replace.html