Connection to db using php in localhost

青春壹個敷衍的年華 提交于 2019-12-12 03:19:26

问题


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 :)



来源:https://stackoverflow.com/questions/32368572/connection-to-db-using-php-in-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!