PHP与数据库的连接错误 [英] PHP connection error with the database
问题描述
我只有一个数据库,为什么要输入2个参数?
I only have a database and why is it asking for 2 parameters?
警告:mysqli_select_db()恰好需要2个参数,第5行的C:\ xampp \ htdocs \ video_upload \ connect.php中给出1个参数
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
?>
推荐答案
mysqli_select_db
函数,当使用过程API时,要求您将实际连接作为第一个参数
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 =======================|
这意味着您必须编写:
$db = mysqli_connect('localhost', 'root', '');
mysqli_select_db($db, 'video_system');
就像手册&&签名显示,此mysqli_select_db
返回布尔值. true
表示已成功选择数据库,false
表示失败.最好养成检查函数返回值的习惯.不管看起来多么琐碎.所以:
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
但是您可以通过将选择的数据库名称从关闭处传递给mysqli_connect
函数来轻松省略第二个函数调用:
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');
这可以为您节省额外的函数调用开销,从而略微提高了性能.我还已将localhost
字符串更改为IP地址127.0.0.1,这也有帮助,因为使用IP意味着无需将该字符串解析为相应的IP地址.
总而言之,我认为最好花一些时间阅读文档
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
这篇关于PHP与数据库的连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!