1

我有一个表格,允许我的用户根据需要编辑信息。作为此表格的一部分,用户最多可以插入 5 种类型的证明。所有证明都存储在一个单独的表中:

Table: Proof

proofid - primary key
banid - foreign key -> links to banlist table which stores all other information
proof - the link to which contains the proof
type - the type of proof (image, demo, league, ...)
number - the index number of the proof (0 up to 4)

我还有以下代码来更新或插入证明项目。它遍历每个字段,并检查数组中当前选定的项目是否不为空。如果为真,它会检查 $i 是否在存储所选禁令 id 的所有数字的数组中。

banid 237 的数组如下所示:Array ( [0] => [1] => 1 )

这实际上表示第一个证明字段是空的,但第二个不是,并且表中存在一条记录。

for($i = 0; $i < 5; $i++)
{
    $proof = $checkprooflist[$i];
    $prooftype = $checkprooftypelist[$i];

    if (!empty($proof))
    {                       
        if(!in_array($i, $proofnumberlist))
        {
            $query2 = "INSERT INTO proof (banid, proof, type, number) VALUE ($id, '$proof', '$prooftype', $i)";
            $result2 = mysql_query($query2);
        }
        else
        {
            $query2 = "UPDATE proof SET proof = '$proof', type = '$prooftype' WHERE number = $i AND banid = $id";
            $result2 = mysql_query($query2);
        }
    }           
}

然而,我遇到的问题是,对于上面的数组,该行if(!in_array($i, $proofnumberlist))返回 false,因此当 $i = 0 时不输入 if 语句。

It works for all other values (where $i = 1, ...) and so forth but not when $i = 0.

Thank you for reading and I appreciate any help you may be able to give me.

Jon.

4

3 回答 3

3

You have to use the $strict parameter of in_array(), it's the third one (default = false).

Due to type juggling, an empty string can be equal to 0, etc. The $strict parameter makes sure to also test the types.

if (!in_array($i, $proofnumberlist, true))
于 2012-05-15T02:34:41.040 回答
2

On the other hand, you could sidestep the entire in_array check by using INSERT ... ON DUPLICATE KEY UPDATE.

This would make your code a bit clearer. See http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

于 2012-05-15T02:38:20.607 回答
1

There is no 0 in this array:

Array ( [0] => [1] => 1 )

The element at index 0 is null, not 0. Where did you get this array in the first place?

于 2012-05-15T02:53:04.877 回答