0

Having an issue with a piece of code when trying to pull an array out of a while loop. The code is as follows

$query = "SELECT ID,Assigned_user FROM work_orders";

$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {

    $Assigned[] = $row['Assigned_user'];
    $ID[] = $row['ID'];

    var_dump($ID);

The issue is when var_dump() returns its results the $ID[] is split in to two arrays which look like the following

array (size=1)
  0 => string '2' (length=1)
D:\wamp64\www\MYCMS\Admin\test.php:31:
array (size=2)
  0 => string '2' (length=1)
  1 => string '3' (length=1)

Where i need it to be one array which consists of the two values like Array ( [0] => 2 [1] => 3 )

then i need to explode it like

$IDS = explode(",", $ID);

so it becomes a string "2,3" so it can be used in the IN statement

to insert in to a select statement from my database

$wo_request = "SELECT * from work_orders Where ID IN ('$ID')";

if anyone can guide me on how to do this i would really appreciate it.

P.S I cant str_split it either since this needs to work for a whole load of numbers that go in to the hundreds so split it down to one character doesn't work `

4 Answers 4

2

It is because you have dumped array inside while loop. var_dump after while loop then check

while ($row = mysqli_fetch_assoc($result)) {

    $Assigned[] = $row['Assigned_user'];
    $ID[] = $row['ID'];
} //complete while loop

    var_dump($ID);
Sign up to request clarification or add additional context in comments.

Comments

1

I guess you need also:

implode(',', $ID);

To get "2,3" string, explode does the oposite.

1 Comment

I was just about to write this :p $wo_request = "SELECT * from work_orders Where ID IN (".implode(",",$ID).")";
0
while ($row = mysqli_fetch_assoc($result)) {

    $Assigned[] = $row['Assigned_user'];
    $ID[] = $row['ID'];
}

implode("','",$ID);

$query = sprintf("SELECT * from work_orders Where ID IN ('".$ID."')");

Comments

0

If the $ID array is only being set so it can be imploded into a string, you could achieve the same results using string concatenation.

$ID = ''; // Define $ID as a blank string so it can be added to in the loop
while ($row = mysqli_fetch_assoc($result)) {

$Assigned[] = $row['Assigned_user'];
$ID .= $row['ID'] . ','; // Append current ID and a comma to the ID string
}
rtrim($ID, ','); // Trim off the last comma

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.