Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

try this, replace this

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

with this

if (mysqli_connect_errno()) {       
    printf("Connect failed: %s\n", mysqli_connect_error());         
    exit();     
}

This is a strange printout. Try to use

if ($con->connect_error) {
   echo "Failed to connect to MySQL: " . $con->connect_error;
}

or another way

if (!$con) {
    die('Failed to connect to MySQL: ' . mysqli_connect_error());
}

The @mysql_connect code to connect to the database was housed in an html file without Apache being configured to run html files as php files. I am managing to connect to the DB now only only with a .php format file. The final working code was:

$conn = mysqli_connect("localhost", "root", "password", "dbname");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

And it was saved in the web server as databaseConnection.php.

At that point, adding the correct parameters lead to a successful connection and adding incorrect parameters lead to an error message being displayed.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top