Raymond the Developer
Raymond the Developer

Reputation: 1674

Only getting first item in array in php mysqli

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.' ';
}

Upvotes: 0

Views: 3048

Answers (3)

user5134807
user5134807

Reputation:

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));

Upvotes: 1

duke
duke

Reputation: 37

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);

Upvotes: 1

John Conde
John Conde

Reputation: 219934

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'].' ';
}

Upvotes: 4

Related Questions