I am tying to use a foreach loop inside a prepared statement…and that because I have to work with an array…here is the code…shortened for brevity.
foreach ($favorites as $key => $value) {
if($stmt = $connection->prepare('SELECT servicename FROM services_list,busers_services
WHERE services_list.serviceID=busers_services.serviceID
AND b_user=?'))
{
....
....
if($stmt->num_rows > 0)
{
$stmt->bind_result($servicename);
while ($stmt->fetch())
{
$services[]=['servicename'=>$servicename];
}
}
.....
}`
The code you see above produces a multidimensional array…(it retrieves from the db the services associated with a business…a hair salon for example might offer a haircut and a maniciur)
And here is my problem,this multidimensional array must have as a key(in the first dimension) an integer which identifies the business user and which is found inside the favorites array and can be accessed with value[‘id’]…if I pass this to the array like this though:
I agree. The prepare statement NEVER belongs in a loop. The main point in using prepare is that you run it only once and so save having to build the entire query every time.
I don’t think this is the best approach. You could just construct the snippet properly using the proper procedures, select all rows (optional can be included with a WHERE clause), loop your data in the while loop and for the final step, create a multidimensional array and append the data appropriately with appropriate keys.
I have never seen a prepared statement being nested inside a foreach loop before. It seems very repetitive if you’d ask me because you’ll be looping multiple times depending on how many values are in the array. You should only need to prepare and do a database call once. Your data should then be handled accordingly.