Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<?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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

Since you're inserting strings, you need to enclose them by single quotes ('):

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

Note, however, that building an SQL statement by using string manipulation will leave your code vulnerable to SQL inject attacks. You'd probably be better off using a prepared statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...