这是检查特定用户池的池中是否存在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 时失败。
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
}
将
这个函数用于多维数组:
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 ) );