If inserting into two mysql tables at the same time is there a chance that another user could insert at the same time making the tables offset?
For example hypothetically: (In php)
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO Name (user_id, name, email)
VALUES (DEFAULT, 'User name', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO Location (user_id, addressline1, addressline1, postcode)
VALUES (DEFAULT, '123 street', 'anytown, country', '123456')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
If 'John' ran this at the same times as 'Bob' is it possible for john's Name to be given the auto-increment id of 1 and his Location to be given 2 because Bob's Location was given 1 first even though his Name was given 2.
Kinda hard to explain.
I want to know if 1000's if not millions of people are running this
could it occur?
is there some reason MySQL will stop this from
happening?
if not what can/can anything be done to prevent it?
In your scenario, given the code you posted, the thing you're worried about is possible and will definitely happen as you gain more and more users.
Using insert_id from mysqli will solve this issue for you. The autoincremented id from the last successful insert query is stored in here for precisely this reason. Change your second sql query to this.
$sql = "INSERT INTO Location (user_id, addressline1, addressline1, postcode)
VALUES ({$conn->insert_id}, '123 street', 'anytown, country', '123456')";
and its no longer a problem.
Related
Is it possible to overwrite a user's input and replace it with whatever prepared statement you have hardcoded into your PHP file? I have included the parts of the my PHP file that are relevant to this question. I am literally trying to overwrite whatever the user inputs is for a single string value with my hardcoded string. All of the values would then be inserted into a table in my database. In this case the value I am trying to overwrite is $empid which previously acquired its value from user input. Any suggestions, comments and advice would be greatly appreciated since I have only been studying PHP for a few weeks now.
Thank you for taking the time to read this post.
<?php
$sql = "INSERT INTO employee (EMPID, NAME, DATEHIRED, POSITION, SALARY, DEPTCODE, CANHIRE, BOSSID) VALUES ('$empid', '$employee', '$date', '$position', '$salary', '$department', '$canhire', '$bossid')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt = $conn->prepare("INSERT INTO employee (EMPID) VALUES (?)");
$stmt->bind_param("s", $empid);
$empid='EMP2022';
$stmt->execute();
$stmt->close();
$conn->close();
?>
I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}
I understand that such questions have been downvoted or closed, however I've been through all the previously asked questions and couldn't find any solutions. The code is supposed to accept input from a HTML form and insert it into the MySQL database and be displayed on another page, but somehow I end up with query failed statement and redirected to the Login page.
<?php
if (isset($_POST['eTransport_ID'])){
$id = ($_POST['eTransport_ID']);
}
if (isset($_POST['Phone_No'])){
$phone = ($_POST['Phone_No']);
}
if (isset($_POST['Amount'])){
$amount = ($_POST['Amount']);
}
$DATEE = date("Y-m-d");
$TIMEE = date("h:i:sa");
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ('$DATEE', '$TIMEE', '$amount', 'WEB', '$id')";
$added = mysqli_query($conn, $query);
if(!$added){
die("Database query failed.");
}
else{
echo "Data Entered Successfully";
}
mysqli_close($conn);
?>
MySQL Table
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ('$DATEE', '$TIMEE', '$amount', 'WEB', '$id')";
Can you write query like this
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ($DATEE, $TIMEE, $amount, $phone, $id)";
This is BAD code which has severe SQL injection vulnerabilities so please look into that separately (your question isn't about security)
I'm assuming 'Date' is a DATE column
I'm assuming 'Time' is a TIME column
It looks as though Agent_No may be an INT column, but you're inserting a string. I've substituted for a "1" so you'll have to look at that separately.
If my assumptions are correct, just change the query line to exactly this (ie: copy and paste it):
$query = "INSERT INTO recharge_history (`Date`, `Time`, `Amount`, `Agent_No`, `eTransport_ID`) VALUES (NOW(), NOW(), $amount, 'WEB', $id)";
This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 5 years ago.
I have a very specific problem and nothing I could find online was able to tell me where my error was.
I want to pass two mysql queries at once. Separately, they work perfectly but together they fail. I've tries JOIN, adding ; and the multi_queries method. Everything fails.
Now I am stuck with this code:
// data insertion
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date')";
$sql.= "DELETE FROM comments_validation WHERE id = $id";
if ($conn->multi_query($sql) === TRUE) {
header('Location: http://url.com/index.php?success');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
And the error:
Error: INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('some values')DELETE FROM comments_validation WHERE id = 'some other value'
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM comments_validation WHERE id = 'some other value' at line 1
Thanks in advance!
You have to add a ; at the end of this sql statement
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date');";
^here
Please add semi-colon as string at the end of every query in multi query.
// data insertion
$sql = "INSERT INTO comments (id, name, email, comment, article_id, date) VALUES ('$id', '$name', '$email', '$comment', '$article_id', '$date');";
$sql.= "DELETE FROM comments_validation WHERE id = $id";
if ($conn->multi_query($sql) === TRUE) {
header('Location: http://url.com/index.php?success');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I have checked for similar questions regarding the error however they didn't match the issue I seem to be having.
Getting the following error when attempting to insert data into database:
Column count doesn't match value count at row 1?
Here is a screenshot of the database table:
In the HTML a form, with an action of the php file, has multiple inputs with the names: name, surname, DateOfBirth, email, password, confirm-password
PHP:
<?php
// Only process the form if $_POST isn't empty
if ( ! empty( $_POST ) ) {
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', '', 'pptpp' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = "INSERT INTO user ( Forename, Surname, DateOfBirth, Email, Password ) VALUES ( '{$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password '])}' )";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success! Row ID: {$mysqli->insert_id}";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
// Close our connection
$mysqli->close();
}
?>
The following part
$mysqli->real_escape_string($_POST['name, surname, DateOfBirth, email, password ']
is invalid for two reasons:
mysqli::real_escape_string() takes only 1 argument at a time, a string (unless using procedural, mysqli_real_escape_string(), then the first is the connection, then the string as the second)
The $_POST can't be accessed in that way, I highly doubt you have one field named all that. You'll have to specify the index, as $_POST['name'] etc.
The solution is to match each column with the respective escaped value from $_POST,
like $mysqli->real_escape_string($_POST['name']) for the name,
$mysqli->real_escape_string($_POST['email']) for the email and so on, an example could be assigning it to variables, and using those in the query, as shown below.
$name = $mysqli->real_escape_string($_POST['name']);
$surname = $mysqli->real_escape_string($_POST['surname']);
$dob = $mysqli->real_escape_string($_POST['DateOfBirth']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES ('$name', '$surname', '$dob', '$email', '$password')";
$insert = $mysqli->query($sql);
Then you should note that even with mysqli::real_escape_string(), it's not secure against SQL injection, and that you should use parameterized queries. An example of that is given below.
// Insert our data
$sql = "INSERT INTO user (Forename, Surname, DateOfBirth, Email, Password) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("sssss", $_POST['name'], $_POST['surname'], $_POST['DateOfBirth'], $_POST['email'], $_POST['password']);
if (!$stmt->execute())
die("Execution failed: ".$stmt->error);
echo "Success! Row ID: ".$stmt->insert_id;
$stmt->close();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
Usage of PHP error-reporting would've likely mentioned something about undefined indexes when you use the current escape. Always (in development) let PHP give you the errors, by enabling error-reporting with error_reporting(E_ALL); ini_set("display_errors", 1); at the top of your file.
Also note that storing passwords in plain-text is a big no. You should use functions like password_hash() / password_verify() to properly and securely store your users passwords.
References
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/mysqli-stmt.prepare.php
How can I prevent SQL injection in PHP?