Chathurika Chathurika - 6 months ago 23
SQL Question

Array to string conversion in mysql while loop

Following is my code,

$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);

$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);





When I'am trying to use
$myArrayOfemp_id
variable in
$sql
query, It shows that error:


Array to string conversion in..


How can I fix it?

Answer

You are trying to convert an array into a string in the following line:

$sql = "SELECT emp_id FROM emp_leaves 
WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";

$myArrayOfemp_id is an array. That previous line of code should be changed to:

$sql = "SELECT emp_id FROM emp_leaves 
WHERE emp_id={$myArrayOfemp_id[0]} ORDER BY apply_date DESC";

I placed 0 inside {$myArrayOfemp_id[0]} because I'm not sure what value want to use that is inside the array.


Edited:

After discussing what the user wanted in the question, it seems the user wanted to use all the values inside the array in the sql statement, so here is a solution for that specific case:

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