警告:mysql_query():3不是有效的MySQL-Link资源

Pie*_*ter 21 php mysql

我得到了这个奇怪的错误,我无法弄清楚它来自哪里:

Warning: mysql_query(): 3 is not a valid MySQL-Link resource in (...)

3有什么关系?我不明白.有没有人自己经历过这个错误?

gap*_*ple 31

PHP使用资源作为特殊变量来保存到外部对象的链接,例如文件和数据库连接.每个资源都有一个整数id.(文件)

连接失败

如果数据库连接失败,你可能会得到一个"指定变量不是一个有效的MySQL-Link资源"错误,正如Dan Breen所提到的那样,因为应该保存资源的变量为null.

$link = mysql_connect('localsoth','baduser','badpass'); // failed connection
$result = mysql_query("SELECT 1", $link); // throws error
Run Code Online (Sandbox Code Playgroud)

由于您在错误消息中获取了特定的资源ID,因此数据库连接可能由于某种原因意外关闭.您的程序仍然具有带有资源ID的变量,但外部对象不再存在.这可能是由于在mysql_close()调用之前某处调用mysql_query,或者是因为关闭连接而导致的外部数据库错误.

$link = mysql_connect();
mysql_close($link);
// $link may still contain a resource identifier, but the external object is gone
mysql_query("SELECT 1", $link);
Run Code Online (Sandbox Code Playgroud)

重用连接

mysql扩展的问题mysql_connect()是默认情况下,如果在连续调用中传递相同的参数,它将重用现有连接而不是创建新连接(文档).这可以通过传递true$new_link参数来修复.
我自己在一个测试系统上遇到过这种情况,在这个测试系统中,来自生产中两个独立数据库的数据被合并到一个测试服务器上,并且在测试中,mysql_xxx()函数调用相互走过并打破了系统.

$link1 = mysql_connect('localhost','user','pass'); // resource id 1 is given
$link2 = mysql_connect('localhost','user','pass'); // resource id 1 is given again
mysql_close($link2); // the connection at resource id 1 is closed
mysql_query("SELECT 1", $link1); // will fail, since the connection was closed
Run Code Online (Sandbox Code Playgroud)

使用$new_link:

$link1 = mysql_connect('localhost','user','pass'); // resource id 1 is given
$link2 = mysql_connect('localhost','user','pass', true); // resource id 2 is given
mysql_close($link2); // the connection at resource id 2 is closed
mysql_query("SELECT 1", $link1); // the connection at resource id 1 is still open
Run Code Online (Sandbox Code Playgroud)

编辑:顺便
说一下,如果可能的话,我建议使用MySQLi扩展或PDO.MySQL扩展已经很老了,无法利用MySQL 4.1.3之后的任何功能.请查看http://www.php.net/manual/en/mysqli.overview.php,了解有关三个接口之间差异的一些详细信息.


小智 6

我也有这个问题.在检查我的代码时,我发现我有一个关闭连接的脚本,所以当php试图再次关闭它时,我们得到了错误.

要解决此问题,请在尝试关闭连接之前检查连接是否已打开:

代替:

mysql_close($con);
Run Code Online (Sandbox Code Playgroud)

做这个:

if( gettype($con) == "resource") {
    mysql_close($con);
}
Run Code Online (Sandbox Code Playgroud)