0

I am trying to add array data from mysql. But only the last row details are getting added. I tried array_push also but did not work. Can any one help

$sql="SELECT * FROM server_details";
$result=mysqli_query($dbC,  $sql);
while ($row = mysqli_fetch_array($result))
{
$services=array( 
    $row['server_name'] => array($row['server_add'] => $row['port'])
); 
}   

2 Answers 2

2

By not creating a new array in every iteration of the loop :

$sql      = "SELECT * FROM server_details";
$result   = mysqli_query($dbC,  $sql);
$services = array();

while ($row = mysqli_fetch_array($result)) {
    $services[$row['server_name']] = array($row['server_add'] => $row['port']); 
}   
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps you're looking for this:

$services[ $row['server_name'] ] = array($row['server_add'] => $row['port']);

In the end you'll get in your $services variable an associative array, indexed by server_name column values.

If they're not unique, you should do this instead...

$services[ $row['server_name'] ][] = array($row['server_add'] => $row['port']);

This way you'll still get the same associative array, but its values will be indexed arrays; thus you won't lose any information for records with the same server_name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.