0

My function for retrieving data from database:

function db_retrieve($query)
{
  // user password etc.
  require_once('db_info.php');

  // Initialise function vars.
  $q_success = 0;    // Query successful?
  $error_text = "";  // Error text (if any).

  $db_handle = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
  $db_found = mysqli_select_db($db_handle, $db_name);

  // Database found
  if($db_found)
  {
    // Query database.
    $result = mysqli_query($db_handle, $query);

    // Database query was successful.
    if($result)
    {
      // Flag showing our DB query was successful.
      $q_success = 1;

      //insert data into an associative array.
      $row = mysqli_fetch_assoc($result);
    }
    // Something went wrong with our SQL query.
    else
    {
      $q_success = 0;
      $error_text = "Error";
    }
  }
  // Database was not found
  else
  {
    $q_success = 0;
    $error_text = "Database not found";
  }

  return array($q_success, $error_text, $row);
}

Usage of the function

list($success, $error, $data) = db_retrieve($sql);

foreach($data as $val)
{
  echo "<img src=\"". $data['path'] ."\"/><br>";  // 'path' is the table row in the database.
}

I decided to implement this database query function as the code will be replecated dozens of times throughout my project otherwise. The function successfully returns $q_success and $error_text, but the issue lies with $row.

using var_dump($data); confirms this.

The problem i have is that when my function returns the associative array, $row only contains the first element of the array and annoyingly displays it 4 times.
For example, if my database query returns lets say 10 rows, instead of my code outputting all 10 rows, it will only output the first row 4 times.

I think the way i am returning my sql query $row is wrong. Any ideas on this would be great.

Thanks.

3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by brizleciderarmy
2

mysqli_fetch_assoc function returns only one row. You use a while loop to go through all the rows (10 in your case) but the way you implemented your function this is not happening. If you want to use this function to return all results, you have to read all the rows within the function an return the array of rows not only one row (hopefuly you wont get to big resultsets).

0

Thanks for the replies. I gathered it may be something as simple as a loop or something similar. Hey Ho.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.