gpt4 book ai didi

php - mysql连接失败

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:07 24 4
gpt4 key购买 nike

我正在使用这段代码连接mysql

    $con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
mysql_select_db("ManagersDatabase", $con);

mysql 数据库位于/var/lib/mysql/ManagersDatabase。我的 php 页面位于 /var/www/html/ 中。它不打印任何东西。我的代码有什么问题?

最佳答案

这是您应该使用 PDO 进行连接的方式:and utilizing prepared query's when querying.

<?php 
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=your_database','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
?>

或者mysqli and utilizing prepared query's when querying .

<?php
$con = new mysqli("127.0.0.1", "user", "password", "your_database");
if ($con->connect_errno) {
die("Failed to connect to MySQL: (".$con->connect_errno.") ".$con->connect_error);
}
print_r($con);
?>

编辑(回复评论):如果添加 print_r($con);,您应该会看到 mysqli 连接对象,如下所示:

/*
mysqli Object
(
[affected_rows] => 0
[client_info] => mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
[client_version] => 50010
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)

[field_count] => 0
[host_info] => 127.0.0.1 via TCP/IP
[info] =>
[insert_id] => 0
[server_info] => 5.5.25a
[server_version] => 50525
[stat] => Uptime: 10 Threads: 1 Questions: 1 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.100
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 1
[warning_count] => 0
)
*/

其他方法已经过时,很快就会(谢天谢地)被弃用。

关于php - mysql连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12051941/

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