public static function find_user_tracks($id)
{
global $mySQL;
$sql = "SELECT * FROM `tracks` WHERE account_id = {$id}";
$result_set = $mySQL->query($sql);
$ret = array();
while($row = $result_set->fetch_assoc())
{
$ret[] = $row;
}
return $ret;
}
The above code contains the result of a database query. The database looks like this:
database screenshot
So, basically, it will return a set of fields with values and then those values will be used for a certain page:
$row = Track::find_user_tracks($id);
if(!empty($row))
{
$track_paths = array();
$track_names = array();
$track_desc = array();
$track_ids = array();
$track_artist = array();
for($i = 0 ;$i<count($row);$i++)
{
$track_paths[] = $row[$i]['track_path'];
$track_ids[] = $row[$i]['track_id'];
$track_names[] = $row[$i]['track_name'];
$track_desc[] = $row[$i]['track_desc'];
$track_artist[] = $row[$i]['artist'];
}
echo "<h1> {$screename}'s Beats</h1>";
}
The $row
variable contains the result from the previous queries. I loop over $row
to extract every single bit of data like track_id
, track_name
, etc.
Is there any way to make this cleaner or improve it?
1 Answer 1
I think this will work. You'll have to have PHP version 5.3 though, otherwise you'll have to remove the lambda functions and define actual functions in their place. Disclaimer, not to say that this is easier to read or easier to understand, but I think it fits the "cleaner" request.
$track_paths = array_map( function ( $array ) { return $array[ 'track_path' ]; }, $row );
$track_ids = array_map( function ( $array ) { return $array[ 'track_id' ]; }, $row );
$track_names = array_map( function ( $array ) { return $array[ 'track_name' ]; }, $row );
$track_desc = array_map( function ( $array ) { return $array[ 'track_desc' ]; }, $row );
$track_artist = array_map( function ( $array ) { return $array[ 'track_artist' ]; }, $row );