在数据库表中使用mysqli插入数据不起作用?连接工作正常

  • It should say new record and then I should be able to see new data in items table

  • connection to database file contains:

        $server="localhost";
        $login="root";
        $pass="";
        $database="floweritem";
    
        $con=mysqli_connect($server,$login,$pass,$database);
        if(mysqli_connect_errno()){
        echo "Failed connect to MYSQL".mysqli_connect_error();
        }
    
  • form action

  • PHP

        <?php
        if(isset($_POST['submit'])){
        $Name=mysqli_real_escape_string($con,$_POST['Name']);
        $Desc=mysqli_real_escape_string($con,$_POST['Desc']);
        $Size=mysqli_real_escape_string($con,$_POST['Size']);
        $Price=mysqli_real_escape_string($con,$_POST['Price']);
    
    
        //no problwm with connection to table or database
        $sql="INSERT INTO `items`(`Name`,`Description`,`Size`,`Price`) 
        VALUES($Name,$Desc,$Size,$Price)";
        echo $Desc;
    
    
        if(mysqli_query($con,$sql)){ 
        echo "new record";
        }
        //always get wrong
        //can't find problem
        else{echo"Wrong";}
        mysqli_close($con);
        }
        ?>
    
  • shows $Desc But Not successful to insert data in items table

You need to add single quotes against values.

Corrected Code:

 //no problwm with connection to table or database
    $sql="INSERT INTO `items`(`Name`,`Description`,`Size`,`Price`) 
    VALUES('$Name','$Desc','$Size','$Price')";
    echo $Desc;

Otherwise, MySQL will consider user entered values as MySQL keywords, hence creating Syntax errors.

New php code should be like this

<?php
    if(isset($_POST['submit'])){
    $Name=mysqli_real_escape_string($con,$_POST['Name']);
    $Desc=mysqli_real_escape_string($con,$_POST['Desc']);
    $Size=mysqli_real_escape_string($con,$_POST['Size']);
    $Price=mysqli_real_escape_string($con,$_POST['Price']);


    //no problwm with connection to table or database
    $sql="INSERT INTO `items`(`Name`,`Description`,`Size`,`Price`) 
    VALUES('$Name','$Desc','$Size','$Price')";
    echo $Desc;


    if(mysqli_query($con,$sql)){ 
    echo "new record";
    }
    //always get wrong
    //can't find problem
    else{echo"Wrong";}
    mysqli_close($con);
    }
    ?>

Try this its working :

PHP :

<?php
    if(isset($_POST['submit'])){
    $Name=mysqli_real_escape_string($con,$_POST['Name']);
    $Desc=mysqli_real_escape_string($con,$_POST['Desc']);
    $Size=mysqli_real_escape_string($con,$_POST['Size']);
    $Price=mysqli_real_escape_string($con,$_POST['Price']);


    //no problwm with connection to table or database
    $sql="INSERT INTO `items`(`Name`,`Description`,`Size`,`Price`) 
    VALUES('$Name','$Desc','$Size','$Price')";
    echo $Desc;


    if(mysqli_query($con,$sql)){ 
    echo "new record";
    }
    //always get wrong
    //can't find problem
    else{echo"Wrong";}
    mysqli_close($con);
    }
    ?>