student_details
VALUES(?, ?, ?)<!DOCTYPE html>
<html>
<head>
<title>MySQL Prepared Statement</title>
</head>
<body>
<?php
// Create connection
$conn = new mysqli("localhost", "root", "", "ftl_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO student_details_2 (stu_name, college, email, mobile) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $stu_name, $college, $email, $mobile);
// set parameters and execute
$stu_name = "Raja";
$college = "Venkateswara";
$email = "sample@example.com";
$mobile = "9966463846";
$stmt->execute();
echo "New record has successfully created..! ";
// Close statement
$stmt->close();
// Close statement
$conn->close();
?>
</body>
</html>
INSERT INTO student_details_2 (stu_name, college, email, mobile) VALUES (?, ?, ?);
In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or blob value.
Then, have a look at the bind_param()
function:
$stmt->bind_param("sss", $firstname, $lastname, $email);
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 :
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.