PHP form not inserting into mySQL database

56,904

Solution 1

Others have already given you answers. To add, you are using quotes around column names which should be backticks or remove the quotes altogether.

Change:

INSERT INTO orders ('name', 'tacoOrder')
                    ^    ^  ^         ^

to

INSERT INTO orders (`name`, `tacoOrder`)

or

INSERT INTO orders (name, tacoOrder)

or as a complete answer:

$name = $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];

$query = "INSERT INTO orders (`name`, `tacoOrder`) VALUES ('$name', '$tacoOrder')";

Sidenote: Backticks are not required but the single quotes for the column names cannot be used. It's just a force of habit that I myself use backticks around column names.

Plus, this $mysql_close(); should not have a $ in front of mysql_close but $link inside the brackets:

Change to mysql_close($link);

Yet as noted by Mr. Alien, the variable for mysql_close() is optional (Thanks for that)

You also have a missing ) in if(!mysql_query($query) which should read as if(!mysql_query($query))

Do consider switching to mysqli_* functions with prepared statements or PDO. The mysql_* functions are deprecated and will be deleted from future releases.


complete rewrite: (tested and working on my server)

<?php

define('DB_NAME', 'tacoPractice');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);

if(!$link)
{
    die('Could not connect to database: ' . mysql_error());
}

$db_select = mysql_select_db(DB_NAME);

if(!$db_select)
{
    die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}

echo "HOLY EFF";
$name = $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];

$query = "INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')";
if(!mysql_query($query))
{
    die("DAMMIT");
}
else{ echo "Success"; }

mysql_close();

?>

You could also use this method which is slightly different:

$query = mysql_query("INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')");
if (!$query) {
    die('Invalid query: ' . mysql_error());
}
else{ echo "Success"; }

Footnotes:

You risk in getting empty data entries because you are not checking if your form elements are left empty.

You could use a conditional statement to the effect of:

if(!empty($_POST['name']) || !empty($_POST['tacoOrder']))
{
// continue with code processing
}

Plus, use what Awlad mentions in his answer in regards to using mysql_real_escape_string()

You can also read a good article here on SO How can I prevent SQL injection in PHP?


Here is a (basic) mysqli_* based method with the mysqli_real_escape_string() function and a conditional statement to check if any of the fields are empty.

If one of the fields is left empty, the query won't execute.

<?php
define('DB_NAME', 'tacoPractice');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_HOST', 'localhost');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);

if(!$link)
{
    die('Could not connect to database: ' . mysqli_error());
}

$db_select = mysqli_select_db($link,DB_NAME);

if(!$db_select)
{
    die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
}

echo "HOLY EFF";
$name = mysqli_real_escape_string($link,$_POST['name']);
$tacoOrder = mysqli_real_escape_string($link,$_POST['tacoOrder']);


if(!empty($_POST['name']) || !empty($_POST['tacoOrder'])){
$query = "INSERT INTO orders (name, tacoOrder) VALUES ('$name', '$tacoOrder')";
if(!mysqli_query($link,$query))
{
    die("DAMMIT");
}
else{ echo "Success"; }

mysqli_close($link);

}

?>

Solution 2

Basic PHP: $_POST is an ARRAY. It's not a function:

$name = $_POST('name');
              ^------^--- should be []

Solution 3

No need of '{}' and $_POST('name')

$name =      $_POST['name'];
$tacoOrder = $_POST['tacoOrder'];
$query = "INSERT INTO orders ('name', 'tacoOrder') VALUES ('$name','$tacoOrder')";

Solution 4

hi @user2839411 even I faced the same problem,where values was not geting inserted into the mysql database,so tried seaching in many related websites but finally w3schools helped me out to achive the result. here is the bellow code thta inserts the value into the database.

PHP CODE:

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "dbitb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if(isset($_POST['btn-signup']))
{
 $name = ($_POST['name']);
 $address = ($_POST['address']);
 $email = ($_POST['email']);
 $mobile = ($_POST['mobile']);
 $highest_degree = ($_POST['highest_degree']);
 $relavant_exp = ($_POST['relavant_exp']);

$sql = "INSERT INTO dbitb.volunteer_reg (name,address,email,mobile,highest_degree,relavant_exp)
VALUES ('$name','$address','$email','$mobile','$highest_degree','$relavant_exp')";

if ($conn->query($sql) === TRUE) 
{
    echo "New record created successfully";
} 
else 
{
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

HTML CODE:

<form method="post" action ="register.php" id="contact-form">

<input type="text" name="name" placeholder="name"  required />

<textarea id = "address" name="address" placeholder="address"  required /></textarea>


<input type="email" name="email"  placeholder="email" required />


<input type="mobile" name="mobile"  placeholder="mobile" required />


<input type="highest_degree" name="highest_degree"  placeholder="highest degree" required />

<textarea id = "relavant_exp" name="relavant_exp"  placeholder="relavant experience" required /></textarea>

<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="btn-signup" value="Enter the box" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
 <a href="index.html"><button type="button" class="btn btn-default" style="margin-top: 15px;">&laquo; Back</button></a>
  </div>

</form>
Share:
56,904
privatestaticint
Author by

privatestaticint

FOR WORK: I develop custom applications for Android and Roku platforms. FOR FUN: I want to get better at web, so I'm developing a personal website!

Updated on July 09, 2022

Comments

  • privatestaticint
    privatestaticint almost 2 years

    I am trying to pull two text fields from a form down into a basic mySQL DB and it is giving me trouble. So here are my two files, HTML form first:

    <!DOCTYPE html>
    
    <html>
      <body>
        <title>Home Page</title>
        <h3>Please Place your Order Below:</h3>
        <form action="tacoOrder.php" method="POST" />
            <p>Name: <input type="text" name="name" /></p>
            <p>Taco Order: <input type="text" name="tacoOrder" /></p>
            <input type="submit" value="Submit" />
        </form>
      </body>
    </html>
    

    and PHP:

    <?php
    
    define('DB_NAME', 'tacoPractice');
    define('DB_USER', 'root');
    define('DB_PASS', 'root');
    define('DB_HOST', 'localhost');
    
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    
    if(!$link)
    {
        die('Could not connect to database: ' . mysql_error());
    }
    
    $db_select = mysql_select_db(DB_NAME);
    
    if(!$db_select)
    {
        die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
    }
    
    echo "HOLY EFF";
    $name = $_POST('name');
    $tacoOrder = $_POST('tacoOrder');
    
    $query = "INSERT INTO orders ('name', 'tacoOrder') VALUES ('{$name}', '{$tacoOrder}')";
    if(!mysql_query($query)
    {
        die("DAMMIT");
    }
    
    $mysql_close();
    
    ?>
    

    It doesn't give a connection error, but no data is inserted into my DB. Any ideas?

    Thanks.

  • Mr. Alien
    Mr. Alien about 10 years
    Copying answers is bad habit :)
  • user3064914
    user3064914 about 10 years
    i didnt copy i gave the answer first mr.Alien
  • Mr. Alien
    Mr. Alien about 10 years
    You edited your answer after reading my and marcs answer, you just answered not to use curly braces, I have eyes everywhere
  • user3064914
    user3064914 about 10 years
    I didnt see your answer i saw the code and edited it.
  • Mr. Alien
    Mr. Alien about 10 years
    None of them are sql reserved keywords, so you wont need backticks, also, variable is optional for mysql_close () in1.php.net/mysql_close and aaaah I didn't saw the quotes around the table names, would delete mine and upvote yours, but you can remove unnecessary part of your answer
  • Funk Forty Niner
    Funk Forty Niner about 10 years
    I am talking about the column names, not reserved words. They cannot be wrapped in quotes but backticks. @Mr.Alien The VALUES yes but not the column names.
  • Mr. Alien
    Mr. Alien about 10 years
    Yup but backticks aren't required here, they are used if we use mysql reserved keywords as column names
  • Funk Forty Niner
    Funk Forty Niner about 10 years
    You mean about the $link inside mysql_close? @Mr.Alien
  • Funk Forty Niner
    Funk Forty Niner about 10 years
    Yes I agree on the backticks, but I tend to think that it's safer using them. But you are right, the backticks are not required, but the quotes cannot be used. @Mr.Alien It's just a force of habit that I have.
  • Mr. Alien
    Mr. Alien about 10 years
    Ya right. ?. And still your answer is wrong anyways, table names do not have quotes, didn't saw that coming?
  • Mr. Alien
    Mr. Alien about 10 years
    No, infact its a bad practice, you use it, so you make your code lose, if you use reserved keywords, they will cause you issue some or the other day, better not use reserved ones, and so no need of backticks, and yes, you do not need to have argument for mysql_close(), its optional
  • Funk Forty Niner
    Funk Forty Niner about 10 years
    I've made an edit to reflect those, thanks @Mr.Alien