MySQL output methods

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

MySQL output methods

Post by impulse() »

I know of two ways to output a query from a MySQL DB. Are there any other ways to do this other than:

Code: Select all

$query = mysql_query("SELECT something FROM somewhere");

while ($results = mysql_fetch_array($query)) {
  echo $results['something'];
}
And

Code: Select all

$query = mysql_query("SELECT something FROM somewhere");
$numRows = mysql_numrows($query);

for ($i = 0; $i < $numRows; $i++) {
$colOne = mysql_results($query, $i, "colName");
$colTwo = mysql_results)$query, $i, "colTwoName");
echo $colOne;
echo $colTwo;
}
Regards,
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Lots of. What are you looking for?
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

Post by impulse() »

Nothing inparticular. Just a few methods I can note down. I'm sure they'll come in useful in the future.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: MySQL output methods

Post by Luke »

This will give you an array of associative arrays with column names as keys and column values as values

Code: Select all

$records = array();
$query = mysql_query("SELECT something FROM somewhere");
while ($row = mysql_fetch_assoc($query)) {
    $records[] = $row;
}
I use a mysql result iterater written by d11wtq... and it's quite slick... (I'm building an active record library on top if it actually -- well it's kind of active record... it's hopefully not going to be quite as restrictive as Active Record usually is). It looks like this:

Code: Select all

require_once('DB.php');
require_once('DB_Result.php');

$db = new DB('localhost', 'user', 'pass', 'db_test');

/*
 create table foo
(
    id int auto_increment primary key,
    one varchar(255),
    two varchar(255)
)
 */

$result = $db->query("select * from foo");

//Go forwards through the resultset
for ($result->first(); !$result->end(); $result->next())
{
        echo $result->one.' '.$result->two.'<br />';
}
Post Reply