dongliao9233
2018-09-08 19:34
浏览 52
已采纳

使用html表单和php [关闭]在mysqli中插入数据

Here is my php code, which is what I have been getting errors with. I'm not sure if i'm not connecting to the database correctly, if there may be an issue with my submit button (which i doubt), or if it's an issue in my syntax. If anyone could help me, I would be grateful.

<?php


$servername = "localhost";
$username = "kaylahblack";
$password = "";
$dbname = "pastalist";

$conn = mysqli_connect('localhost','kaylahblack','', 'pastalist');

if(isset($_POST['submit']))
{
$sauce=$_POST['sauce'];
$meat=$_POST['meat'];
$noodle=$_POST['noodle'];

$sql = "INSERT INTO pastalistt (sauce, meat, noodle)
VALUES ('$sauce', '$meat', '$noodle')";
$result=mysqli_query($sql);


if($result){
echo "Pasta Added!";
}
}

mysqli_close($conn);

?>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doubu1950 2018-09-08 19:43
    已采纳

    Hope this fix works for you. The syntax for mysqli_query is -

    mysqli_query($connectionObject, $query);

    <?php
    
    
        $servername = "localhost";
        $username = "kaylahblack";
        $password = "";
        $dbname = "pastalist";
    
        $conn = mysqli_connect('localhost','kaylahblack','', 'pastalist');
    
        if(isset($_POST['submit']))
        {
        $sauce=$_POST['sauce'];
        $meat=$_POST['meat'];
        $noodle=$_POST['noodle'];
    
        $sql = "INSERT INTO pastalistt (sauce, meat, noodle)
        VALUES ($sauce, $meat, $noodle)";
        $result=mysqli_query($conn, $sql);
    
    
        if($result){
        echo "Pasta Added!";
        }
        }
    
        mysqli_close($conn);
    
        ?>
    
    已采纳该答案
    打赏 评论
  • dourao1968 2018-09-08 19:39

    I think you are missing $conn

    it should be

      $result=mysqli_query($sql, $conn);
    

    or something like

      $result= $conn -> mysqli_query($sql);
    
    打赏 评论
  • dtpa98038 2018-09-08 19:48

    Unfortunately I can not judge on your related php logics, as they were not posted. What is the exact error you have received? I am typically using an object-oriented style, but which is basically the same as yours:

    $conn = new mysqli($server,$user,$password,$db);
        if(mysqli_connect_errno()) {
            //some error message
            die();
        }
    $conn -> query($sqlquery);
    

    EDIT: Venkat D. gave u the correct answer. Indeed, the syntax of mysql_query is different, as you have to provide a mysqli handle.

    打赏 评论

相关推荐 更多相似问题