Search code examples
phpmysqlarraysmultidimensional-array

How to save a query result set as an array?


I have stored the data in a mysql database, I want to know how I can split the data in each different array before output them in php?

<?php
  define('DB_HOST', 'localhost');
  define('DB_USER', 'myusername');
  define('DB_PASSWORD', 'mypassword');
  define('DB_DATABASE', 'mydbname');   

  $errmsg_arr = array();
  $errflag = false;
  $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

   if(!$link)
  {
    die('Failed to connect to server: ' . mysql_error());
  }
  $db = mysql_select_db(DB_DATABASE);

  if(!$db)
  {
    die("Unable to select database");
  }


  if($errflag)
  {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    echo implode('<br />',$errmsg_arr);
  }
  else
  {
    $qrytable1="SELECT id, mydata FROM mydb ";
    $result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());

     while ($row = mysql_fetch_array($result1))
    {
      echo "<tr><td>".$row['mydata']."</td></tr>";
    }
  }
?>

On my PHP page it show something like this:

<tr><td>my data 1</td></tr><tr><td>my data 2</td></tr><tr><td>my data 3</td></tr><tr><td>my data 4</td></tr>

I want to split them up by turn into array and output them with each different array to something like this:

mydata1

mydata2

mydata3

mydata4

How I can split the data into array before I could output them in my php?


Solution

  • Are you looking for something like this?

    (consider it as an example, but, as @BenM, consider using PDO)

    $sql = 'SELECT * FROM country';
    $query = mysql_query($sql);
    $countries = array();
    while ($country = mysql_fetch_assoc($query)){ $countries[] = $country; }
    

    This will allow you to use

    foreach ($countries as $country) {
        echo $country['name'];
    }