Connection to db using php in localhost

2019-09-09 15:03发布

问题:

Even if I have used LAMPP many times, this time something goes wrong. When I visit the browser(chrome) nothing echos. Here is my code:

index.php

<?php

error_reporting(E_ALL); /*after edit*/
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
    die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);

?>

Do I miss something? The output is nothing. By the way i write my files in

var/www/html/my_pages

and i call it this way: localhost/my_pages. Simple echos are working and php in general is fine. Something goes wrong with my db connection.

回答1:

Use this code

<?php
$link = mysqli_connect('localhost', 'root', 'root', 'db');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
else
{
echo 'Connected successfully';
}
?>


回答2:

Yes probably, because mysqli_connect() method return the object, not Boolean value. You can verify the connection with the following code:

if($link->connect_error) 
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

return false;
}
else{
echo "Connection Successful";
   return $link;
}


回答3:

Why not using PDO.

 $dsn = "mysql:host=localhost;dbname=db";
        try {
        $pdo = new PDO($dsn, "root", "");
        } catch (PDOException $ex) {
            $ex->getMessage();
        }

with PDO you can change anytime you need the Db vendor: http://php.net/manual/en/book.pdo.php



回答4:

<?php
echo phpinfo();
?>

Run this file and get all PHP and apache details. Search for mysqli support in it. If it is supported, you should have something like below.

Also check for your root directory



回答5:

Thanks everyone for the response! I found the problem. Something went wrong and mysqli wasn't enabled in php. That's why i had this error Fatal Error:Call to undefined function mysqli_connect() in /var/www/html/diamond/index.php on line 8 I reinstalled php and problem solved :)