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.