警告:mysql_query()期望参数2是资源,

时间:2013-08-29 23:03:42

标签: php mysql

我正在尝试运行这个PHP函数:

function makeString() {
    // Create our random string
    $string = "";
    $characters = array('a', 'b', 'c', 'd');

    for ($i = 0; $i < 4; $i++)
    {
        $string .= $characters[mt_rand(0, 4)];
    }

    $sql="SELECT COUNT(*) FROM urls WHERE short_url = '{$string}'";
    $rs=mysql_query($sql,$conn);
    $result=mysql_fetch_array($rs);

    if($result['COUNT(*)'] > 0)
    {
        // if it already exists, do it again
         makeString();
    }
    else
    {
        return $string;

        //insert the data
    }
}

makeString();

但我得到了这些错误:

Warning: mysql_query() expects parameter 2 to be resource, null given in /home/charlie/public_html/short/shorten.php on line 15

Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/charlie/public_html/short/shorten.php on line 16

他们是什么意思?

所有表/数据库列似乎没问题,没有保留字等...

2 个答案:

答案 0 :(得分:2)

$conn在函数makeString()范围内不可用,您可以将其删除,因为如果已连接则不需要它,或者您可以将其作为函数参数传递,如:

makeString($conn);

答案 1 :(得分:2)

您需要定义$conn或将其传递给函数。

//Defined Outside of Function
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database', $link);

//Make argument for connection
function makeString($conn)
{
    //Rest of Function Here
}

//Execute function, passing $link as argument.
$result = makeString($link);

function makeString()
{
    //Define Connection Within Function
    $conn = mysql_connect( 'localhost', 'user', 'pass' );
    mysql_select_db('database', $conn);

    //Rest of Function Here
}

在任何情况下,直接mysql扩展程序都会被弃用,请考虑将代码转换为使用mysqliPDO

MySQLi Reference
PDO Reference