php - 警告 : in_array() [function. in-array]:第二个参数的数据类型错误

标签 php mysql

几年没有使用 PHP 进行编程,我对 PHP 有点生疏了。

我正在使用 PHP 从 mySQL 中的数组中获取数据。

我的问题是,在某些时候我使用以下方法从表中获取数据:

$myArray = mysql_fetch_array( $data ); 

但在某些时候,数据库可能为空,因此 $myArray 将为 null 或不包含任何元素。

然后我必须检查即时生成的特定字符串是否在 $myArray 上。如果是,则必须生成另一个字符串并验证它是否已存在于 $myArray 上。

$myString = generateString();
if (in_array($myString, $myArray)) {
    $myString = generateString();
}

这段代码给了我这个错误:

警告:in_array() [function.in-array]:第二个参数的数据类型错误

为了防止 in_array 在 $myArray 为空时运行,我这样做了:

if (count($myArray) > 0) {
    if (in_array($myString, $myArray)) {
        $myString = generateString();
    }
}

但是当数组为空时 count 给我 1 (?)...

我该如何解决这个问题?

还有一个问题:$myString 正在已测试的 IF 内部进行修改。这在 PHP 中可能吗?

最佳答案

好吧,如果您的查询失败,您将...等待...没有数组!

因此,in_array 调用会向您发出警告,提示 $myArray 不是数组(而是 false)。

您需要检查查询是否有错误,最好是:

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

关于php - 警告 : in_array() [function. in-array]:第二个参数的数据类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13445051/

相关文章:

php - 数据库与 XML 文件的最小内容

php - 加载自定义 CodeIgniter 库时传递参数

php - 如何在 PocketMine 插件中创建具有本地化描述的命令?

php - MySQL 连接返回太多行

mysql - 如何在 MySQL 中创建/使用变量

mysql - 错误代码: 1064 in stored procedure update

php - Wsdl curl 错误 7 : couldn't connect to host

php - 从 3 个表中选择并在 div 中回显结果

mysql - 查找组中特定行的两个日期列之间的平均值

python - mysql 向表中插入重复值