0

Suppose that I have a table like this:

id     name    age   birthplace
------------------------------
1      John    28   NY
2      Marry   23   LD
3      Mohamad 34   Malaysia
...

I do while loop like this:

$query = "SELECT name, age, birthplace FROM tableName";
$result = mysqli_query($dbc, $query);
$tableRows = array();
while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)){
   $tableRows[] = $rows; 
}

echo '<pre>';
print_r($tableRows);//Print the table rows from array
echo '</pre>';

I've got:

Array
(
[0] => Array
    (
        [name] => John
        [age] => 28
        [birthplace] =>  NY

    )

[1] => Array
    (
        [name] => Marry
        [age] => 23
        [birthplace] =>  Prozent Rabatt
    )

[2] => Array
    (
        [name] => 45521
        [age] => Bekleidung
        [birthplace] =>  LD
    )

[3] => Array
    (
        [name] => Mohamad
        [age] => 34
        [birthplace] =>  Malaysia 
    )
)

I would like to change the keys name, age, birthplace to 0, 1, 2 respectively.

I have read this link: In PHP, how do you change the key of an array element? But it seems that I do not need it as the function because it looks so advanced to me.

I also read this link: PHP rename array keys in multidimensional array But it just meant to change one key in one array only as I tested for my case.

Your help is appreciated. Thanks,

1 Answer 1

1

using MYSQLI_ASSOC its return associative array if you replace it with MYSQLI_NUM in mysqli_fetch_array() it will return a result as you ask

$query = "SELECT name, age, birthplace FROM tableName";
$result = mysqli_query($dbc, $query);
$tableRows = array();
while($rows = mysqli_fetch_array($result,MYSQLI_NUM)){
   $tableRows[] = $rows; 
}

echo '<pre>';
print_r($tableRows);//Print the table rows from array
echo '</pre>';
Sign up to request clarification or add additional context in comments.

5 Comments

Oh, it returns Array ( [0] => Array ( [0] => John [name] => John [1] => 28 [age] => 28 ) ... ). That means each key is printed twice within its array. Any suggestion?
check it with MYSQLI_NUM. I also fix it in my answer
It throws an error like this Undefined index: name.
It works for me. is this your full code. if this is your full code try SQL query with SQL server because query can't find collum as a name it throws error like this

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.