问题
I am trying to create a PHP file that connects to a mysql database and inserts data into the database. However I am having difficulty getting it to connect to the database. I get the following error ( ! ) Notice: Undefined variable: dbname in C:\wamp\www\php_Final_kk.php on line 34 Call Stack
( ! ) Notice: Undefined variable: sql in C:\wamp\www\php_Final_kk.php on line 52
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)
My username and password are correct for the database and all privilges have been granted but I just can not seem to get it to connect any help would be aprreciated and I have included my code below. Thanks!
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$uname = $_POST['uname'];
$password = $_POST['password'];
$SSN = $_POST['ssn'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (fname, lname,email,username,password,SSN) VALUES ('$fname', '$lname', '$email', '$uname', '$password', '$ssn')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
enter code here
回答1:
When you create connection via mysqli_connect
, you must supply 4 arguments: host, username, password and database name. You lack database name.
The right call is:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
It's all explained in the official docs
回答2:
You have not defined a database name
dbname=$dbname
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my db name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname );
回答3:
Correct here :
you must supply 4 necessary arguments: host, username, password and database name. You missing database name.
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'test';
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$dbname
is you database name that is missing in your code.
来源:https://stackoverflow.com/questions/27345532/php-wont-connect-to-mysql