PHP SQL insert prepared statements doesn't insert properly - php

When executing the following code, no Errors occur but the data isn't put into the database!
$zero = 0;
$connection = new mysqli("localhost", "andrewle_me", "*****", "andrewle_velocity");
$stmt = $connection->prepare("INSERT INTO accounts Values(?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issssssi", $zero, $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT), $_POST["Email"], $_POST["firstname"], $_POST["lastname"], $_POST["nationality"], $zero);
$stmt->execute();
$stmt->close();
$connection->close();
echo "Success";

Define your posts and password hash outside of the param binding. Set the fields in the table that your values are going to be entered into.

Related

How to run multiple INSERT queries in a transaction and use insert id?

I need to insert data into 3 tables and need to get the id of last inserted query into shopper table. I know this is doable by running
$conn -> insert_id;
in a single query but in my case I need to create a transaction with rollback in case of any failure. something like
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$stmt1 = $conn->prepare("INSERT INTO shopper (usersID, parentJob, phoneNumber,address) VALUES (?, ?, ?, ?)");
$stmt1->bind_param("ssss", $userId, $parentJob, $phoneB, $addressB);
$stmt2 = $conn->prepare("INSERT INTO shipment (shipmentID, usersID,..) VALUES (?, ?, ?, ?)");
$stmt2->bind_param("ssss", $userId, ...);
$stmt3 = $conn->prepare("INSERT INTO address (addressID, usersID, ...) VALUES (?, ?, ?, ?)");
$stmt3->bind_param("ss", $userId, ...);
$conn->begin_transaction();
if ($stmt1->execute() && $stmt2->execute() && $stmt3->execute()) {
$conn->commit();
} else {
$conn->rollback();
}
$conn->close();
As you can see I am trying to pass last inserted usersID as Foreign Key into shipment and address tables. so how can I do this when committing all of them together like
if ($stmt1->execute() && $stmt2->execute() && $stmt3->execute()) {
$conn->commit();
} else {
$conn->rollback();
}
Exceptions offer enormous help with transactions. Hence configure mysqli to throw exceptions. Not only for transactions but because it's the only proper way to report errors in general.
With exceptions your code will be plain and simple
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$conn->set_charset('utf8mb4');
$conn->begin_transaction();
$stmt = $conn->prepare("INSERT INTO shopper (usersID, parentJob, phoneNumber,address) VALUES (null, ?, ?, ?)");
$stmt->bind_param("sss", $parentJob, $phoneB, $addressB);
$stmt->execute();
$userId = $conn->insert_id;
$stmt = $conn->prepare("INSERT INTO shipment (shipmentID, usersID,..) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $userId, ...);
$stmt->execute();
$stmt = $conn->prepare("INSERT INTO address (addressID, usersID, ...) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ss", $userId, ...);
$stmt->execute();
$conn->commit();
in case of error an exception will be thrown and a transaction will be rolled back automatically.

SQL Prepared statement not inserting my values

I have this prepared statement and it isn't inserting into the table at all. The connection to my database is working. I am still new to this so I am unsure on what is wrong. The spelling of my table is correct also. My network tab on inspect element doesn't show any errors as if it did insert the data but the table doesn't update with said data.
$stmt = $conn->prepare("INSERT INTO usersreports (DateOfReport,Username,ReportedPostId,ReportedUser,ReportedUserId,ReportedReason,ReportedTopic,Resolved,Response,ActionTaken) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $DateOfReport,$YourUsername,$UsersPostId,$ReportedUsername,$ReportedUserId,$ReportReason,$ReportTopic,$Resolved,$Response,$ActionTaken);
if ( $stmt === false ) {
echo $conn->error;
exit;
}
$stmt->execute();
$stmt->close();
$conn->close();

How to Use prepare statement to insert data to three different tables in MySQLi with consideration of transaction

What is the perfect and safest way to execute the following SQL statements simultaneously, with consideration of transaction in MySQLi in order the data to be added to all tables or the data needs to be rolled back when a failure happens to the adding process of one on the tables.
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$stmt1 = $conn->prepare("INSERT INTO stdHouseholder (usersID, parentJob, phoneNumber,address) VALUES (?, ?, ?, ?)");
$stmt1->bind_param("ssss", $userId, $parentJob, $phoneB, $addressB);
$stmt2 = $conn->prepare("INSERT INTO stdConfirmInfo (usersID, commitment, credentials, haveOfficialLetter) VALUES (?, ?, ?, ?)");
$stmt2->bind_param("ssss", $userId, $commitment, $credentials, $NamesEnglish);
$stmt3 = $conn->prepare("INSERT INTO users_roleTB (usersID, role_id) VALUES (?, ?)");
$stmt3->bind_param("ss", $userId, $role_id);
You can use the begin transaction, commit and rollback features of the mysqli commands to assist with you.
You'll want to start a transaction, check the result of each insert query and then commit (if they all performed well) or rollback if they didn't:
<?php
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$stmt1 = $conn->prepare("INSERT INTO stdHouseholder (usersID, parentJob, phoneNumber,address) VALUES (?, ?, ?, ?)");
$stmt1->bind_param("ssss", $userId, $parentJob, $phoneB, $addressB);
$stmt2 = $conn->prepare("INSERT INTO stdConfirmInfo (usersID, commitment, credentials, haveOfficialLetter) VALUES (?, ?, ?, ?)");
$stmt2->bind_param("ssss", $userId, $commitment, $credentials, $NamesEnglish);
$stmt3 = $conn->prepare("INSERT INTO users_roleTB (usersID, role_id) VALUES (?, ?)");
$stmt3->bind_param("ss", $userId, $role_id);
$conn->begin_transaction();
if ($stmt1->execute() && $stmt2->execute() && $stmt3->execute()) {
$conn->commit();
} else {
$conn->rollback();
}
$conn->close();
You can't insert to multiple tables in one statement
you will have to put them in a transaction
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$conn->query("BEGIN;");
$failed = false;
$stmt1 = $conn->prepare("INSERT INTO stdHouseholder (usersID, parentJob, phoneNumber,address) VALUES (?, ?, ?, ?)");
$stmt1->bind_param("ssss", $userId, $parentJob, $phoneB, $addressB);
if (!$stmt2->execute()) {
$failed = true;
$conn->query("ROLLBACK;");
}
if(!$failed){
$stmt2 = $conn->prepare("INSERT INTO stdConfirmInfo (usersID, commitment, credentials, haveOfficialLetter) VALUES (?, ?, ?, ?)");
$stmt2->bind_param("ssss", $userId, $commitment, $credentials, $NamesEnglish);
if (!$stmt2->execute()) {
$failed = true;
$conn->query("ROLLBACK;");
}
}
if(!$failed){
$stmt3 = $conn->prepare("INSERT INTO users_roleTB (usersID, role_id) VALUES (?, ?)");
$stmt3->bind_param("ss", $userId, $role_id);
if (!$stmt3->execute()) {
$failed = true;
$conn->query("ROLLBACK;");
}
}
if(!$failed){
$conn->query("COMMIT;");
}
LOCKING TABLES ?
If you want to make a transaction while locking your tables , you are going to need another approach ,because locking a table is going to commit any running transaction, and this is horrifying.
In this case you are going to start the transaction by turning off the auto commit feature of mysql
SET autocommit=0;
Then you lock your tables
LOCK TABLES stdHouseholder WRITE, stdConfirmInfo WRITE, users_roleTB WRITE;
Then run your prepared statements normally
$stmt->execute();
Finally, if the statements succeed then you commit the transaction , and turn the auto commit on again.
$conn->query("COMMIT;");
$conn->query("SET autocommit=1;");
Note that if you didn't commit (and didn't roll back) the transaction will be rolled-back when the session ends (but this is not guaranteed).

PHP,PDO,MySQLi function dont insert to database

I make code that using pdo to insert information to database and gain XSS protection.
now im few days look at the code and dont see the problem that make the code to not insert the requird information.
Here`s My code:
if ($register = $mysqli->prepare("INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (! $register->execute()) {
echo "אירעה שגיאה";
$register->close();
}else{
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';}
$register->close();
}
And the connection code:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
Thank you.
Use mysqli_affected_rows to get the number of inserted row, if any function fails, check for errors using mysqli_error
$sql = "INSERT INTO `accounts`(`id`, `username`, `email`, `password`, `salt`, `fullname`, `birthdate`, `gender`, `secure question`, `secure answer`, `asked`, `answered`, `lastlogin`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($register = $mysqli->prepare($sql)) {
$register->bind_param("ssssssddsdds", $username, $email, $password, $random_salt, $fullname, $birthdate, $gender, $question, $answer, $z, $z, $lastlogin);
// Execute the prepared query.
if (!$register->execute()) {
echo "אירעה שגיאה";
die("execute() failed: ". mysqli_error($mysqli));
}
if(mysqli_affected_rows($register) > 0){
echo 'אתם נרשמתם בהצלחה!. לחצו כאן';
}else{
echo 'Did not inser any row';
}
}else{
die("prepare() failed: ". mysqli_error($mysqli));
}

Get last ID after SQL insert

This code below inserts some data into a MySQL database. I want the page to load to this record after the insert but the variable ($insert) that I'm trying to load is not coming through on the header. can someone help?
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO riders (firstname,secondname,email,mobile,landline,dob,addressline1,town,county,postcode) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($firstname,$secondname,$email,$mobile,$landline,$dob,$streetaddress,$town,$county,$postcode));
$insert = mysql_insert_id();
Database::disconnect();
header("Location:read.php?id=.$insert");
Use $pdo->lastInsertId() for getting last ID after SQL insert.

Categories