Below is the modified code with Prepared Statement.
First step is to connect to the database. To do that, we need to define the access details.
// Define Database Credentials
$servername = "localhost"; //Server Name
$username = "KyleHulse"; //Username to the DB
$password = "(my password)"; //Password to the DB
$dbname = "csdb1082"; //Name of the Database
// Create Database Connection
$conn = new mysqli($servername, $username, $password, $dbname);
Now check the connection.
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
After this, you run your query. Please note that since this is your personal project, therefore I am using SHA1
as the hashing of your password. For a bigger project, I recommend to research further on how to secure your password.
To run the query, first is to prepare it. This is how you do.
$stmt = $conn->prepare("INSERT INTO feedback (user, password, email) VALUES (?, ?, ?)");
In this, you store the statement in $stmt
variable. The query has INSERT INTO
followed by the table's name. In your case it is feedback
.
After this, you fill in the table's fields to be saved in first bracket. In your case it will be (user, password, email)
followed by VALUES
.
After this you add placeholders for the actual values using (?, ?, ?)
. Please note that the total count of ?
must match the total count of fields in the previous bracket.
Now you have to bind the variables to these ?
. This is done by,
$stmt->bind_param("sss", $user, $password, $email);
Please note that "sss"
are the formats of values passed. Below are the formats.
i - integer
d - double
s - string
b - BLOB
So you need to pass 3 values, therefore you have 3 s
, followed by the variables where you will store the values from HTML form by,
$user = $_POST["user"];
$password = sha1($_POST["password"]); //simplest way to use SHA1 hash.
$email = $_POST["email"];
Now you just need to execute the prepared statement.
$stmt->execute();
That's it!
Below is the full code.
// Define Database Credentials
$servername = "localhost"; //Server Name
$username = "KyleHulse"; //Username to the DB
$password = "(my password)"; //Password to the DB
$dbname = "csdb1082"; //Name of the Database
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO feedback (user, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $user, $password, $email);
$user = $_POST["user"];
$password = sha1($_POST["password"]); //simplest way to use SHA1 hash.
$email = $_POST["email"];
$stmt->execute();
Hope this helps.