Mr Zy Mr Zy - 2 months ago 6
MySQL Question

How to Convert mysql to array result with number

I have php code like this

$sql = mysql_query("SELECT userName FROM `rcpa_users` WHERE upline_users = '$selectuname'");
while($tjans = mysql_fetch_array($sql)){

print_r($tjans);

}


But output show this

Array ( [userName] => mita )
Array ( [userName] => wendyang )
Array ( [userName] => viviekosasih )


Now, how to convert array like this result

Array
(
[0] => mita
[1] => wendyang
[2] => viviekosasih
)


so I can call with echo $tjans[0], $tjans[1], $tjans[2]

Thank You..

Answer

mysql_fetch_assoc() - Fetch a result row as an associative array.This function will return a row as an associative array where the column names will be the keys storing corresponding value.

Description: Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

After that you need to do the array_values() so that it converts all the values to array with numeric keys.

array_values — Return all the values of an array

array_values() returns all the values from the array and indexes the array numerically.

If your query returns multiple rows as output you can prefer this method:

$sqlxx = mysql_query("SELECT userName FROM rcpa_users WHERE upline_users = '$selectuname'"); 
$final_tjans = array();
while($tjans = mysql_fetch_assoc($sqlxx))
{
    $final_tjans[] = $tjans['userName'];
}
print_r($final_tjans);

If you code returns only single row as output:

$sqlxx = mysql_query("SELECT userName FROM rcpa_users WHERE upline_users = '$selectuname'"); 
$tjans = mysql_fetch_assoc($sqlxx));
$final_tjans = array_values($tjans); 
print_r($final_tjans);

Example:

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

Output:

Array
(
    [0] => XL
    [1] => gold
)

Note: Usage of mysql extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.