插入MySQL Table PHP [英] Insert into MySQL Table PHP

查看:42
本文介绍了插入MySQL Table PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作一个简单的表单以将数据插入MySQL表时遇到了一些麻烦.我不断收到此SQL错误:

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

错误:您的SQL语法有错误;请查看手册 对应于您的MySQL服务器版本以使用正确的语法 在第1行的'stock('ItemNumber','Stock')VALUES('#4','3'')'附近

"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"

我的表单的 HTML 是:

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

PHP 是:

    <?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);
    ?>

推荐答案

尝试一下

您不应在POST前后使用参数引号.您应该在POST中使用它们

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']."' )";

在将变量插入到mysql之类的变量之前,应该先对其进行转义

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

  • 请注意,该示例未调用mysqli_real_escape_string.如果直接将字符串嵌入查询中,则只需要使用mysqli_real_escape_string,但是我建议您不要这样做.始终尽可能使用参数.
  • 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.

这篇关于插入MySQL Table PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆