1

I am fairly new to PHP and I was following a simple tutorial on youtube, I followed the youtube video, double and tripple checked to make sure everything I typed was correct and data was still not being inserted.

I searched the internet for hours and I came up with a fix, sort of but I don't think it's the correct way to do it

HTML

<html>
<head>

<title>Insert Form Data In MYSQL Database Using PHP</title>
</head>
<body>

<form action="insert.php" method="post">

    Name : <input type="text" name="username">
            <br/>
    Email : <input type="text" name="email">
            <br/>
    <input type="submit" value="Insert">
</form>
</body>
</html>

PHP

<?php

$con = mysqli_connect('localhost','root','');

if (!$con) {
    echo 'Not Connected To Server';
}

if (!mysqli_select_db($con,'tutorial')) {
    echo 'Database Not Selected';
}

if (isset($_POST['username'])){
    $Name = $_POST['username'];
}

if (isset($_POST['email'])){
    $Email = $_POST['email'];
}

$sql = "INSERT INTO person (Name, Email) VALUES ('John', 'john@gmail.com')";


if (!mysqli_query($con,$sql)) {
    echo 'Not Inserted';
} else {
    echo 'Inserted Successfully!';
}
header("refresh:10; url=index.html");
?>

I replaced '$Name' and '$Email' with John and john@gmail.com, then I type it into the html form and the data goes into the database correctly.

I then found another HTML form online with more PHP but it does the same thing(not inserting any data to the database)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert1.php" method="post">
    <p>
        <label for="firstName">First Name:</label>
        <input type="text" name="firstname" id="firstName">
    </p>
    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastname" id="lastName">
    </p>
    <p>
        <label for="emailAddress">Email Address:</label>
        <input type="text" name="email" id="emailAddress">
    </p>
    <input type="submit" value="Submit">
</form>
</body>
</html>

PHP

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);

// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
?>

The fields are blank, any help will be greatly appreacited!

Btw This is how the fields display I'm using xampp server.

enter image description here

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Quite a good way to test as you go is to echo the varibles to check your progress. For example, echo $first_name . " " . $last_name . " " . $email_address; after they are declared, and echo $sql; after it is created. Do you get what you expect? – RGriffiths Sep 02 '16 at 13:53
  • So what messages do you get from either of these bits of code – RiggsFolly Sep 02 '16 at 13:55
  • I note they are both connecting to different databases. Do you have a database called `tutorial` and/or one called `demo` – RiggsFolly Sep 02 '16 at 13:56
  • Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` to the top of your script. This will force any `mysqli_` errors to generate an Exception that you cannot miss or ignore. – RiggsFolly Sep 02 '16 at 13:56
  • Notice: Undefined index: firstname in C:\xampp\htdocs\search\insert1.php on line 12 Notice: Undefined index: lastname in C:\xampp\htdocs\search\insert1.php on line 13 Notice: Undefined index: email in C:\xampp\htdocs\search\insert1.php on line 14 Records added successfully. edit, and yes I am testing 2 different databases. –  Sep 02 '16 at 13:58
  • That would have been useful information to put in your original questions, now wouldn't it! – RiggsFolly Sep 02 '16 at 13:59
  • Your first example does not have `name="something"` attributes on the HTML input fields so NOTHING will be passed to the PHP script. – RiggsFolly Sep 02 '16 at 14:02
  • I am afraid I have to mention this: Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Sep 02 '16 at 14:06
  • Well I followed this tutorial and his data inserted but mine didn't https://www.youtube.com/watch?v=0BoZc5oUioA –  Sep 02 '16 at 14:16

1 Answers1

1

I had used the below code and it works fine for me.

  <?php

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

      // Check connection
     if($link === false){
     die("ERROR: Could not connect. " . mysqli_connect_error());
     }

 /* Collect below values from $_POST
 $firstname = 'John';
 $lastname = 'Doe';
 $email = 'test@gmail.com';
 */
   // Escape user inputs for security
  $first_name = mysqli_real_escape_string($link, $firstname);
  $last_name = mysqli_real_escape_string($link, $lastname);
  $email_address = mysqli_real_escape_string($link, $email);

  // attempt insert query execution
     $sql = "INSERT INTO accounts (account_firstname, account_lastname, account_email) VALUES ('$first_name', '$last_name', '$email_address')";
   if(mysqli_query($link, $sql)){
       echo "Records added successfully.";
     } else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
   }

    // close connection
     mysqli_close($link);
     ?>
Bhushan
  • 46
  • 4
  • Accounts table I had used for demo, please use your table name and column names. – Bhushan Sep 02 '16 at 14:07
  • Still blank.. Notice: Undefined variable: firstname in C:\xampp\htdocs\search\insert1.php on line 16 Notice: Undefined variable: lastname in C:\xampp\htdocs\search\insert1.php on line 17 Notice: Undefined variable: email in C:\xampp\htdocs\search\insert1.php on line 18 Records added successfully. –  Sep 02 '16 at 14:15
  • Nevermind I got it to work now, but with every name I then have to type the name and emails into the php code first, then submit via the html form, I thought there would be a simple way to use the html form only to insert the data to the database, but thanks. –  Sep 02 '16 at 14:22
  • 1
    So I figured out my .HTACCESS file was what's causing the blank fields in the tables in the DB, I had used it to remove .php extensions from files, but after removing the htaccess file from my web directory the forms work as they should, just had to post this in case it helps anyone else in the future. –  Nov 07 '16 at 19:00