Skip to content
Advertisement

MySQL error because of syntax in Custom PHP code

I am trying to enter user’s data into a database. I think the commas in the address are causing the error.

<?php 
 $full_name = $_POST["fullname"]; 
 $email = $_POST["email"]; 
 $password = $_POST["password"]; 
 $full_address = $_POST["address"]; 
 $city = $_POST["city"]; 
 $age = $_POST["age"]; 
 $contact_number = $_POST["number"]; 
 $gender = $_POST["gender"]; 
 $education = $_POST["education"]; 

?>

<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Advertisement

Answer

As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:

$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
        VALUES (?,?,?,?,?,?,?,?,?)";

$stmt = mysqli_prepare($conn, $sql);

// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);

if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

For more information refer to the PHP manual on MySQLi prepared statements.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement