php mysql数据库连接错误

时间:2014-04-06 14:01:17

标签: php mysql

我有以下PHP代码从html表单获取用户登录详细信息:

  $con=mysqli_connect("host","user","pass","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$query = "select username from users where user='$_POST[username]' limit1";
$result = mysql_query($query);
echo result;

但是当我运行它时,我似乎得到了这些错误:

  

警告:mysql_query()[function.mysql-query]:无法连接到本地   MySQL服务器通过socket' /目录省略' (2)in   /目录在第10行省略

     

警告:mysql_query()[function.mysql-query]:指向服务器的链接   无法建立   /目录在第10行省略

任何人都可以帮忙吗?非常感谢!

2 个答案:

答案 0 :(得分:1)

您已将mysqlimysql混合在一起,因此存在大量拼写错误

代码应该是:

 $con = mysqli_connect("host","user","pass","db");

 // Check connection
 if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $u = $_POST['username'];

 $sql = "SELECT username FROM users WHERE user='$u' LIMIT 1";
 $query = mysqli_query($con, $sql);
 if ($row = mysqli_fetch_assoc($query)) {
    echo $row['username'];
 }

希望它有效。

或者如果您需要打印所有行,则应该是:

while ($row = mysqli_fetch_assoc($query)) {
    echo $row['username'];
}

答案 1 :(得分:1)

$query = "select username from users where user='$_POST[username]' limit1";
$result = mysql_query($query);

这些行应该类似于以下

$query = "SELECT username FROM users WHERE user='".$_POST['username']."' LIMIT 0,1";
$result = mysqli_query($con,$query);
print_r(mysqli_fetch_array($result));