-1

Can anyone tell me what is the problem with this line of PHP code? I am trying to insert values in a database.

<?php

// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
$con;



 mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");

 // Making connection
$con = mysqli_connect($host, $username, $password, $database) or die(mysqli_error());


?>

THE ERROR:

Notice: Undefined variable: con in C:\xampp\htdocs\database.php on line 13

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\database.php on line 13

6
  • 2
    I see the problem. You're storing passwords in plain text instead of hashing them.
    – Mike
    Mar 14, 2014 at 4:32
  • 1
    put query query below connection Mar 14, 2014 at 4:34
  • @user41510 Where you are putting the $con??
    – Jenz
    Mar 14, 2014 at 4:37
  • most databases don't allow a blank password, especially for root. Mar 14, 2014 at 4:38
  • use connection before insert query..what is the error that you are getting
    – codelover
    Mar 14, 2014 at 4:39

4 Answers 4

0

Use Following code:

You just need to connect to database before INSERT .

<?php

// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';

$con = mysqli_connect($host,$username,$password,$database) or die("Error " . mysqli_error($con));



 mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");


?>
0

You are trying to insert a query into the database before making a connection to it. Swith lines 13 and 11.

0

Check this ..This will help you

$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';

$con = mysqli_connect($host, $username, $password) or die(mysqli_error());
$db_selected = mysqli_select_db("mywebsite", $con);

$check= mysqli_query("INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");

if($check)
 echo "inserted";
else
 echo "not inserted";
0

webserver reads PHP code line by line from the top of the page.

it displays Undefined variable error on the variable because you use it before you define $con. so when the webserver reach line 13, it doesn't know what is variable $con and then it throws the error.

My suggestion is the same with the others. put the

$con = mysqli_connect($host, $username, $password, $database) or die(mysqli_error());

above this

mysqli_query($con,"INSERT INTO members (Name, Password) VALUES ('Daniel', 'abc123')");

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.