Monday 3 September 2018

Mysqli does not include any data

I just changed from mysql to mysqli, and now it won't insert any data (it inserts empty fields)

It worked fine before I changed the connection to mysqli.
Any idea why it does that?
<?php

$mysqli = new mysqli("localhost", "root", "", "opdracht");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

    if($_POST['action'] == 'button'){ // als de knop is ingedrukt insert dan
    if(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) && preg_match('#\.[a-z]{2,6}$#i', $_POST['email'])){

        $voornaam  = mysqli_real_escape_string($_POST['voornaam']);
        $achternaam = mysqli_real_escape_string($_POST['achternaam']);
        $email  = mysqli_real_escape_string($_POST['email']);
        $telefoonnummer = mysqli_real_escape_string($_POST['telefoonnummer']);

        $query = mysqli_query($mysqli,"insert into
           `form` (`id`,`voornaam`, `achternaam`, `email`, `telefoonnummer`)
            values ('','".$voornaam."', '".$achternaam."', '".$email."', '".$telefoonnummer."')")
            or die(mysqli_error($mysqli));

        $subject = 'Een email van '.$voornaam.'';
        $headers  = 'MIME-Version: 1.0' ."\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";
        // opmaak mail
        $content = '<html><header><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </header><img src="http://www.tekstbureaudevulpen.nl/wp-content/uploads/2010/11/Webparking_logo.png"/><body>';
        $content .= '<p>Je hebt een mail van:</p>';
        $content .= $voornaam;
        $content .= ' ';
        $content .= $achternaam;
        $content .= '<p>'.$telefoonnummer.'</p>';
        $content .= '</body></html>';

        mail($email, $subject, $content, $headers); // Verstuurd de mail
        error_log(E_ALL);
 }
    }
?>


Because now string escaping also requires the connection handle. All of the following need to be updated
    $voornaam  = mysqli_real_escape_string($_POST['voornaam']);
    $achternaam = mysqli_real_escape_string($_POST['achternaam']);
    $email  = mysqli_real_escape_string($_POST['email']);
    $telefoonnummer = mysqli_real_escape_string($_POST['telefoonnummer']);

to this format
    $voornaam  = mysqli_real_escape_string($mysqli,$_POST['voornaam']);
                                           ^

But you shouldn't still be playing with string escaping for queries even after moving to a new API, why not use prepared statements? Much safer and they come with a lot more benefits.

0 comments:

Post a Comment