2012-11-18 26 views
0

幾年後,我在PHP中有點生疏,沒有用這種語言編程。警告:in_array()[function.in-array]:第二個參數的數據類型錯誤

我使用PHP從MySQL中的數組中獲取數據。

我的問題是,在某些時候,我從表中提取數據,使用這樣的:

$myArray = mysql_fetch_array($data); 

,但在某些時候,數據庫可以是空的,所以$ myArray的將是空的或不包含元素。

然後我必須檢查一個特定的字符串是否在$ myArray上。如果是,則必須生成另一個字符串,並驗證它是否已經存在於$ myArray上。

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

此代碼給我此錯誤:

警告:in_array()[function.in陣列]:錯誤的數據類型的第二個參數

爲了防止in_array運行$ myArray的時是空的我這樣做:

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

,但數量是給我1當數組是空的...

(?)

我該如何解決?

只是另一個問題:$ myString在已經測試它的IF內被修改。這在PHP中可能嗎?

+0

的'mysql'擴展是過時,不鼓勵使用。改用'MySQLi'或'PDO_MYSQL'。 http://www.php.net/manual/en/function.mysql-connect.php – KingCrunch

+0

根據[文檔](http://php.net/manual/en/function.mysql-fetch-array.php) ,你可能會收到'假'的回報。你可以發佈'var_dump($ myArray)'的輸出嗎?注意,'mysql_ *'很快就會被棄用,請看[PDO](http://www.php.net/manual/en/ref.pdo-mysql.php)或[mysqli](取而代之的是http://www.php.net/manual/en/book.mysqli.php)。 –

回答

2

那麼,如果你的查詢失敗了,你將有......等待它......沒有數組!

因此,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 .

+0

你從哪裏拿過這個盒子?除此之外,引用總是好的:我想要它:D – KingCrunch

+0

http://stackapps.com/q/2116。評論源代碼可以在這裏找到:https://gist.github.com/3881905 –

+0

ahhhhhhh ....沒有數組!謝謝。現在工作! – SpaceDog

相關問題