I have the following schema of the database,
CREATE TABLE `tz_todo` (
`id` int(8) unsigned NOT NULL auto_increment,
`position` int(8) unsigned NOT NULL default '0',
`text` varchar(255) collate utf8_unicode_ci NOT NULL default '',
`dt_added` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `position` (`position`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
If I am writing the following PHP statement,
$query = mysql_query("SELECT * FROM `tz_todo` ORDER BY `position` ASC");
How I access the text items inside $query?
Please guide. Thanks
UPDATE: I have tried this,
echo $query['id'];
echo $query['position'];
echo $query['text'];
Attempting to print $query won't allow access to the information. One of the mysql result functions must be used: mysql_fetch_assoc(), mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
This is an example of how you would access your results using mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['position'];
echo $row['text'];
echo $row['dt_added'];
}
It is good practice to first check if there are any results returned, below is an example of how you could do that:
if (!$query) {
//do stuff when there is no data returned
}
NOTE: mysql_query is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL should be used.
This is covered, in reasonably simple terms, in the documentation. (Do note that you are recommended to move away from the mysql_query
family of commands.)
The basic approach is to iterate over the results in the following manner.
$query = mysql_query( ...
while ($row = mysql_fetch_assoc($query))
{
do something
}