无法使简单的SQL插入工作 [英] Can't Get Simple SQL Insert to Work

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

问题描述

<?php include_once("database.php");

?>
<?php include_once("header.php");

?>



<?php 
    if ($_POST['submit'] )
    {
        $food_name = $_POST['food_name'];
        $food_calories = $_POST['food_calories'];
        echo $food_name . $food_calories;

        if (!empty($food_name) && !empty($food_calories) ) 
        {
            $query = 'INSERT INTO foods VALUES(0, $food_name, $food_calories)';
            mysqli_query($con, $query) or die(mysqli_error($con));
            echo 'added';   
        } else {echo'fail';}

    } else {echo'fa2oo';}


?>

  <h1> Please Fill out Form Below to Enter a New Food </h1>
  <form action="addfood.php" method="post">
    <p>Name:</p>
    <input type="text" name="food_name"/>
    <p>Calories:</p>
    <input type="text" name="food_calories"/> </br>
    <input type="submit" value="submit" />
  </form>

<?php include_once("footer.php")?>

真的不明白为什么这个简单的插入无法正常工作.表单是自引用的.表单没有回显任何内容,只是在我按下提交"按钮时重置.数据库连接没有错误.

Really don't understand why this simple insert is not working. The form is self-referencing. The form does not echo anything and simply resets when i hit the submit button. database connects with no errors.

推荐答案

您的代码中有一些错误:

You have a few errors in your code:

1.缺少名称属性

您缺少提交按钮的名称属性.所以像这样添加它:

You are missing the name attribute for your submit button. So add it like this:

<input type="submit" name="submit" value="submit" />
                   //^^^^^^^^^^^^^

2. empty()

您必须检查$_POST变量是否为空!否则,您将尝试将未定义的变量分配给另一个变量.因此,将第二个if语句更改为此:

You have to check if the $_POST variables are empty! Otherwise you would try to assign an undefined variable to another variable. So change your second if statement to this:

 if (!empty($_POST['food_name']) && !empty($_POST['food_calories']) ) 
          //^^^^^^^^^^^^^^^^^^^            ^^^^^^^^^^^^^^^^^^^^^^^

然后将赋值放入第二个if语句中.

And also put the assignments inside the second if statement.

$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];

3.引号错误+引号缺失

3. Wrong quotes + missing quotes

您必须使用双引号将查询中的变量解析为变量.另外,由于它们是字符串,因此还必须在其周围加上单引号,因此请将查询更改为:

You have to use double quotes that your variable in the query gets parsed as variables. Also you have to put single quotes around them since they are strings, so change your query to this:

$query = "INSERT INTO foods VALUES(0, '$food_name', '$food_calories')";
       //^                            ^          ^  ^              ^

旁注:

在文件顶部添加 error reporting )以获取有用的错误消息:

Add error reporting at the top of your file(s) to get useful error messages:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

您可能还希望更改为 具有准备好的声明 ,因为它们更安全.

You may also want to change to mysqli with prepared statements since they are, much safer.

这篇关于无法使简单的SQL插入工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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