0

I want to fill array with this table data DataBase Table Data

like this Array //$student=array('user1'=>array(0=>'cs201',1=>'cs502'), // 'user2'=>array(0=>'mth201',1=>'mgt302'));

2 Answers 2

1

If you are using PDO you can use below code, but next time qive more specific information in question

$servername = "localhost";
$username = "username";
$password = "password";

$conn = new PDO("mysql:host=$servername;dbname=database_name", $username, $password);

$sth = $conn->query("SELECT * FROM table");
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

$finalResult = array();

if(is_array($result))
    foreach($result as $item)
        $finalResult[$item['UserName']][] = $item["Cources"];

echo "<pre>";
var_dump($finalResult);
echo "</pre>";
Sign up to request clarification or add additional context in comments.

Comments

0

Connect to your DB, then query the DB table and store the mysqli result in a variable. This will place the results of the query in an array with the variable name you declare. You can use a while loop to accomplish this.

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
  printf("Connect failed: %s\n", $mysqli->connect_error);
  exit();
}

$sql = "SELECT * FROM `table-name`";

if ($result = $mysqli->query($sql)) {

  /* fetch associative array */
  while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["St-ID"], $row["UserName"], $row["Cources"]);
  }
  /* free result set */
  $result->free();
}

This has not been tested and is just a basic structure as laid out in php manual. PHP Manual on fetch_assoc()

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.