phpmysqlmysql-select-db

mysql_select_db failure


I am using phpMyAdmin + MySQL.

I created a database and am now trying to make the connection in a PHP script. The curious thing is that connecting to the DB works, so I get the "Connected to MySQL server" message, but I when it comes to selecting the 'petfood' database, the script shows "DIED at selection".

Any idea why? Thanks, and here's my piece of code:

<?php

$user = 'localhost';
$pass = 'password';
$db_name = 'petfood';

$db_conn = new mysqli("localhost", $user, $pass, $db_name) or die("Cannot connect to DB");
echo "Connected to MySQL server";
mysql_select_db($db_name) or die("DIED at selection");
echo "Database Selected";

?>

Solution

  • Spot the difference:

    $db_conn = new mysqli("localhost", $user, $pass, $db_name) or die("Cannot connect to DB");
                        ^----
    
    mysql_select_db($db_name) or die("DIED at selection");
         ^---
    

    If you had proper debugging, you'd have been told about the problem:

    mysql_select_db($db_name) or die(mysql_error());
                                     ^^^^^^^^^^^^^^
    

    Never output a fixed (useless) error message when you can have the system TELL you what's wrong.