Lupus
Lupus

Reputation: 1518

Mysqli connection give an error Access denied for user ''@'localhost' to database 'mydb'

I'm trying to write a mysql class...

enter code here
class ASQL
{

public $baglanti;


   public function __construct()
{
    $host = "localhost";
    $user = "root";
    $password = "";
    $db = "mydb";



    $this->baglanti = new mysqli($host, $user, $password)
            or die('Could not connect to the database server' . mysqli_connect_error());

    $this->baglanti -> connect();

    if(!$this->baglanti -> select_db($db)){
        echo "Check the DB name!";
        echo "<br>";
        $this->baglanti->error;
        echo "<br>";
    }

}

public function Q( $query )
{
    if ($stmt = $this -> baglanti -> prepare($query))
    {
        $stmt -> execute();
        $result = $stmt -> get_result();
        while ($myrow = $result -> fetch_assoc())
        {
            var_dump($myrow);
        }
    }
    else
    {
        var_dump($this -> baglanti);
    }





}

public function __destruct()
{
    $this -> baglanti -> close();
}



}

$vt = new ASQL;
$vt -> Q("SELECT * FROM mytable");
?>

this code gives me an error

Access denied for user ''@'localhost' to database 'mydb'

I tried to remove the select_db() part and added the database name to the __construct but I got a diffrent error that:

No database selected

I tried a procedural connection with this account and it works fine.

By the way as you can see the first error tells that i'm tring to connect with a blank user name...

Am I missing something?

Upvotes: 0

Views: 4289

Answers (1)

Daniel Freudenberger
Daniel Freudenberger

Reputation: 352

Remove the line $this->baglanti->connect(); and assuming your database credentials are correct, everything should work fine.

The method mysqli::connect() is not even mentioned in the documentation and has already confused others (a-bug-in-mysqli-connect-method)

Upvotes: 1

Related Questions