Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

php wont connect to mysql

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:wampwwwphp_Final_kk.php on line 34 Call Stack

( ! ) Notice: Undefined variable: sql in C:wampwwwphp_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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...