PHP_Ninja PHP_Ninja - 6 months ago 43
PHP Question

PHP PDO SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'events'

When I connect to the database using MySQLi, everything works as it should, but with PDO or with CI database methods, I get this error : SQLSTATE[HY000] [1044] Access denied for user ''@'localhost' to database 'events'.

try {
$link = new PDO("mysql:host=localhost;dbname=events;");
$link->setAttribute(PDO::ATTR_MODE, PDO::ERR_MODE_EXCEPTION);

//create statement;
$statement = $link->prepare($sql);
$statement->bindParam(":username", $login_request["username"]);
$statement->bindParam(":password", $login_request["password"]);
$statement->execute();

$rows = $statement->fetchColumn();

return ($rows == 1) ? true : false;
}
catch(PDOEXCEPTION $e){
echo $e->getMessage();
}

Answer

Try to connect like this. Put it in a separate file connection.php and include it in every page you run queries

try{
$connect = new PDO('mysql:host=localhost;dbname=YOUR_DB_NAME;charset=utf8', 'USERNAME', 'PASSWORD',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
    die('Error connecting to database');
}

then you can run queries in every page like this

$stmt = $connect->prepare("SELECT * FROM table WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();