I make an insert in my database and after this insert i want to get my id ( but he is auto increment ) and all the data i have on this one are not unique . I want create a folder with this id.
$reponse = $bdd->prepare(' INSERT INTO motorbike (countryMotorbike,idModel,idGarage) VALUES (?,?,?) ');
$reponse->execute(array($country,$modelid,$_SESSION['idgarage']));
mkdir('./photos_customer/'.$_SESSION['id'].', 0777, true);
I can make a select with all the params i give to create this " motorbike " but if an other one has the same params it's could fail. That's why i need to get my ID but i really don't know how to do it.
Thank you for your help.
And sorry for my bad english.
You can get the last inserted id from the lastInsertId function. Something like this:
$reponse = $bdd->prepare(' INSERT INTO motorbike (countryMotorbike,idModel,idGarage) VALUES (?,?,?) ');
$reponse->execute(array($country,$modelid,$_SESSION['idgarage']));
$id = $response->lastInsertId();
Related
I'm trying to update a record if the key is known else I want to insert it and get the inserted id, currently I have:
if(isset($data['applicationId']))
{
//update
$sql="
UPDATE myTable SET data='jsonstring' WHERE id = {$data['applicationId']}
";
}
else
{
//insert and get id
$sql="
INSERT INTO myTable SET data='jsonstring'
";
}
Is it possible to simplify the above to one query using INSERT ...ON DUPLICATE KEY UPDATE even when the key is not always known ?
I've tried this:
INSERT INTO myTable
(
id,
data
)
VALUES
(
?, # <- I may not know this!!
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring'
Thanks for any suggestions.
Yes, you can do that, assumed id is your primary key and auto_increment. You will have two different queries, one if you know the applicationId and one when you not knowing it.
The first, when you know it:
INSERT INTO myTable
(
id,
data
)
VALUES
(
1337, # <- insert id
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
And the one if the applicationId is unknown:
INSERT INTO myTable
(
id,
data
)
VALUES
(
NULL, # <- This will cause mysql to use a auto_increment value
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
So you can conclude this to:
$sql="INSERT INTO myTable
(
id,
data
)
VALUES
(" .
isset($data['applicationId']) ? $data['applicationId'] : 'NULL'
.",
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
";
But be aware of How can I prevent SQL-injection in PHP?
Happy coding
Please forgive because your question is not 100% clear. However, the concept I can tell is that you want to be able to ask more than 1 query on 1 sql statement. That can be done with a multi-query command. However, if you want some of your data from a query placed in your next query I do not think it will work. Link provided for multi_query
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
First, Simple update query will run. If it runs successfully, it will not go to if condition and your ID will be the one which was used in updating.
And, if that ID is not available (means update query fails, $Query will be false), so pointer jumps to if condition and insert the query. Now, new Inserted ID we can get.
$ID=$data['applicationId'];
$Query=mysql_query("UPDATE myTable SET data='jsonstring' WHERE id='$ID' ");
if(!$Query)
{
$InsertQuery=mysql_query("INSERT INTO myTable SET data='jsonstring'");
$ID=mysql_insert_id();
}
So, $ID will be your ID.(either updated or currently inserted)
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
is there anyway to get the ID of the current record I am INSERTING into the database table using php with Mysql without having to do an extra select to get the last ID?
FOr example, if my table has these columns, id, url, name
and if url consists of the domain name and current id as the query variable ex:
domainname.com/page.php?id=current_id
$sql="INSERT INTO Persons (id, url, name )
VALUES
('domainname.com/page.php?id=".**whats_the_current_id**."','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
as far as I know, there is no 'clean' way to find the ID you are about to insert (from what I understand from your question, this is what you want to know).
Two options in my opinion, starting with the ugly one: select max(id) from Persons, increment it with one, and hope that no insert's will mess this up for you. Like I said, its ugly, and -not- reliable.
A better option would be to first insert the record with a dummy value for url, and then retrieving the just inserted row's ID with mysql_insert_id(). Then update that record with the correct url value.
You asked for a way to retrieve the id without a select query following the insert query, but like I said, I don't think this is possible.
i use mysql_insert_id() for that. it works fine.
// pseudo-ish code
$query = "INSERT something .... "
$updated = $db->run_query($query);
$id = mysql_insert_id();
your table should be like this
ID AUTO_INCREMENT
person_id VARCHAR
person_url ...
person_name ...
your post form something like
<form method="post">
<input type="hidden" name="id" value="<?php echo uniqid() ?>" />
...
</form>
the query should be like this:
$person_id = intval($_POST['id']);
$person_url = mysql_real_escape_string($_POST['url']);
$person_name = mysql_real_escape_string($_POST['name']);
mysql_query("INSERT INTO Persons (person_id, persno_url, person_name) VALUES ( {$person_id} , {$person_url}, {$person_name} )");
$ID = mysql_insert_id();
The current ID is in $_GET['id']. You should sanitize it before inserting it into your query:
$id = intval($_GET['id']);
Then, use $id in your query.
If you add classes around the first insert and then the second select. The select will work then.
<?php
class insert1{
function inserthere(){
***insert***
}
}
class select1{
function selecthere(){
***select***
}
}
$a = new insert1;
$a->inserthere();
$b = new select1;
$b->selecthere();
?>
If I have two different MySQL insert functions in a document going to two different tables, how can I get the id of one record and place it in the other table?
After the first insert you can pickup the id via mysql_insert_id
tru something like this
function insert1()
{
mysql_query("INSERT .....");
return myqsl_insert_id();
}
function insert2()
{
$id1 = insert1(); // the id you want
mysql_query("INSERT ..... $id1 ");
}
you can get the last insert id by mysql_insert_id() function and then use it.
For example your first Insert query is
$insertqry1 = mysql_query("insert into tbl_name values(..,...,..)");
$lastinsertid = myqsl_insert_id();
Your second Query will be
$insertqry2 = mysql_query("insert into tbl_name(id) values('$lastinsertid')");
I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?