Reputation: 29
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
}
}
?>
Upvotes: 3
Views: 54
Reputation: 43
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".
Upvotes: 2