Reputation: 13
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 `
Upvotes: 0
Views: 944
Reputation: 424
If the $ID
array is only being set so it can be implode
d 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
Upvotes: 0
Reputation: 226
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."')");
Upvotes: 0
Reputation: 220
I guess you need also:
implode(',', $ID);
To get "2,3" string, explode does the oposite.
Upvotes: 1
Reputation: 16436
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);
Upvotes: 2