- Use prepared statements. See reference(s) below.
Here is a script that I use (pulled from one of my libraries) and it works, even with the ampersand (pre-tested) and make sure the column is varchar
.
-mysqli
with prepared statements method
<!doctype html>
<head></head>
<title></title>
<body>
<form action="<?php echo htmlentities($_SERVER["PHP_SELF"]); ?>" method="post">
<p><strong>Name: </strong>
<input name="name" type="text" width="50">
</p>
<p><strong>Email: </strong>
<input name="email" type="text" width="50" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</body>
</html>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
if( isset($_POST['submit'])
&& !empty($_POST['name'])
&& !empty($_POST['email']) ){
/* ===================== not all parts needed, modify to suit ======================= */
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg = '<p class="error">The email address you entered is not valid.</p>';
echo $error_msg;
exit;
}
/* ===================== not really needed, just querying ======================= */
$checkemail = mysqli_real_escape_string($con, $_POST['email']);
$query = "SELECT * FROM yourTable WHERE email = '".$checkemail."'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
if (mysqli_num_rows($result) > 0) {
echo $checkemail . " already exists in DB";
exit;
}
$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql = mysqli_prepare($con, "INSERT INTO yourTable
(id, name, email)
VALUES (null,?,?)");
$sql->bind_param("ss", $name, $email);
$sql->execute();
if($sql){
echo "Success!";
}
}
else{
echo "Fill in all fields.";
}
Reference(s):