I was using the code below, when user_id wasnt set as unique and it entered the same data twice with the same user_id. So I have set it to unique and now just get Error, query failed.
All help is greatly appreciated :(
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
// insert into the database
$the_query ="SELECT * FROM thesis WHERE user_id='$_SESSION[user_id]'";
$testResult = mysql_query($the_query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
//insert...
$the_query ="INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)";
$result = mysql_query($the_query) or die('Error, query failed') ;
}
else{
//update...
$the_query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE user_id='$_SESSION[user_id]'";
$result = mysql_query($the_query)or die('Error, query failed');
}
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
I have also tried
$the_query = "INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)
ON DUPLICATE KEY UPDATE thesis_Name=VALUES(thesis_Name), abstract=VALUES(abstract)";
Use ON DUPLICATE KEY UPDATE.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Example:
INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)
ON DUPLICATE KEY UPDATE thesis_Name=VALUES(thesis_Name), abstract=VALUES(abstract)
This basically handles the duplicate checking and choosing between INSERT and UPDATE all on the MySQL side, which is much faster (by about a factor of 2). As a bonus, the VALUES() function allows you to retrieve values from the row being inserted, so that you don't have to provide the values twice and multi-row inserts work properly.
In response to an edit to the OP:
You have to specify the individual columns to change in the UPDATE clause. If you want to update thesis_Name and abstract, then you have to specify those. If you specify only the unique key that caused the update in the first place, then it will update only that, which will most likely do nothing!
What I think you are looking for is: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html which will update the row if the insert query encounters a duplicate key.
Related
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
I have looked everywhere and keep getting different answers and incorrect code. All I want to do is after I have added a field to my database in MySQL is to get the user_id of the field that has just been created. I just cannot seem to do it?
I am using this to input the field and thanks for any help. It has a auto_increment value of user_id which is what I need to get.
mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq)
VALUES ('$business', '$email_uniq')");
use this after insert query
$last_row = mysqli_insert_id($con);
You can return the primary key of the last row inserted with
$last_id = mysqli_insert_id($con);
You can find more information here: http://php.net/manual/en/mysqli.insert-id.php
After executing the query, you can use mysqli::$insert_id value or mysqli_insert_id function to retrieve the last generated id, like this:
mysqli_query($con,"INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = mysqli_insert_id($con);
or using the object functions:
$con->query("INSERT INTO users_accounts (business, email_uniq) VALUES ('$business', '$email_uniq')");
$insert_id = $con->insert_id;
edit: Not related, but definitly important!
If the values for either of these parameters $business or $email_uniq are user supplied, it is highly recommended to make sure they are filtered properly. The easiest way is by using a prepared statement for security (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Here is your code using prepared statements:
$stmt = $con->prepare("INSERT INTO users_accounts (business, email_uniq) VALUES (?,?)");
$stmt->bind_param("ss", $business, $email_uniq);
$stmt->execute();
$insert_id = $con->insert_id;
I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php
PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.