0

I can't get this to work, it is not posting data to the database, I am completely new to this and any help is great!

<?php
    $connection = mysql_connect('server', 'user', 'pass') or die(mysql_error());
    mysql_select_db('db') or die(mysql_error());

    $client = $_POST['client'];
    $date = $_POST['date'];
    $amount = $_POST['amount'];

    $sql = "INSERT INTO $sales (client, date, amount) VALUES ('$client', '$date', '$amount')";

    $result = mysql_query($sql, $connection);

    if ($result) {
        echo "Successful";
        echo "<BR>";
        echo "<a href='insert.php'>Back to main page</a>";
    } else {
        echo "ERROR";
    }
?>
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Aurelius
  • 475
  • 2
  • 8
  • 19

2 Answers2

1

What is $sales looks like it should not be variable, assuming it as a tablename, try this

$sql="INSERT INTO sales (client, date, amount) VALUES ('$client', '$date', '$amount')";

Also, date is a reserve word in MYSQl, though it is accepted to use it without back tick operator, it would be good to escape it like this

 $sql="INSERT INTO sales (client, `date`, amount) VALUES ('$client', '$date', '$amount')";
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
  • No, date is not a [reserved word in MYSQL](https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html). From the doc: _MySQL permits some keywords to be used as unquoted identifiers because many people previously used them. Examples are those in the following list: ACTION BIT DATE_ – antoox May 20 '13 at 12:46
  • @antoox you should read my answer properly "Also, date is a reserve word in MYSQl, though it is accepted to use it without back tick operator," – chandresh_cool May 20 '13 at 12:47
  • @chandresh_cool Yes sorry for the noise. It adds, however, a little explanation. – antoox May 20 '13 at 12:48
1

It looks like you have set your table name as a variable, which is fine, but you haven't defined it. Also, i'd highly recommend sanitizing your $_POST variables to prevent SQL injection.

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.

<?php

$mysqli = new mysqli('host', 'user', 'password', 'database');

$client = $_POST['client'];
$date   = $_POST['date'];
$amount = $_POST['amount'];

$sql = "INSERT INTO sales (client, `date`, amount) VALUES ('$client', '$date', '$amount')";
$result = $mysqli -> query($sql);
$num    = $mysqli -> affected_rows;

if($num == 1){
    echo 'Success';
}else{
    echo 'Error: '.$mysqli -> error;
}

Also, date is a reserved word in MySQL so i'd suggest using the back tick operators or maybe change the column name.

Community
  • 1
  • 1
ajtrichards
  • 29,723
  • 13
  • 94
  • 101