Shino Rascal Shino Rascal - 5 months ago 20
SQL Question

PHP Array from mysql assoc

Confusing my values so messy

Home Code

$user = getventList();
$response = array();
if(mysql_num_rows($user) > 0){
while ($row = mysql_fetch_assoc($user)){
$response[] = $row;
echo json_encode($response);
}
} else {
return false;
}


enter code here


Function event
this one is function to generate result from mysql


$result = mysql_query("SELECT * from event where status = '2'");
return $result;


Bad Result

[ {"cPID":"123","image_event":"enjoy.jpg"}
]

[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"}
]

[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"}
]

[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"}
]

[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"},
{"cPID":"1234567","image_event":"enjoy.jpg"}
]


i wanna get only like the last array

[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"},
{"cPID":"1234567","image_event":"enjoy.jpg"}
]

Answer

Move json_encode out of the while loop. Additionally quit using mysql and start using mysqli or PDO functions.

$user = getventList();
    $response = array();
    if(mysql_num_rows($user) > 0){
    while ($row = mysql_fetch_assoc($user)){
         $response[] = $row;          
    }
    } else {
         return false;
    }
    echo json_encode($response);

Now your output will be the expected one

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"},
   {"cPID":"12345","image_event":"enjoy.jpg"},
   {"cPID":"123456","image_event":"enjoy.jpg"},
   {"cPID":"1234567","image_event":"enjoy.jpg"}
]
Comments