Related
I have written my sql below and it works. As I've set my particulars_id to autoincrement, i have to use Last_Insert_ID() in order for the database to use the next id using auto increment. However, i would like to store that value into a php variable. Is that possible?
$addquery = "INSERT INTO Particulars (Particulars_ID, Name, Identification_Number, Number, Nationality, Status, Remarks)
VALUES(LAST_INSERT_ID(),'$_POST[newname]', '$_POST[newic]','$_POST[newnumber]','$_POST[newnationality]','$_POST[newstatus]','$_POST[newremarks]')";
When you insert a row into a table that has an AUTO_INCREMENT field that field will be incremented automatically as the name implies. You don't need to tell MySQL to increment it, you don't have to provide a value for the auto-increment field at all.
So to begin with, remove the call to LAST_INSERT_ID() from your query:
$addquery = "INSERT INTO Particulars (Name, Identification_Number, Number, Nationality, Status, Remarks)
'$_POST[newname]', '$_POST[newic]','$_POST[newnumber]','$_POST[newnationality]','$_POST[newstatus]','$_POST[newremarks]')";
Notice how I completely removed the Particulars_ID from the query.
Second, this is not directly related to your question but your query is vulnerable to SQL Injection. When accepting user input you should avoid concatenating it to your query, instead use Prepared Statements and modify your query like this:
$addquery = "INSERT INTO Particulars (Name, Identification_Number, Number, Nationality, Status, Remarks)
VALUES(?,?,?,?,?,?)";
You can then prepare a statement and bind the values from $_POST. This essentially sanitizes user input. Read more about prepared statements here
START OF EDIT
An example of binding the real values to the ? placeholders using PDO:
//First prepare the statemt
$db->prepare("INSERT INTO Particulars (Name, Identification_Number, Number,Nationality, Status, Remarks)
VALUES(?,?,?,?,?,?)";
//Start binding values to placeholders
$db->bindValue(1, $_POST['name']);
$db->bindValue(2, $_POST['Identification_Number'];
$db->bindValue(3, $_POST['Number'];
//Bind the rest of the values in the same way
END OF EDIT
About the id of the last inserted row you will need to run a separate query to get it. So after you run the above query and if insertion is successful you can
run a query like this:
SELECT LAST_INSERT_ID() AS id FROM Pariculars
I have a PHP-script in which I can register news users.
Of course I want to insert things like username, password etc. (these values come from the user) but on the other side I want to insert his user_id (new user!) into another table.
My SQL
$sql = "
BEGIN;
INSERT INTO users (username, password, auth_lvl, realname, usercolor) VALUES ('$username', '$password', '$auth_lvl', '$realname', '$usercolor');
INSERT INTO users_startmodules (user_id, startmodule, enabled) VALUES ('(SELECT MAX(user_id)+1 FROM users)', 'newsmodule', '1');
COMMIT;
";
How can I solve this problem and is BEGIN; ... COMIT; the right choice when I want to get the query canceled if just one thing didn't work, because I don't want to have just a few entries in the worst case.
I suggest to change the type of user_id in users table to auto_increment with something like this:
alter table users alter column user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
Now, Assuming that you have escaped the user input data:
$query="INSERT INTO users (username, password, auth_lvl, realname, usercolor) VALUES ('$username', '$password', '$auth_lvl', '$realname', '$usercolor');"
and run that:
$mysqli->query($query);
then get the userid with mysql_insert_id() function of MySQL or alternatively in PHP:
$userid=$mysqli->insert_id;
and:
$query="INSERT INTO users_startmodules (user_id, startmodule, enabled) VALUES ('$userid', 'newsmodule', '1');";
$mysqli->query($query);
This is too long for a comment.
To get the id that was just inserted, use last_insert_id(). This function is documented here.
Next, the answer to your question is to start a transaction. I would give you the syntax, but it is better for you to read the documentation on transactions before you start using them.
The key idea is that a transaction groups data modifications together. Either all take place or none do. Along the way, you can use commit or rollback, depending on whether or not you want to keep the changes or keep none of the changes.
I have a table named user_data which contains 5 rows-id(primary key),name,address,phone,sex.When I try to insert values into the table via this query
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
it doesnt work.But When I tried this one,it works.
mysqli_query($con,"INSERT INTO user_data (name,address,phone,sex) VALUES ('Peter_Gregory', 'Griffin door',35897,'male')");
I didnt understand what is the real issue behind this.I am using PHP 5.4.7 and XAMPP 1.8.1.
instead of this:
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
Use this when the field is set as NOT NULL
mysqli_query($con,"INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')");
Or use this when the field is set as NULL
mysqli_query($con,"INSERT INTO user_data VALUES (0, 'Peter_malik', 'Griffin door',35897,'male')")
See the mysql manual: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
It does not insert in the first query since it assumes the first value i.e. 'Peter_malik' is for your primary key and it fails.
When you specify the column names in the query it knows which value is for which column.
I addition in the first case i.e.
'Peter_malik', 'Griffin door',35897,'male'
will refer to
id(pk),name,address,phone
So u need to pass the first value as NULL so that id gets auto incremented. So the first query should be as
VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male')
If your table has 5 columns id, name, address, phone and sex your staement has to provide 5 values, one for each column. Since your stament provides only 4 values, you need a column list to tell MySQL which values you do provide.
If your id column is a auto_increment column, you can provide null in your values clause.
So you have to say:
INSERT INTO user_data VALUES (NULL, 'Peter_malik', 'Griffin door',35897,'male');
OR
INSERT INTO user_data (name,address,phone,sex) VALUES
('Peter_malik', 'Griffin door',35897,'male')
You need to include the id column on your insert statement:
mysqli_query($con,"INSERT INTO user_data VALUES (null, 'Peter_malik', 'Griffin door',35897,'male')");
, provided that your id field is set to autoincrement! ;)
If you provide the ID also in your first query, it will work without any problem.
Assuming that id=1
mysqli_query($con,"INSERT INTO user_data VALUES (1,'Peter_malik', 'Griffin door',35897,'male')");
As others said when you have not explicitly mentioned your column names in a query, you have to provide all the values.
when you are trying the following query then...
mysqli_query($con,"INSERT INTO user_data VALUES ('Peter_malik', 'Griffin door',35897,'male')");
In this query you only inserting 4 values in the table but the table has 5 field so it is causing problem because in the above query the value is inserting form first field & the sequence or datatype mismatching in the database because of this this query causing problem .
If u want insert wuthout specifing field then you may use the following query....
mysqli_query($con,"INSERT INTO user_data VALUES (0,'Peter_malik', 'Griffin door',35897,'male')");<br><br>
It Will work properly.
and in the your second query you also specifying the field name & corresponding their values so that's query not causing any problem.
I have a MySQL table with an auto-incrementing primary key (UID). The user can bring up a record in this table via a PHP form, where the UID is a $_GET variable. I would like the database to update the chosen record if it exists, but every time the user hits submit, a new record is created. This is what I've tried so far:
//Present the form
$form = $con->prepare("SELECT Name, Date, Time FROM forms WHERE UID = :uid");
$data = array('uid'=>$_GET['uid']);
$form->execute($data);
$row = $form->fetch(PDO::FETCH_ASSOC);
//Write new record to database. If the UID exists, update the record.
INSERT INTO forms (Name, Date, Time) VALUES (:name, :date, :time)
ON DUPLICATE KEY UPDATE Name=VALUES(Name),Date=VALUES(Date),Time=VALUES(Time);
This doesn't work. Do I need another unique key in the table, or am I missing something obvious?
INSERT INTO forms (`Name`, `Date`, `Time`) VALUES (:name, :date, :time)
ON DUPLICATE KEY UPDATE `Name`=:name, `Date`=:date, `Time`=:time;
This should be the query; I removed VALUES() from your code and added backticks and corrected your parameters.
And I recommend you to use backticks around column names so it doesn't get confused with other similar SQL keywords as example.
I am not able to insert id and name in myTable MySQL table by using following PHP syntax. id is integer field and name is varchar field.
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", ".$_SESSION["name"].");";
Is there something wrong with above syntax? As per me its right because if insert hardcoded values, those are inserted fine.
Yes, you need to use single quotes for name
$query="INSERT INTO myTable (id, name) VALUES (" . $_SESSION["id"] . ", '" . $_SESSION["name"]."');";
Also, please try not to contstruct the queries by hand using string concatenation/substitution. It can be dangerous if your $_SESSION (somehow) contains content that can manipulate queries completely.
Read about SQL Injection, and what PHP offers.
Put the string value inside quotes:
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";
String should be enclosed in quotes
$query="INSERT INTO myTable (id, name) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."');";
name is a reserved word. Put backticks around it. Also, you need quotes around your name variable (and the id, if it is not an integer).
Your query should look like this:
$query="INSERT INTO myTable (id, `name`) VALUES (".$_SESSION["id"].", '".$_SESSION["name"]."')";
use this
$query="INSERT INTO myTable (id, name) VALUES ({$_SESSION["id"]},'{$_SESSION["name"]}');";