Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...