-1

I'm having problems with inserting my form data into the database. Help!!

if($_SERVER["REQUEST_METHOD"] == "POST" ){
    if(!empty($_POST)){

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "data";

        $conn = new mysqli($servername, $username, $password, $dbname);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

        $sql = "INSERT INTO cases (name, email, case, phone, address) VALUES ('{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}',
        '{$conn->real_escape_string($_POST['message'])}', '{$conn->real_escape_string($_POST['phone'])}', '{$conn->real_escape_string($_POST['address'])}')";
        $insert = $conn->query($sql);

        $conn -> close();
    });
aynber
  • 22,380
  • 8
  • 50
  • 63
GetRekt
  • 23
  • 1
  • 2
  • 6
  • 1
    What exactly is the problem? Are you getting an error? The wrong data? – Mureinik Jul 05 '19 at 18:52
  • 2
    You cannot use functions within a string like that, even with the braces. You need to break out of the string completely and use concatenation. But I'd recommend dropping that completely and instead use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php) to prevent both SQL injection and pesky quoting/concatenation issues like this one. – aynber Jul 05 '19 at 19:06
  • You also have a syntax error with `});` It should be `}}` – aynber Jul 05 '19 at 19:07
  • 1
    Possible duplicate of [PHP parse/syntax errors; and how to solve them?](https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them) – aynber Jul 05 '19 at 19:07
  • 1
    By the way, phpmyadmin is not a database. It's an interface package to access the database, and has nothing to do with your code here. – aynber Jul 05 '19 at 19:08

1 Answers1

1

Case is a MySQL reserved word. You have to enclose it in back ticks `. Changed to prepared statement.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try{
    $db = mysqli_connect($host, $user, $pass, $db);
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}
$sql = '
INSERT INTO cases
 (name, email, `case`, phone, address) 
VALUES
  (?,?,?,?,?)
';
try{
    $stmt = $db->prepare($sql);
    $stmt->bind_param('sssss',$_POST['name'],$_POST['email'],$_POST['message'],$_POST['phone'],$_POST['address']);
    $stmt->execute();
} catch(Exception $e) {
    var_dump($e);
}
Jason K
  • 1,406
  • 1
  • 12
  • 15
  • If you enabled MySQLi errors then why do you catch them? This is just making your code bloated unnecessarily. – Dharman Jul 05 '19 at 20:45