我有这样的代码来连接我的服务器数据库:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
但是却显示“无法连接MySQL”,这段代码有什么问题吗?我第一次在网络服务器中尝试它,而我的本地主机工作得很好。
服务器名称不能为空。如果 MySQL 安装在本地,请使用 localhost
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "test";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
要使用 mysqli 连接到 MySQL 数据库,您需要执行 3 行代码。您需要启用错误报告、创建 mysqli 类的实例并设置正确的字符集。
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
mysqli 构造函数中的参数都是可选的,但大多数时候您希望传递至少 4 个。按照正确的顺序,它们是:
localhost
,但如果您连接到远程主机,它将是其他 IP 地址。确保它不包含 http
协议部分。它应该是 IP 地址或不带协议的 URL。不幸的是,字符集不是这些参数之一,因此您必须使用专用函数来设置这个非常重要的参数。
请注意切勿手动显示连接错误。这样做完全没有必要,而且会泄露您的凭据。
不相关的说明:我不建议在新项目中使用 MySQLi。请考虑使用 PDO,总的来说,这是一个更好的连接 MySQL 的 API。
为什么使用mysqli?只需使用 PDO 即可获得更安全的 mysql 连接,只需使用:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
您应该指定 主机名
$con = mysqli_connect("localhost","username" ,"password","databasename");
如果它返回类似的错误
无法连接到MySQL:无法通过套接字'/var/lib/mysql/mysql.sock'连接到本地MySQL服务器
将
localhost
替换为 127.0.0.1
。
如果仍然无法连接,请检查 mysql 服务器是否正在运行。
service mysqld start
然后,尝试以下操作之一:
(如果你还没有设置mysql密码)
mysql -u root
如果您已设置密码
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
更好的方法是将连接和登录参数分开。
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
与数据库工厂结合使用可以保持数据分离和干净。
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
之后,您可以轻松地创建您的(基于类的)CRUD 类(对象名+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
通过这种精细的编码,在前端选择项目是小菜一碟:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
@session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
像这样的本地主机(MySQLi 程序)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}
使用 php 连接 MySQL 服务器的最简单方法。
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";