简体   繁体   中英

Can't connect to localhost MySQL server with PHP

I have Apache (with PHP) and MySQL installed and running on my Raspberry Pi. I've done some simple tests with PHP, and it seems to be working. And MySQL is working perfectly from the terminal, and even another computer.

I made this PHP file:

<?php

echo("Connecting");

$connection = new mysqli("127.0.0.1", "admin", "password", "test");

if ($connection->connect_error) {
    die("Connection error");
}

echo("Connection successful");

?>

Yet when I go to this page in my web browser, all I see is "Connecting". If I comment out the connection command, I see "Connecting Connection successful" in the browser.

It seems as if the PHP code stops running or hangs at the connection command.

Any ideas why I'm having this strange behavior?

Try adding these lines at the top: error_reporting(E_ALL); ini_set('display_errors',1);

I hope You should do following

if ($connection->connect_error) {
    echo "Connection error";
}else{
    echo "Connection successful";
}

Try this instead

<?php
   $link = mysqli_connect("127.0.0.1", "admin", "password", "test");

    if (!$link) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

    echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
    echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

   mysqli_close($link);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM