0

Hi I am stuck at this echo array part. Only getting first item. Please help! All help will be appreciated!

session_start();
$session = $_SESSION['sessionId'];

$link = mysqli_connect("localhost", "ideajackpot", "random!", "ideajackpot");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$result = "SELECT title FROM title WHERE session_id LIKE $session";

$flickrItems = mysqli_query($link, $result);
$flickrArray = mysqli_fetch_array($flickrItems);


mysqli_close($link);

foreach($flickrArray as $result) {
    echo $result.' ';
}

3 Answers 3

4

You're only getting the first row of your SQL query because you are calling mysqli_fetch_array() only once. You need to loop through the results to get all of your returned rows:

while ($flickrArray = mysqli_fetch_array($flickrItems);
    echo $flickrArray['title'].' ';
}
Sign up to request clarification or add additional context in comments.

3 Comments

I changed it to echo $flickrArray[0].' '; and it's working now thanks!
I'm curious though. This line WHERE session_id LIKE $session shouldn't that be WHERE session_id='$session'? Doing it the other way would need to have % signs, no?
Ah ok. Bizarre though. I guess there's something I didn't know, that I now know. @RaymondtheDeveloper - Will give that a try sometime.
1

You can try also object oriented aproach:

  $link = new mysqli("localhost", "ideajackpot", "random!", "ideajackpot")

  $flickrItems = $link->query("SELECT title FROM title WHERE session_id LIKE $session");

  while ($flickrItem = $flickrItems->fetch_assoc() ){
        $result[] = $flickrItem;
  }

  var_dump($result);

Comments

1

If you ever want to fetch just the first, or perhaps, the last item in an array why not create some little functions for that.

/**
 * Return first element in array.
 *
 * @param array $array
 * @return mixed
 */
function array_first(array $array)
{
    reset($array);

    return current($array);
}

/**
 * Return last element in array.
 *
 * @param array $array
 * @return mixed
 */
function array_last(array $array)
{
    reset($array);

    return end($array);
}

Usage:

$foo = [1, 2, 3];

var_dump(array_last($foo));

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.