0

Additional Information 1) I have multiple records (name, age, gender), ((John, 10, Male), (Sally, 9, Female), (Jack, 12, Male)).

2) All these records are in a database.

3) I want to add these records into an array automatically with a while loop.

I tried to submit my codes with these question but it prompt that it is not properly formatted. Please help. Most welcome to give u more information if needed.

1 Answer 1

1

Try:

foreach ($con->query("SELECT * FROM table") as $row){
    $arr[] = array(
        "name" => $row['name'],
        "age" => $row['age'],
        "gender" => $row['gender']
    );
}

Where $con is your connection, table is your table name ...

Then if you var_dump $arr you'll see array structure something like this =>

array (size=n) // n number of array in $arr
  0 => 
    array (size=3)
      'name' => string 'John' (length=7)
      'age' => string '10' (length=2)
      'gender' => string 'Male' (length=4)
  1 => 
    array (size=3)
      'name' => string 'Sally' (length=7)
      'age' => string '10' (length=2)
      'gender' => string 'Female' (length=4)
  2 => 
    array (size=3)
      'name' => string 'Other' (length=7)
      'age' => string '10' (length=2)
      'gender' => string 'Male' (length=4)
  // etc ...
Sign up to request clarification or add additional context in comments.

3 Comments

What if I have a WHERE clause, how does it look like? Example, I tried adding WHERE age = '9' but when I var_dump the arr, every records still came up. Next, my string all is NULL, ["class_id"]=> NULL ["student_id"]=> NULL ["result_marks"]=> NULL
@user1436885 If you write WHERE age=9 all records (that have age equal to 9) will return. And please write more carefully next question ...
@user1436885 if your age column type is INT you mustn't use '' , otherwise if you have type VARCHAR you have to

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.