-2

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 !

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
Chathurika
  • 419
  • 2
  • 6
  • 18

3 Answers3

1

Just initialize array $myArrayOfemp_id before while loop

$myArrayOfemp_id = array();
while ($row = mysql_fetch_array($array)) {
      $myArrayOfemp_id[$cnt] = $row[0];
      $cnt++;
}
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
1

you also should make sure to escape your strings before putting them in the query. see here for a better explanation How to include a PHP variable inside a MySQL insert statement

And before the while loop you should check with mysql_num_rows() if there are any results.

Community
  • 1
  • 1
1

Hi First why you are using "1=2" it should be 1=1. Second always define array before using it so define $myArrayOfemp_id = array(); before while loop.

For sake of correct ouput please print your $sql before executing is means. echo $sql; and run the resultant query in Phpmyadmin

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44