3

As I am using PHP to connect to mysql database. I tried to connect to database and similarly I want to insert data into Database whenever I click to login button on my form. But no changes are shown db when I try this code so please any help with it. Thank you..

<?php
        $servername = "localhost"; 
        $username = "root";
        $password = "password";
        $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database

        if(isset($_POST['Log In'])){
            $username=$_POST['username'];
            $query = "Insert into User(username) values('$username')"; //query to insert to db

            if (mysql_query($query)) //checking the query 
            {
                echo"<h3>Inserted Successfully</h3>";   //value inserted to db successfully           
            }       


        }
    ?>
1
  • Just replace mysql_query($query) with $conn->query( $query ) and look at Jack M's answer, because you should be doing more to be safe. Commented Aug 27, 2017 at 4:09

1 Answer 1

2

It appears as though you are making a PDO connection but using mysql_ functions. You should have your code written like this instead.

<?php
        $servername = "localhost"; 
        $username = "root";
        $password = "password";
        $conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database

    if(isset($_POST['Log In'])){
        $username=$_POST['username'];
        $query = "INSERT INTO User(username) VALUES(:username)"; //query to insert to db
        $stmt = $conn->prepare($query);
        $result = $stmt->execute(["username"=>$username]);
        if ($result) //checking the query 
        {
            echo"<h3>Inserted Successfully</h3>";   //value inserted to db successfully           
        } else {
            die("query failed");
        }       


    }
?>

Your original code was susceptible to SQL injection, which is not good. I would also not reccommend using $_POST["Log In"] because it is terrible practice to have spaces in an array key. Try something simpler such as "submit" or just "login".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.