get ID of current inserted ID [duplicate] - php

This question already has answers here:
How can I make sure that PDO's lastInsertId() is not that of another simultaneous insert?
(2 answers)
Closed 7 years ago.
When you go to my website, i have a homepage with a button: Start enquete.
When you click that button, you will see the enquete.
In the meantime, when you clicked that button. A ID has been inserted in the database.
Index.php:
<form method="POST">
<input type="hidden" name="x">
<input type="submit" value="Go to enquete">
</form>
<?php
if(isset($_POST['x'])){
$test = $database->insert_user_id();
//header('Location: enquete/page1.php');
}
And the function:
function insert_user_id(){
$sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->('user_id');
}
the return $this->pdo->('user_id'); is something i'm testing with!
Now my question is. How do i return the last inserted id from the table user.
I need to show it on the next page. (See //header).
I can't do this with a other query like: SELECT MAX ID or GetLastInsertId.
This becuase, when some one else also starts the enquete, he will have an other id all of the sudden.
How do i let the person keep the correct id.

Use PDO::lastInsertId
$this->pdo->lastInsertId();

Try this. Manual PDO::lastInsertId
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

You can easily do this by a Get method.
But you can also do this by slightly adjusting your code.
<form method="POST">
<input type="hidden" name="x">
<input type="submit" value="Go to enquete">
</form>
<?php
if(isset($_POST['x'])){
$id = $_POST['X'];
$test = $database->insert_user_id($id);
//header('Location: enquete/page1.php');
}
and change ur function to
function insert_user_id($id){
$sql = "INSERT INTO user (user_id) VALUES ('".$id. "')";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->('user_id');
}
Edit: i failed.
Check this link out http://php.net/manual/en/function.mysql-insert-id.php

If i understand you correctly you want the id of the row you just inserted into the database, and redirect the user to that one?
Index.php
if(isset($_POST['x'])){
$enqueteId = $database->insert_user_id();
header('Location: enquete/page1.php?id=' . $enqueteId);
}
Function:
function insert_user_id(){
$sql = "INSERT INTO user (user_id) VALUES (DEFAULT)";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $this->pdo->lastInsertId();
}

You can make use of PHP mysqli_insert_id() Function which returns the last inserted id of table
For more info go through the link below
http://www.w3schools.com/php/func_mysqli_insert_id.asp

Related

Insert the next highest value in the database using php

Imagine I have a data in the database named warehouse and a whID for the warehouse number. In my add.php I have a form where when you click the submit button, it will add whID data higher than the whID number in the database without using auto increment. I'ved tried a few code for this but nothing works.
this is my code in add.php:
<form action="sidenav/function.php" method="post">
<button type="submit" name="submit" class="button">Add</button>
</form>
This is my code for the function of form in add.php:
if (!isset($_POST['submit'])) {
$insert = $conn->prepare("INSERT INTO warehouse (whID) VALUES (?)");
$insert->bind_param('i', $whNumber);
if ($insert->execute()) {
header('Location: ../warehouseList.php');
die();
}
Sorry for my bad English, I hope you understand my question. Thank you!
If you don't want to use auto-increment just get the highest id from database and increment it yourself.
Quick and dirty example:
$stmt = $conn->prepare("SELECT MAX(whID) as id FROM warehouse LIMIT 1");
$stmt->execute();
$row = $stmt->fetch();
$id = $row["id"] + 1;
Anyway I recommend you to use auto-increment on the id. That's a scenario for what it's created for.

Clicking a submit button won't refresh the mysql stuff

Sorry if my question seems weird, not sure about how to explain it. Here's an example of what my code is looking for :
// SUBMIT FORM
echo '<form action="" method="POST">
<input type="submit" value="Stuff" name="Things"/>
</form>';
// DO THINGS IN MYSQL WHEN CLICKED ON
if (isset($_POST['Things'])) {
$query= $db->prepare('DELETE item_id FROM users WHERE (player_id=:id)');
$query->bindParam(':id', $data['id'], PDO::PARAM_INT);
$query->execute();
}
Now, Imagine I had an image linked to the item_id in the page, for instance :
foreach ($img in $data['item_id']) { // Show IMG }
(This is an example, I may have made some mistakes while writing this but you need to focus on the idea and not the code)
What I would like to do is to make the image (or some text, or some button, or many elements..) when I press the submit button. Because what I have to do right now is making something like this :
if (isset($_POST['Things'])) {
$query= $db->prepare('DELETE item_id FROM users WHERE (player_id=:id)');
$query->bindParam(':id', $data['id'], PDO::PARAM_INT);
$query->execute();
header("Refresh:0");
exit();
}
And submiting already "refresh" the page, so doing this lead in a weird double-page refresh.
Thanks for the help !

Get ID from PHP URL and use in a query

I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)

Select Data from Database with Id From URL

I've a database it is look like this
|ID | Name |
|081| John Davidson|
and i have "index.php" in my website, i've learnt about php form, using method get, and the url is change to index.php?id=081
<form action="index.php" method="get">
<input name="id" value="081"/>
<input type="submit" value="Submit"/></form>
and when the page is loaded i want to show the name of id 081 from my database, how to do that?
Try this,
//Your index.php file
if($_GET['id']){
$id = $_GET['id'];
$sql="SELECT * FROM tableName where id='$id'";
$data = mysql_query($sql);
$row = mysql_fetch_array($data);
echo $row['name'];
}
<form action="index.php" method="get">
<input name="id" value="081"/>
<input type="submit" value="Submit"/></form>
After submitting , you are sending the id value with GET to index.php by url.
You can catch it with $_GET['id'],and store it in database like this:
$sql="INSERT INTO table SET id='".$_GET['id']."'";
$query=mysqli_query($connection,$sql);
If you want to retrieve this value from the database,you can do it like this:
$sql="SELECT id FROM table";
$query=mysqli_query($connection,$sql);
$row=mysqli_fetch_array($query);
echo $row['id'];
UPDATE As Abhik mentioned, those statements are very vulnerable, you should probably learn about using prepared statements here
Another simple way of avoiding sql injection , since it's pretty obvious you are new to php , is to use POST method instead of GET , and check on user input with this little function:
function test_input($data){
$data=htmlentities($data);
$data=stripslashes($data);
$data=trim($data);
return $data;
}
$id=test_input($_POST['id']);
Of course,depending on the field type, there must be some validation like min,max length , character allowed , etc.

button to call php to delete mysql row via ID

Hi I have a html form button called delete. Next to the button is an input area. The logged in user will enter a number corresponding to the ID then press delete. It should delete the row corresponding to that ID.
For some reason it doesn't work.
This is my html form:
<h3 class="block-head">Delete Job</h3>
<form action="deletejob.php" method="post" class="basic-grey">
<label>Please Enter Job ID</label><input type="text" name="idnum" id="id"/><br>
<input type="submit" name="delete" value="delete"/>
</form>
This is my php code:
mysql_connect("********", "root", "******")
or die("Connection Failed");
mysql_select_db("jobslist")or die("Connection Failed");
$idnum = $_POST['id'];
$query = "delete from jobs_list where idnum = '".$id."'";
if(mysql_query($query)){ echo "deleted";}
else{ echo "fail";}
I know about switching to mysqli and that...I just want to see if this method works first.
thanks.
the name of your input is idnum yet you are looking in the $_POST array for id and in your query using the variable $id when you declare $idnum in the line previous.
$idnum = intval($_POST['idnum']);
$query = "delete from jobs_list where idnum = '".$idnum."'";
PHP receive the data via $_POST as an array of input elements with the key as the NAME of the input field, so you have to change this line:
$idnum = $_POST['idnum'];
You can also change the input name and don't change the php code:
<input type="text" name="id" id="id"/>
It's a typical mistake, don't worry too much about that :P
You should change the POST value.. and then try
$idnum = $_POST['idnum'];
Change the HTML, update the input type id to:
id="idnum"
then, update the PHP query while fetching the post value to:
$idnum = $_POST['idnum'];
It should work.

Categories