user3537990
user3537990

Reputation:

Data not inserting into database

So I have my form that sends data to my php file that then enters it into the database. Here's the php backend part

<?php
 $db = new mysqli('localhost','root','x','app');
 $username = $_POST['username'];

 $db->query("INSERT INTO people (first_name) VALUES ('{$username}'");

?>

But my question is, why isn't username being put into the database?

Upvotes: 1

Views: 117

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

You are missing a bracket ) in the following line:

("INSERT INTO people (first_name) VALUES ('{$username}' ")
                                                       ^ // <= right there

change it to:

("INSERT INTO people (first_name) VALUES ('{$username}')")

Yet, as pointed out in comments, you are open to SQL injection when using your present method.


Here follows an example of a prepared statement:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = @mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');

if (!$mysqli) {
    die('Connect Error: ' . mysqli_connect_error());
}

// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);

   $sql = ("INSERT INTO people (first_name) VALUES (?)");

    $stmt = $mysqli->prepare($sql) or die("Failed Execution");
    $stmt->bind_param('s', $username);

    $stmt->execute();
    echo $stmt->error;

echo "SUCCESS";

    exit();

Plus, using error reporting is important before going live.


Should you want to get into learning PDO,

Here are a few tutorials for you to look into:


Here is a PDO example:

<?php

    $mysql_hostname = 'xxx';
    $mysql_username = 'xxx';
    $mysql_password = 'xxx';
    $mysql_dbname = 'xxx';

    try{

    $db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 

$email = $_POST['email'];
$username = $_POST['username'];

$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`) 

 VALUES (:email, :username)");

$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);

$result_set->execute(array(':email' => $email, ':username' => $username));

    echo "Data successfully written.";

        return $db;
    }catch(PDOException $e){
        echo $e;
        return false;
    }

?>

PDO error handling links:

Upvotes: 5

Related Questions