Php connect using pdo

I am newbie in php

I get this error message kindly help.

my connect.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "user_login";

try {
	//creating connection to mysql
    $dbh = new PDO("mysql: host=$localhost;dbname=user_login", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    exit;
    }
?>

Could you post your connect.php where the error is happening?

My connect.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "user_login";

try {
	//creating connection to mysql
    $dbh = new PDO("mysql: host=$localhost;dbname=user_login", $username, $password);
    // set the PDO error mode to exception
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    exit;
    }
?>

There is no variable $localhost defined in your script. There is however a variable $servername.

1 Like

Thanks bro…It worked changed the variable $servername to $localhost and it worked!! Much thanks!!!

If would have changed $localhost to $servername as that makes more sense, but yeah, the other way around works too :slight_smile:

1 Like

Sure it does…Thanks for the help!:smiley:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.