Chathurika Chathurika - 6 months ago 9
SQL Question

Foreach loop in php mysql

Following code is fine to retrieve relevant result from DB. But when result is null, It shows


Notice: Undefined variable: myArrayOfemp_id in Warning: Invalid
argument supplied for foreach() in .


$result1 = "SELECT leave_id FROM emp_leaves where duty_assign=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
// var_dump($myArrayOfemp_id);

$sql = "SELECT * FROM emp_leaves WHERE ";
foreach ($myArrayOfemp_id as $value) {
$sql .= " leave_id={$value} || ";
}
$sql .= "1=2";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);


How can I avoid from displaying that error. Please help !

Answer

Just initialize array $myArrayOfemp_id before while loop

$myArrayOfemp_id = array();
while ($row = mysql_fetch_array($array)) {
      $myArrayOfemp_id[$cnt] = $row[0];
      $cnt++;
}
Comments