PHP if语句使用foreach循环

时间:2013-09-16 07:34:03

标签: php

我在php中使用这个foreach循环来选择每个$_SESSION变量

<?php
//reseller info
foreach ($_SESSION["domain.co.uk"]["resellers"] as $reseller)
{
    $sql2="SELECT * from reseller where sequence = '".$reseller."' ";
    $rs2=mysql_query($sql2,$conn) or die(mysql_error());
    $result2=mysql_fetch_array($rs2);
    $ResellerID = $result2["sequence"];
}
?>

显然有不止一个,我需要查看页面:

if($this_var = $ResellerID)
{
...

但这只是检查一个$ResellerID的if语句 - 我需要检查所有这些语句。

这可能吗?

3 个答案:

答案 0 :(得分:1)

if循环中使用foreach子句。

<?php
//reseller info
foreach ($_SESSION["integradigital.co.uk"]["resellers"] as $reseller)
{
    $sql2="SELECT * from reseller where sequence = '".$reseller."' ";
    $rs2=mysql_query($sql2,$conn) or die(mysql_error());
    $result2=mysql_fetch_array($rs2);
    $ResellerID = $result2["sequence"];

   if($this_var == $ResellerID)
   {
      // Something to do
   }
}
?>

或者您可以与in_array一起查看:

<?php
   $rid = array();

   foreach ($_SESSION["integradigital.co.uk"]["resellers"] as $reseller)
   {
      $sql2="SELECT * from reseller where sequence = '".$reseller."' ";
      $rs2=mysql_query($sql2,$conn) or die(mysql_error());
      $result2=mysql_fetch_array($rs2);
      $rid[] = $result2["sequence"];
   }

   if(in_array($this_var, $rid))
   {
      // Something to do
   }
?>

答案 1 :(得分:1)

首先,您应该立即停止使用任何mysql_ *函数。看看这里:http://php.net/manual/en/function.mysql-query.php

现在不推荐使用该接口,您应该使用PDO_MySQL或MySQLi。

您的代码中也存在SQL注入漏洞,因为您没有清理SQL查询的输入。

要回答你的问题,你可以这样:

<?php
//reseller info
foreach ($_SESSION["integradigital.co.uk"]["resellers"] as $reseller){
    $stmt = $db->prepare('SELECT * FROM reseller WHERE sequence = (?)');
    $stmt->execute(array($reseller));
    $result = $stmt->fetchAll();
    $resellerID = $result["sequence"];

    if($this_var == $resellerID){
        //Your code here
    }
}
?>

您还应该尽可能避免使用SELECT *,而是将*替换为字段名称。如果将来添加新字段,则查询可能会提取并返回不需要的数据。

$stmt = $db->prepare('SELECT name, address FROM reseller WHERE sequence = (?)');

答案 2 :(得分:0)

在你的foreach中,添加一个变量$ i,如果满足条件则递增:

$ I = 0;

<?php
//reseller info
foreach ($_SESSION["integradigital.co.uk"]["resellers"] as $reseller)
{
    $sql2="SELECT * from reseller where sequence = '".$reseller."' ";
    $rs2=mysql_query($sql2,$conn) or die(mysql_error());
    $result2=mysql_fetch_array($rs2);
    $ResellerID = $result2["sequence"];

   if($this_var == $ResellerID)
   {
      $i++;// or change $i to boolean
   }
}

 if($i>0){ 
    //your code here 
 }

?>