gpt4 book ai didi

php - Codeigniter 无法连接到外部 SQL Server

转载 作者:可可西里 更新时间:2023-11-01 07:43:55 26 4
gpt4 key购买 nike

我正在尝试将我的 codeigniter 框架连接到外部数据库。但是显示错误

A Database Error Occurred Unable to connect to your database server using the provided settings. Filename: core/Loader.php Line Number: 346

然后,我将这个插入到 config/database.php 的末尾

  echo '<pre>';
print_r($db['default']);
echo '</pre>';

echo 'Connecting to database: ' .$db['default']['database'];
$dbh=mysql_connect
(
$db['default']['hostname'],
$db['default']['username'],
$db['default']['password'])
or die('Cannot connect to the database because: ' . mysql_error());
mysql_select_db ($db['default']['database']);

echo '<br /> Connected OK:' ;
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);

但是显示

A PHP Error was encountered Severity: 8192 Message: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead Filename: config/database.php Line Number: 79

A PHP Error was encountered Severity: Warning Message: mysql_connect(): Can't connect to MySQL server on '167.114.xxx.xxx' (111) Filename: config/database.php Line Number: 79

Cannot connect to the database because: Can't connect to MySQL server on '167.114.xxx.xxx' (111)

然后我尝试在 codeigniter 目录之外创建这个(在 public_html 中)

<?php
$servername = "167.114.xxx.xxx";
$username = "myusername";
$password = "dbpass";
$database = "dbname";

// Create connection
$conn = mysql_connect($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

然后显示连接成功。所以我该怎么做?而 config/database.php 中的数据库详细信息与上面相同

最佳答案

默认情况下,MySQL 将拒绝来自外部的连接。

您的 MySQL 服务器位于何处?通常,如果您使用某些网络托管服务,它们允许您从他们的 CPanel 解锁外部连接。请注意,它们中的大多数都需要一些时间才能真正激活。

此外,请注意 mysql_connect 不返回对象,而只是返回资源(连接 ID)。因此,如果您真的想继续使用已弃用的(旧的)MySQL API,请执行以下操作:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // note that if the port is different from 3306, you must do: 'server:port'
if (!$link) {
die('Could not connect ' . mysql_error());
}
echo 'Connection successfull';
mysql_close($link);

但是,建议使用 MySQLi 或 PDO 之类的东西,因为 MySQL 扩展由于长时间未更新、缺乏 OOP 支持、缺乏新的 MySQL 功能支持等原因而被弃用。

使用 MySQLI 的替代方法,来自 PHP 手册:

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

关于php - Codeigniter 无法连接到外部 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36575887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com