-1

这是检查contact_id是否存在于特定用户池中的代码

function checkid()
{
    $conn = connectPDO();

    $query = "SELECT contact_id FROM contacts WHERE contact_by = :cby";
    $st = $conn->prepare( $query );
    $st->bindValue( ':cby', $this->contact_by, PDO::PARAM_INT );
    $st->execute();
    $row = $st->fetchALL();
    $conn = null;

    print_r($this->contact_id); //1
    print_r($row);     //Array ( [0] => Array ( [contact_id] => 1 [0] => 1 ) [1] => Array ( [contact_id] => 3 [0] => 3 ) ) 

    if( !in_array( $this->contact_id, $row ))
    {
        echo 'You are not authorised to update the details of this contact';
    }
}

这是网址:

http://localhost/contmanager/home.php?action=update&contactid=1

我注意到的一件事是,当我使用 fetch 而不是 fetchall 时,它适用于 contact_id '1' 但在使用 fetchALL 时会失败。

4

2 回答 2

2

in_array不适用于多维数组,解决方法将是:

foreach( $row as $each ){  #collect all the ids in an array
    $temp[] = $each['contact_id'];
}

然后检查in_array

if( !in_array( $this->contact_id, $temp )){
    //your code here
}
于 2013-09-17T11:43:18.137 回答
-1

将此函数用于多维数组:

function in_multiarray($elem, $array)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom] == $elem)
            return true;
        else 
            if(is_array($array[$bottom]))
                if(in_multiarray($elem, ($array[$bottom])))
                    return true;

        $bottom++;
    }        
    return false;
}

例子 :

$array = array( array( 'contact_id' => '1' , 1 ) , array( 'contact_id' => '3' , 3 ) );
var_dump( in_multiarray( 1 , $array  ) );
于 2013-09-17T11:45:08.973 回答