Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function to return sql results that contain arrays, as an array

So im having a problem (obviously). I have the following MySQL table data

7   USER1       1,1,1,10,1      The Guys Team   8,7,13,14,16
8    USER1      1,1,1,10,1  The Girls Team  7,12,15
10  USER1       1,1,1,10,1  Dog Team    8,7,14,15

I wrote a function to retrieve the data, and return it.

function ShowSetTeams($coach){
    $result = mysql_query("SELECT * FROM `teams` WHERE coach = '$coach'") or trigger_error(mysql_error()); 
    while($row = mysql_fetch_array($result)){ 
        foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } 
            $id = $row['id'];
            $teamname = $row['teamname'];
            $team = $row['team'];
            $event = $row['event'];
            $push .= array($id, $teamname, $team, $event);
    }
    return $push;
}

When i call the function, as below

$info = ShowSetTeams("USER1");

I get this

ArrayArrayArray 

I tried echoing $info[0], $info[1], and $info[2], but get this

Arr

So each line in the info array, is the result array. I should be able to do $info[0][0] and get the first ID value, from the first result right?

Fatal error: Cannot use string offset as an array

Im at a loss. How can i get to each of the values of the returned arrays? And more to the point, how could i run a foreach operation on them such as

foreach( $info as $key => $value){
$key[0] //ID
$key[1] //TEAMNAME
$key[2] //TEAM
$key[3] //EVENT
}
like image 652
mrpatg Avatar asked Aug 08 '26 20:08

mrpatg


1 Answers

You're using string concatenation instead of array notation:

$push[] = array($id, $teamname, $team, $event);

You should also initialise $push = array(); before you start using it.

You're also doing a lot of extra work... you could just do:

function ShowSetTeams($coach)
{   
    $push = array();
    $result = mysql_query("SELECT id, teamname, team, event FROM `teams` WHERE coach = '$coach'") or trigger_error(mysql_error());
    while($row = mysql_fetch_array($result, MYSQL_NUM))
    {
        // I doubt you actually need to run stripslashes on your data...
        $row = array_map('stripslashes', $row);
        $push[] = $row;
    }

    return $push;
}

Unless you have to, I wouldn't use re-key it to a numerically indexed array either - you're just making it harder to understand in your later code. Use mysql_fetch_assoc() to do this

like image 92
Greg Avatar answered Aug 10 '26 09:08

Greg