Insert into MySQL Table PHP

64,780

Solution 1

try this

you should not use quotes of parameter around POST . and you should use them inside POST

       $sql = "INSERT INTO `current stock` (ItemNumber, Stock)
           VALUES
         ('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";

you should escape your variables before you insert them to mysql like that

  • Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.

Solution 2

You have an extra quote and you need ticks around your table name as it contains a space.

INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";

should be:

INSERT INTO `current stock` (`ItemNumber`, `Stock`)
VALUES
('$_POST[ItemNumber]','$_POST[Stock]')";

FYI, you also wide open to SQL injections

Share:
64,780
Jake Ols
Author by

Jake Ols

Updated on July 14, 2022

Comments

  • Jake Ols
    Jake Ols almost 2 years

    I am having some trouble making a simple form to insert data into a MySQL table. I keep getting this SQL error:

    "Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'stock ('ItemNumber', 'Stock') VALUES ('#4','3'')' at line 1"

    My HTML for the form is:

        <form action="database.php" method="post">
        Item Number: <input type="text" name="ItemNumber">
        Stock: <input type="text" name="Stock">
        <input type="submit">
        </form>
    

    And the PHP is:

        <?php
        $con=mysqli_connect("localhost","root","root","inventory");
        if (mysqli_connect_errno($con))
          {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
         $sql = "INSERT INTO current stock ('ItemNumber', 'Stock')
        VALUES
        ('$_POST[ItemNumber]','$_POST[Stock]'')";
        if (!mysqli_query($con,$sql))
          {
          die('Error: ' . mysqli_error($con));
          }
        echo "1 record added";
        mysqli_close($con);
        ?>
    
  • Meier
    Meier over 8 years
    Please don't give bad examples with SQL-injections, especially to beginners that still have problems with the syntax....
  • Niraj
    Niraj about 7 years
  • gre_gor
    gre_gor about 7 years
    If this is meant as part of your existing answer, add this to your existing answer and add an explanation. Otherwise this isn't really a good answer.