Last active
December 28, 2020 02:48
-
-
Save barmgeat/d866c5bbd6d9d684d9030b1557effd23 to your computer and use it in GitHub Desktop.
MySQLi with Prepared Statements.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$servername = "localhost"; | |
$username = "username"; | |
$password = "password"; | |
$dbname = "myDB"; | |
// Create connection | |
$conn = new mysqli($servername, $username, $password, $dbname); | |
// Check connection | |
if ($conn->connect_error) { | |
die("Connection failed: " . $conn->connect_error); | |
} | |
// prepare and bind | |
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); | |
/* This function binds the parameters to the SQL query and tells the database what the parameters are. | |
The "sss" argument lists the types of data that the parameters are. | |
The s character tells mysql that the parameter is a string. | |
The argument may be one of four types: | |
i - integer | |
d - double | |
s - string | |
b - BLOB | |
We must have one of these for each parameter. | |
By telling mysql what type of data to expect, we minimize the risk of SQL injections. */ | |
$stmt->bind_param("sss", $firstname, $lastname, $email); | |
// set parameters and execute | |
$firstname = "John"; | |
$lastname = "Doe"; | |
$email = "[email protected]"; | |
$stmt->execute(); | |
$firstname = "Mary"; | |
$lastname = "Moe"; | |
$email = "[email protected]"; | |
$stmt->execute(); | |
$firstname = "Julie"; | |
$lastname = "Dooley"; | |
$email = "[email protected]"; | |
$stmt->execute(); | |
echo "New records created successfully"; | |
$stmt->close(); | |
$conn->close(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment