我正在尝试创建一个连接到mysql数据库并将数据插入数据库的PHP文件。但是我很难将它连接到数据库。我收到以下错误 (!)注意:未定义的变量:第34行的C:\ wamp \ www \ php_Final_kk.php中的dbname 调用堆栈
(!)注意:未定义的变量:第52行的C:\ wamp \ www \ php_Final_kk.php中的sql
SQLSTATE [HY000] [1045]拒绝访问用户' root' @' localhost' (使用密码:是)
我的用户名和密码对于数据库是正确的,并且所有权限都已被授予,但我似乎无法将其连接到任何帮助都会受到重视并且我在下面包含了我的代码。谢谢!
<?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
答案 0 :(得分:1)
通过mysqli_connect
创建连接时,必须提供4个参数:主机,用户名,密码和数据库名称。你缺少数据库名称。
正确的电话是:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
中对此进行了解释
答案 1 :(得分:0)
您尚未定义数据库名称
dbname=$dbname
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my db name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname );
答案 2 :(得分:0)
在此更正:
您必须提供4个必要参数:主机,用户名,密码和数据库名称。您缺少数据库名称。
$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
是您的代码中缺少的数据库名称。