user10480642
user10480642

Reputation:

MySQL Error - MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?)'

I am a CS freshman and I am currently learning PHP/MySQL on my own. I was able to send a contact form to the mySQL db via PHP. Now I am using mysqli prepared statements to protect my code against mySQL injections but I am having trouble. I created a new file called contact_check.php.

The error I am getting is:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?)' at line 2. Do you know what is the error? 

contactform.php

<?php 

require("../config/db.php");
require("contact_check.php");


$link = mysqli_connect("localhost","root","","benoit");

if(isset($_POST["submit"])){
    $name = $_POST["name"];
    $company = $_POST["company"];
    $emailFrom = $_POST["email"];
    $phone = $_POST["phone"];
    $message = htmlspecialchars($_POST["message"]);

    $mailTo = "[email protected]";
    $headers = "From:".$emailFrom;
    $txt = "You have received an email from ".$name.".\n\n\n".$message;

    mysqli_query($link,"INSERT INTO contact (`name`, `email`, `company`, `phone`, `message`)
    VALUES (?, ?, ?, ?, ?)") or die(mysqli_error($link));

    $stmt = mysqli_stmt_init($conn);

    if(!mysqli_stmt_prepare($stmt, $sql)){
        echo "SQL error";
    } else{
        mysqli_stmt_bind_param($stmt, "sssss", $name, $company, $emailFrom, $phone, $message);
        mysqli_stmt_execute($stmt);
    }


    mail($mailTo, $name, $txt, $headers);

    header("Location: contact.php?mailsend");
}

?>

contact_check.php

<?php

    $data = "Admin";

    //Template 
    $sql = "SELECT * FROM contact where name=?;";

    //Prepared statement

    $stmt = mysqli_stmt_init($conn);

    if(mysqli_stmt_prepare($stmt, $sql)){
        echo "error";
    } else{
        mysqli_stmt_bind_param($stmt, "s", $data);

        //run parameters inside database
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        while($row = mysqli_fetch_assoc($result)){
            echo $row["user_uid"] .  "<br>";
        }
    }

?>

db.php

<?php

$dbServerName = "localhost";
$dbUserName = "root";
$dbPassword = "";
$dbName = "benoit";

$conn = mysqli_connect($dbServerName, $dbUserName, $dbPassword, $dbName);

if(mysqli_connect_error()){
    echo"failed to connect to MYSQL" . mysqli_connect_error();
}

?>

Upvotes: 0

Views: 1743

Answers (1)

Joel Wembo
Joel Wembo

Reputation: 870

BTW you are not escaping your user input which could lead to syntax errors and SQL injections. Use Prepared Statements. Also check your column name as sad above it might be that you referenced one wrong.

Upvotes: 1

Related Questions