Search code examples
phpmysqlmysql-connect

Connecting web page to database using PHP gives strange results


I have a Raspberry Pi web server set up at home and I have phpMyAdmin set up to administer databases.

I have created a database to hold bits of information which will be used to place markers on a Google map (multiple users will be adding markers of different types for a role play event).

My problem is that I don't seem to be able to connect to the database. Though I've tried example code from many different sources I get strange results. E.g.

Using this code:

<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if($con)
{
echo "Connection OK";
}
if(!$con)
{
echo "No Connection";
}
?>

I get the following print out on the web page:

Connection OK
"; } if(!$con) { echo "
No Connection
"; } ?>

The localhost I've tried "localhost", a domain name which points to the server, a combination of them both, etc. The fact is I feel like I don't understand the printed results on screen and feel like maybe I have been able to connect but I'm being mislead by the echo statements which don't seem to be logical.

I was under the impression that phpMyAdmin would also be able to generate connection code but I don't seem to be able to find anything of the sort.


Solution

  • Please check this is okay

    $conn = mysqli_connect("localhost", "root", "password", "dbname");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    

    instead of, $con->connect_error use mysqli_connect_errno()