【问题标题】:MySQL error connecting when creating a user using PHP使用 PHP 创建用户时 MySQL 连接错误
【发布时间】:2012-02-27 02:33:46
【问题描述】:

我正在尝试创建一个用于注册用户并将他们的信息存储在 MySQL 表中的 php 表单。这是 PHP 代码和 MySQL 表之后的错误。

警告:mysql_query(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /hsphere/local/home/khalidalomar/khalidalomar.com/talent/第 22 行的 added.php 警告:mysql_query():无法在第 22 行的 /hsphere/local/home/khalidalomar/khalidalomar.com/talent/added.php 中建立到服务器的链接 无效查询:无法连接通过套接字'/var/lib/mysql/mysql.sock'到本地MySQL服务器(2)

这是我的 PHP 代码

include("connect.php");

// Talent table
$t_username = strip_tags(substr($_POST['t_username'],0,32));
$t_password = strip_tags(substr($_POST['t_password'],0,32));
$t_fname = strip_tags(substr($_POST['t_fname'],0,32));
$t_lname = strip_tags(substr($_POST['t_lname'],0,32));
$t_cname = strip_tags(substr($_POST['t_cname'],0,32));
$t_phone = strip_tags(substr($_POST['t_phone'],0,32));
$t_description = strip_tags(substr($_POST['t_description'],0,32));
$t_tags = strip_tags(substr($_POST['t_tags'],0,32));


$results = mysql_query("INSERT INTO talents (id, t_username, t_password, t_fname, t_lname, t_cname, t_phone, t_description, t_tags, t_approved, t_dateofreg)
VALUES ('', '$t_username', '$t_password', '$t_fname', '$t_lname', '$t_cname', '$t_phone', '$t_description', '$t_tags', 'N', NOW() )"); // store date by NOW() // date int(8)

if($results) { echo "Successfully Added"; } else { die('Invalid query: '.mysql_error()); }

?>

如果您需要我可以提供的 SQL 查询。

【问题讨论】:

  • 您也应该在connect.php 中提供代码,因为这是连接到数据库的问题,而不是查询失败...
  • @MichalPlško 它有我的主机名、数据库用户名、密码和数据库名称。你觉得有必要把它的代码贴出来吗?
  • 当然不要暴露密码 :) xxx 在发布之前将它们暴露出来......您在此处发布的代码中没有对数据库的连接调用,所以它在 @987654324 中@ 或者你错过了什么......

标签: php mysql


【解决方案1】:

要么你的 mysql.conf 设置错误,要么编译你的 php 以在错误的路径中搜索 mysql.sock,或者你的 mysql 服务器没有运行。从我在您发布的代码中看到的您根本没有连接到数据库? connect.php 文件中有 mysql_connect(); mysql_select_db(); 吗?

【讨论】:

  • 完美!我不知道我需要添加 mysql_connect();到我的 added.php 页面和 connect.php 非常感谢 =)
  • 这是不正确的@Khalid - 要么将其添加到 connect.phpadded.php,不要将其添加到两者... connect.php 从脚本中调用,如果您将其添加到这两个文件最终都会出现重复的连接调用...
  • @MichalPlško 再次感谢。我将仅添加到 connect.php =) 赞赏。
【解决方案2】:

以前发生过。只需在 php 验证之前定义连接或使用绝对路径。此外,您可以在会话文件中创建一个 DB con 类(我假设您有一个,否则将其包含在连接中并在需要连接时简单地实例化)

<?php $root = realpath($_SERVER["DOCUMENT_ROOT"]);
inlcude($root./connect.php);//edit the path as needed.
?>

除此之外,你应该知道永远不要使用相对路径,因为这是一个非常糟糕的习惯。另外,我不会为此使用mysql。去 mysqli 参数化查询。这是一个升级的努力,但它是非常值得的麻烦。

【讨论】:

  • 感谢@Alex 的提示,感谢 =)
猜你喜欢
  • 2016-06-14
  • 2013-03-16
  • 1970-01-01
  • 2013-12-03
  • 2017-09-25
  • 2018-10-11
  • 2014-07-07
  • 2014-12-03
  • 1970-01-01
相关资源
最近更新 更多