0

I've searched through the stack for an answer but it seems that I cannot find a solution for the following code:

$servers = array();
while($row = mysql_fetch_array( $result ))
{
   $servers[] = $row['name'] => array('ip' => $row['ip'],'port' => $row['port'],'info' => $row['info'],'purpose' => $row['purpose']),
}

What I'm trying to achieve is fetch all results but I receive the following error:

syntax error, unexpected '=>' (T_DOUBLE_ARROW).

Making it like this gets only the last item:

while($row = mysql_fetch_array( $result )) {
$servers = array(
    $row['name'] => array('ip' => $row['ip'],'port' => $row['port'],'info' => $row['info'],'purpose' => $row['purpose']),
    );
}

That being said, $servers is in the while loop, thus making it index only the last item. I don't know what causes the unexpected => :/

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 2
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 04 '16 at 20:18

1 Answers1

1

It looks like you're trying to do this:

$servers = [];
while($row = mysql_fetch_array( $result )) {
   $servers[$row['name']] =  [
       'ip' => $row['ip'],
       'port' => $row['port'],
       'info' => $row['info'],
       'purpose' => $row['purpose']
   ];
}

That gives you a final $servers array, indexed by server name, with an array of details.

Side note: as Jay commented, you really shouldn't be using mysql functions any longer, really encourage you to check out mysqli or PDO functions instead.

jszobody
  • 28,495
  • 6
  • 61
  • 72
  • seems like $servers = array(); did the job. $servers = []; was still calling only 1. I took note on Jay's comment and will take a deep look on it. – Martin Spatovaliyski Mar 04 '16 at 20:32
  • @MartinSpatovaliyski `$servers = array()` and `$servers = []` are the exact same thing. `[]` is just shorthand for `array()`. – jszobody Mar 04 '16 at 20:33
  • @MartinSpatovaliyski If you'd like me to take a look at it, update your question with your modified code. something isn't right, and I can't tell you what's wrong unless I can see it. – jszobody Mar 04 '16 at 20:55