How to get the last ID with mysql using php - php

I have a form with two stages, the first is to put the information but the second is the UPDATE to add the photo. So what I want to do is retrieve the last auto incremented ID to update the data, I used LAST_INSERT_ID ()
but I realize it is the update everywhere. Do you have a suggestion for me to help me? Thank you and sorry sorry for my english.
You can see here what I did:
$sql = 'UPDATE 'jj_news' SET
cover_picture="'.$large_image_name.$_SESSION['user_file_ext'].'",
min_picture="'.$thumb_image_name.$_SESSION['user_file_ext'].'", statut="1",
edited="'.date('Y-m-d h:i:s').'" WHERE id_news= LAST_INSERT_ID(id_news)';
mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

You cannot get your id in the "second stage". You have to get it immediately after running insert.
So, get it in the first stage, store it in a session and then use in the second one.

Bloody hell, why don't you just store the damn id, into a hidden post field and pass it to the second page on form submit?

mysql_query("INSERT INTO `xy` (`xy`) VALUES ('$_POST[xy]');");
$insertId = mysql_insert_id();
mysql_query("UPDATE xy SET xy='$xy' WHERE id='$insertId'");
only know from the mysql_* function...
use mysqli or PDO, but if this helps you i´m glad.....

You can try the following function.
function getLastId($tablename,$id_field){
$id=0;
$sql="select ".$id_field." from ".$tablename." order by ".$id_field." desc limit 1" ;
$res_obj=mysql_query($sql) or die(mysql_error);
if(mysql_num_rows($res_obj)>0){
$result=mysql_fetch_array($res_obj); //we have only on row and column.
$id=$result[$id_field]; //set the last greator Id value;
}
return $id;
}
$newid=getLastId("yourtable","id_field")+1;
//insert your data using $newid instead of autocomplete.
//use $newid during update if update is on new page make a session of $newid. like
$_SESSION['update_id']=$newid;
this function make manual increment of id column, instead of auto increment. I think it is ease to control your situation using this function.

Related

Primary Key of the DB as PHP header info

I have created a registration form which is in application.php and when submitted it is processed and the contents are stored using submit.php and I want to redirect to thanks.php with a parameter called message with value equal to the primay key of the recently inserted row.. For example it should return my 100th applicant to the page,
www.mydomain.com/thanks.php?message=100
where 100 is the Primary key (AI).
In other words I want to print the primary key of the table as a refernce id for the users.. I tried
header("location: thanks.php?message=".$id); and
header("location: thanks.php?message=".$_POST['id']);
Both dont work for me.
Kindly help me guys!
EDIT:
require("admin/sources/connection.php");
$id = mysql_insert_id();
// Other variables are declared here
$sql = "my_INSERT_query_goes_here";
$result = $conn->query($sql);
if($result) {
header("location: thanks.php?message=".$id);
}
This is my submit.php code
Wrong execution order - simple fix
You are first assigning $id, and then running the query.
Twist them around to make it work.
Not using auto-increment?
I see in the query in your comment, that you manually pass the id you want to enter. Did you realize that mysql_insert_id() will not return the sql column that you did call "id", but the column that you set an auto-increment on? That is a single row in your table that automaticly gets an incrementing number without the need to manually enter it.
Couple issues ... it looks like you're mixing mysql_ methods with mysqli and you have the execution in the wrong order.
If your database table is auto-increment, you don't need to pass an ID in the query. By calling $id = mysql_insert_id(); and using the id in the query, you're passing in 0 as the id which uses the next auto-increment id.
Getting the insert_id after $conn->query($sql); will return to you the insert id used.
Echo some variables to see what values you're getting for mysql_insert_id(); before and after.
However, if you're doing a $conn->query(), then you're not using the standard mysql_ functions.
Try this:
require "admin/sources/connection.php";
// Other variables are declared here
$sql = "my_INSERT_query_goes_here";
$result = $conn->query($sql);
if($result) {
$id = $conn->insert_id;
header("location: thanks.php?message=".$id);
}

How to get inserted data from a query to database as success message?

i'm working for a project and this problem came across me as i'm not a master in php and mysql.
here is the sample.
table
id(AI)-fname-lname
<php
include 'db.php';
$query=mysql_query("INSERT INTO table(`fname`, `lname`) VALUES('some', 'one')");
if($query==1)
{
//some code
}
this is working fine, i can know whether the Query is Successful or not. what i want to know is, how to get the data of the row i just inserted, so that i can use the 'id' in another related table...
hoping for positive responce..
Use this function
mysql_insert_id()
This will return you the last inserted id with specific database connection. Also you don't want to get the data inserted other than id, because you already have it while inserting row.
you can get id of recent inserted record using mysql_insert_id()
by using that id you can get records using select query
<?php
include 'db.php';
$query=mysql_query("INSERT INTO table(`fname`, `lname`) VALUES('some', 'one')");
$id=mysql_insert_id();
$select_query=mysql_query("SELECT * FROM table where id=".$id."");
?>
You can use this function
$id = mysql_insert_id();
This will give the id to which the data is inserted, you can use that id for further use.
This will give you the key ID of the row
$id = mysql_insert_id();

How to delete and update data in MySQL at the same time

Basically what I am trying to do is when I delete a client with an ID of lets say 6 and I have 50 clients, I then want to update the client with the ID of 50 to 6.
This is my code, in PHP, but it won't execute 2 mysql_query-s at the same time at least I think that's the problem. Otherwise the SQL syntax works fine.
public function delete () {
$last=$this->numrow; //contains last ID works fine
if (isset ($_GET['x'])) {
mysql_query('DELETE FROM proba WHERE ID ='.$_GET['x']);
mysql_query('UPDATE proba SET ID='.(int)$_GET['x'].'WHERE ID='.(int)$last);
}
}
The $_GET['x'] contains the ID on which it was clicked . But only the first mysql_query gets executed how do i make it so the second one gets executed also ?
And another question is is it possible to get <a href="munka/index.php?x=5" > [-] </a> the x=5 with a $_POST ?
You might save yourself a lot of trouble by using mysql's replace query:
see http://dev.mysql.com/doc/refman/5.6/en/replace.html
for details.
most probably you are facing a php error on the first query. Check the php error log.
for the second question $_GET is used to take parameters from the URL for example
munka/index.php?x=5
$_POST is used to get parameters posted on http post (usually on form submits).
just change the update query with a space before the where clause
mysql_query('UPDATE proba SET ID='.(int)$_GET['x'].' WHERE ID='.(int)$last);
Better to use transactions support by using InnoDB Mysql DB Engine, so both delete and update execute together wuth COMMIT without miss , and in case anything goes wrong your delete changes get ROLLBACK
if (isset($_GET['x'])) {
mysql_query('DELETE FROM proba WHERE ID =' . $_GET['x']);
mysql_query('ALTER TABLE `proba` DROP `ID`;');
mysql_query('ALTER TABLE `proba` ADD `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
}
Try in Phpmyadmin delete record no of 5 and drop id column and recreate id column.
It is work.

Check for duplicate when editing a record in MySQL

I'm having problems with a piece of code and wonder if someone can help.
I have a form that submits information to a MySQL database, I have the correct code for checking to see if the submitted product code already exists, and if so shows a warning message and the record is not added.
That code is:
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code'");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - <b>$product_name</b> has <b>NOT</b> been added because the reference number already exists.");
}
That works fine for Data Entry, however I have another form that allows users to edit the record, this is what is causing me a problem, as the above code only tells me that there is already a matching record in the database, Of course when I try to save (update) the record it now tells me I can't because it is a duplicate.
What I would like to happen is that it doesn't allow users to choose another productcode that already exists, but I want them to be able to update the record using the same product code the form fetched from the database.
Hope that makes sense, any help greatly appreciated.
If you have id (primary key) then You will have to compare with id of that product before updating the record. For example
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code' AND id!=$id");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
echo "duplicate record";
}
Here $id is the id of the product that you should have while editing the record.
following is the step you need to follow when you managing the Database
First you need an primary key(auto_increment) in "ID" field
When you execute insert query that time first check where record is already available or not. if not available than only you should execute insert query.
use primary key filed for update, delete etc...
if you follow the above step than you never face this problem
Are you perhaps checking for duplicate occurrences in both of insert and update statement? If so, you shouldn't. Duplicate entry is relevant only when "inserting". You shouldn't use the same check for update. Hope that helps.
why the same code for update also? you can use another query for updating which is better for debugging if you have problems later. try this
$result = mysql_query("UPDATE listing_1 SET product_code='$new_product_code' WHERE product_code='$product_code' AND id='$id'");
if($result) {
echo "your product was updated.";
} else {
echo "your product is not in DB";
}
EDIT: be careful in updating or inserting things, take always id to check unless your product_code is unique
EDIT
I have resolved this issue by making $productcode field a unique Index.
Now when editing if there is a duplicate..
Mysql does not accept the update query, it returns an error code
I trap that error code and include it in an if statement...
if( mysql_errno() == '1062' )
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - $product_name has NOT been added because the reference number already exists");
}
adminmessage("Item Updated", Congratulations you updated $productname succesfully");
}
This now allows editing of $productcode but does not allow it to be changed to one already used in the database.
Thank you to everyone who took the time to offer help

How get value from POST

This piece of code has been tripping me out for the past four hours. It is deleting a row of photos by the primary ID.
I have var_dump($selectedPhoto) and it is the correct ID, a number. My code will run every time I press delete photo, get to the mysqli_stmt_store_result part and shoots out the $txtMessage, But the database does not update.
This is really weird because I have used the exact same code, with different variables on another page and it works perfectly fine.
Can you see any errors by looking at this? OR have a better way to writing the delete statement.
if (isset($_POST['btnDeletePhoto']))
{
$selectedPhoto = $_SESSION['selectedPhoto'];
$deleteString = "DELETE FROM Photos WHERE PhotoID = ?";
$preparedDeleteStmt = mysqli_prepare($link, $deleteString);
mysqli_stmt_bind_param($preparedDeleteStmt, 'i', $selectedPhoto);
if (!mysqli_stmt_execute($preparedDeleteStmt))
{
mysqli_close($link);
die("The system is not available, try again later");
}
if(mysqli_stmt_store_result($preparedDeleteStmt))
{
$txtMessage = "Delete successfull";
}
To add: $selectedPhoto is a value of a select, drop down list value.
If the photo comes from the value of a select, it is not going to be stored in a session variable, so you probably need to change:
$selectedPhoto = $_SESSION['selectedPhoto'];
to:
$selectedPhoto = $_POST['selectedPhoto'];
Apart from that you need to add error handling to all database operations.

Categories