本文介绍了如何使用 mysqli 扩展在 PHP 中连接到 MySQL 数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的代码来连接我的服务器数据库:
I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
但是显示无法连接到MySQL",这段代码有什么问题?我第一次在 Web 服务器中尝试它,而我的本地主机运行良好.
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
推荐答案
mysqli_connect("","username" ,"password","databasename");//服务器名不能为NULL
使用 loaclhost 作为服务器名称(在 Loacl 中)
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
或者可以使用 MySQLi Procedural
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
编辑 01
$servername = "localhost";
$username = "root";
$password = "";
这篇关于如何使用 mysqli 扩展在 PHP 中连接到 MySQL 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!