JeepFreak
JeepFreak

Reputation: 107

Loading a whole mySQL table into a PHP array

I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).

The rows are:
ID
Category
Summary
Text

I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.

I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.

I really appreciate any help! Billy

Upvotes: 0

Views: 9664

Answers (3)

JeepFreak
JeepFreak

Reputation: 107

OK, I found my answer with better search terms. I'm still new here, so let me know if this is not a fair way to handle the situation. I upvoted @Indranil since he or she spent so much time trying to help me.

Anyway...

    $content = array();
    while($row = mysql_fetch_assoc($result)) {
      $content[$row['id']] = $row;
    }

Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code. And it even names the first level of the array by the ID (which is the unique identifier).

Thank you to those that tried to help me!
Billy

Upvotes: 3

tereško
tereško

Reputation: 58454

$pdo = new PDO( 
    'mysql:host=hostname;dbname=database;charset=utf-8', 
    'username', 
    'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
   $data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}

In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.

Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.

Upvotes: 1

Indranil
Indranil

Reputation: 2471

Just a SELECT * FROM table_name will select all the columns and rows.

$query = "SELECT * FROM table_name";
$result = mysql_query($query);

$num = mysql_num_rows($results);
if ($num > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        // You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
    }
}

Upvotes: 4

Related Questions