PHP connection error with the database [closed]

2019-03-07 06:36发布

问题:

I only have a database and why is it asking for 2 parameters?

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\video_upload\connect.php on line 5

<?php    
   mysqli_connect('localhost', 'root', ''); //connecting to the database    
   mysqli_select_db('video_system');   //chosing a database 
?>

回答1:

the mysqli_select_db function, when using the procedural API requires you to pass an actual connection as a first parameter, as shown on the man pages. This connection, or link, is what mysqli_connect returns, so you shouldn't ignore what mysqli_connect returns, but rather assign it to a variable.
The function's signature clearly tells you all of this, so please, RTM. Here's a few copy-pasted exerts:

                            \/=============================|
bool mysqli_select_db ( mysqli $link , string $dbname )   ||
//returns bool         argument 1       argument 2        ||
mysqli mysqli_connect ([...])                             ||
//returns type mysqli  accepts vast number of arguments   ||
              //                                          ||
              |======== useful here =======================|

This means you'll have to write:

$db = mysqli_connect('localhost', 'root', '');
mysqli_select_db($db, 'video_system');

Like the manual && signature show, this mysqli_select_db returns a bool. true means the DB was successfully selected, false indicates failure. It's best to get into the habit of checking function return values. No matter how trivial it may seem. So:

$db = mysqli_connect('localhost', 'root', '');
if (!mysqli_select_db($db, 'video_system'))
{//if return value is false, echo error message and exit script
    echo 'Failed to select db "video_system": ', mysqli_error($db), PHP_EOL;
    $db = null;//optional, but generally safer
    exit(1);//stop execution
}
//db selected, get to work here

But you can easily omit this second function call, by passing the DB name of choice to the mysqli_connect function from the off:

$db = mysqli_connect('127.0.0.1', 'root', '', 'video_system');

Which saves you the overhead of an additional function call, which slightly improves performance. I've also changed the localhost string to the IP address 127.0.0.1, which can also help, because using the IP means the string needn't be resolved to the corresponding IP address.
All in all, I think it best you spend some time reading the documentation