0
votes

Using the following to connect to a MySQL server while using Xampp.

<?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';

$mysql_db = 'a_database';

if(mysqli_connect('$mysql_host','$mysql_user','$mysql_pass') || !mysqli_select_db($mysql_db)) {
    die ('could not connect');
}

?>

But I received the following errors:

Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\php\connect.inc.php on line 8

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\php\connect.inc.php on line 8

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\php\connect.inc.php on line 8 could not connect

How can I fix this problem?

2

2 Answers

1
votes

You didn't specify the db connection in mysqli_select_db

Try this instead!

$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';

$mysql_db = 'a_database';

$db = mysqli_connect($mysql_host, $mysql_user, $mysql_pass);

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

// you select db with the mysql connection variable
mysqli_select_db($db, $mysql_db);
4
votes

Single quotes do not interpolate, they send in literal text, including the $, which is not what you want.

You shouldn't be enquoting these values anyway, just put them in as-is:

$db = mysqli_connect($mysql_host, $mysql_user, $mysql_pass)

It's a very common anti-pattern to see things like "$x" in PHP code, something that presumably bubbles over from shell scripting where it can be necessary. In PHP it isn't, and often causes trouble as it has here.

Don't forget to save your database connection into a variable or it'll be thrown out before you can use it.

Another thing to note is that the object-oriented interface to mysqli is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete mysql_query interface. Before you get too invested in the procedural style it’s worth switching over. Example: $db = new mysqli(…) and $db->prepare("…") The procedural interface is an artifact from the PHP 4 era when mysqli API was introduced and ideally should not be used in new code.

The proper way to use mysqli is:

$db = new mysqli($mysql_host, $mysql_user, $mysql_pass)

Where that operates exactly the same except that it's far more minimal, like as in:

$stmt = $db->prepare("...");

Instead of the far more verbose:

$stmt = mysqli_prepare($db, "...")

Where that gets even more verbose for statement manipulation functions.