Insert into MySQL Table PHP

后端 未结 5 886
悲&欢浪女
悲&欢浪女 2021-01-13 22:37

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

相关标签:
5条回答
  • 2021-01-13 22:59
    <form action="database.php" method="post">
       Item Number: <input type="text" name="ItemNumber">
       Stock: <input type="text" name="Stock">
       <input type="submit" name="submit">
    </form>`
    
    0 讨论(0)
  • 2021-01-13 23:07

    Please learn to use parameter binding. You are creating code with security vulnerabilities.

    Here's how to do your code in mysqli:

    $sql = "INSERT INTO current stock (ItemNumber, Stock) VALUES (?, ?)";
    
    if (!($stmt = mysqli_prepare($con, $sql))) {
        die('Error: ' . mysqli_error($con));
    }
    
    if (!mysqli_stmt_bind_param($stmt, "ii", $_POST[ItemNumber], $_POST[Stock])) {
        die('Error: ' . mysqli_stmt_error($stmt));
    }
    
    if (!mysqli_stmt_execute($stmt)) {
        die('Error: ' . mysqli_stmt_error($stmt));
    }
    

    It's easier to use bound parameters than to get all confused with quotes-within-quotes.

    0 讨论(0)
  • 2021-01-13 23:08
    ?php
      $conn=new mysqli("localhost","root","","inventory")
      or die("not connected".mysqli_connect_error());
      if(isset($_POST['submit']{
        $ItemNumber=$_POST['ItemNumber'];
        $Stock=$_POST['Stock'];
        $sql="insert into current stock(ItemNumber,Stock) values('$ItemNumber','$Stock')";
        $query=mysqli_query($conn,$sql);
        if($query){
          echo"1 row inserted";
        }else{
          echo mysqli_error($conn);
        }
      }
    ?>
    
    0 讨论(0)
  • 2021-01-13 23:16

    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.
    0 讨论(0)
  • 2021-01-13 23:20

    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

    0 讨论(0)
提交回复
热议问题