简体   繁体   English

PHP mysql_connect不返回布尔值

[英]PHP mysql_connect not returning boolean

I have the following PHP code: 我有以下PHP代码:

$con = mysql_connect("localhost","name","pass") or die(mysql_error());

$db = "db";

mysql_select_db($db,$con);

Now in my experience, $con should be true or false. 现在,根据我的经验, $con应该为真或为假。 When I echo $con I get: 当我echo $con我得到:

Resource id #25

If I do the following code, the echo never fires (as to be expected after the above statement): 如果我执行以下代码,则回声将永远不会触发(如上述声明所示):

if($con) { echo "it worked"; }

When I run a query against this connection, everything works as expected. 当我对此连接运行查询时,一切正常。 Is there a reason why this $con will not be true or false? 为什么$con不能为真或假?

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

Check mysql_connect Return Values : 检查mysql_connect返回值:

Returns a MySQL link identifier on success or FALSE on failure.

So to check the connection: 所以要检查连接:

if($con !== false) { echo "it worked"; }

or to quit in case of an error: 或在出现错误时退出:

if (!$con) {
    die('Could not connect: ' . mysql_error());
}

A word of advice though, better to use the MySQLi or PDO_MySQL instead of mysql_connect since it will soon be deprecated: 提示一下,最好使用MySQLiPDO_MySQL而不是mysql_connect因为它将很快被弃用:

Warning 警告

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. 自PHP 5.5.0起不推荐使用此扩展,以后将删除。 Instead, the MySQLi or PDO_MySQL extension should be used. 相反,应使用MySQLi或PDO_MySQL扩展。 See also MySQL: choosing an API guide and related FAQ for more information. 另请参见MySQL:选择API指南和相关的FAQ,以获取更多信息。 Alternatives to this function include: 此功能的替代方法包括:

mysqli_connect() mysqli_connect()

PDO::__construct() PDO :: __结构()

Its simply b/c of the or or die(mysql_error()); 它只是or or die(mysql_error()); b / c or die(mysql_error()); at the end. 在末尾。

Give this a shot: 试一下:

<?php
$con = mysql_connect("localhost","name","pass");
$db = "db";
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db,$con);
?> 

I think it is because of the or die(mysql_error()); 我认为这是因为or die(mysql_error()); part. 部分。 I should be the $con = mysql_connect("localhost","name","pass") only. 我应该仅是$con = mysql_connect("localhost","name","pass") Then you can check like this: if (!$con) . 然后,您可以像这样检查: if (!$con)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM