0

I have a function that extracts the details of an item in a database, and adds it to an array before returning it. Currently, i am trying to query the filepath of any images related to the item and add it to the array.To do this, i run the query with PDO, fetch the filepaths using a WHILE->fetch loop and then use a $i iterator to change the array's key with each loop.

Problem:The WHILE loop is working as a var_dump of the array shows the latest filepath, however the iterator isn't working, and the array key isn't being changed.As such,the array key for the image is being overwritten with each loop, instead of having a new one added.

How do i make the array key update with each loop?

Function code(extract):

//Additional code above
//Gets itempics
$getimg=$connection->prepare("SELECT `FilePath`,`Extension` FROM `ItemPics` WHERE `ItemID`=:itemid");
$getimg->bindValue(":itemid",$itemid);
$getimg->execute();
while($fetchimg=$getimg->fetch(PDO::FETCH_ASSOC))
{
    $i=0;
    $imgname=$fetchimg["FilePath"];
    $imgext=$fetchimg["Extension"];
    $details["img$i"]=$imgname.$imgext;
    $i+=1;
}
return $details;

var_dump results(extract):

["img0"]=> string(58) "..\Images\1\item\ITEMDPTEST 15\52b5d6cca8ba08.33798550.jpg" 

The solution is probably pretty obvious but i can't seem to figure it out. P.S i've tried changing the $i+=1 to $i++ but it doesn't work as well.

3 Answers 3

2

Move $i=0; outside the while loop:

$i=0;
while($fetchimg=$getimg->fetch(PDO::FETCH_ASSOC))
{
    $imgname=$fetchimg["FilePath"];
    $imgext=$fetchimg["Extension"];
    $details["img$i"]=$imgname.$imgext;
    $i+=1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

This:

$i=0; //outside the loop, first this and bellow the while loop

Later change this:

$details["img$i"]=$imgname.$imgext;

To something like this:

$details["img"][$i]=$imgname.$imgext;

At the end:

var_dump($details["img"]);

Comments

0

You need to set $i = 0 before the loop.

It would also probably make more sense (and be more natural) if you just used numeric indices:

$imgname = $fetchimg["FilePath"];
$imgext = $fetchimg["Extension"];
$details[] = $imgname.$imgext;

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.