-2

I want to insert data into the database.but when i click on save button than data did not go in database.i did not understand where i did mistake. This is my php code:

    <?php
$host = "localhost";
$user = "root";
$password ="";
$database = "crud";
$conn = new mysqli($host, $user, $password);
mysql_select_db($database);

if(isset($_POST['btn-save']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city_name = $_POST['city_name'];
$sql_query ="INSERT INTO users(first_name,last_name,user_city) VALUES('$first_name','$last_name','$city_name')";
  mysql_query($sql_query);
}
?>

1 Answers1

1

You are mixing mysqli and mysql methods ~ ignore the now deprecated mysql_* suite of functions and concentrate on mysqli - learn about prepared statements if you wish to prevent sql injection.

Hopefully the following should insert data.

<?php
    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "crud";

    $conn = new mysqli( $host, $user, $password, $database );

    if( isset( $_POST['btn-save'] ) ){
        $first_name = $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $city_name = $_POST['city_name'];

        $sql ="INSERT INTO `users` (`first_name`,`last_name`,`user_city`) VALUES ( '{$first_name}', '{$last_name}', '{$city_name}' )";
        $res=$conn->query( $sql );
        if( $res ){
            /* all good */  
        }
        $conn->close();
    }
?>

I mentioned prepared statements - the following could be used ( hopefully without issue ) in place of the $conn->query() above! The basic idea is that you use a placeholder in the sql statement and then bind variables to those placeholders - believe it or not this method will drastically reduce any chance of sql injection ;/

    $sql  = "INSERT INTO `users` (`first_name`,`last_name`,`user_city`) VALUES ( ?, ?, ? )";

    $stmt = $conn->prepare( $sql );
    $stmt->bind_param('sss',$first_name,$last_name,$city_name);
    $res=$stmt->execute();

    if( $res ){
        /* all good ~ display a message or set a var etc */
        $stmt->close();
    }
    $conn->close();
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46