note 53525 added to function.mysql-list-fields
| From: | rhyous at yahoo dot com | Date: | Sat, 04 Jun 2005 22:22:47 +0000 |
| Subject: | note 53525 added to function.mysql-list-fields | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89924@lists.php.net to get a copy of this message | ||
To make an array containing the names of a column from a table, you use the following simple script:
(Note: using table1 with three columns)
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql
error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
$colname = mysql_fetch_row($qColumnNames);
$col[$colname[0]] = $colname[0];
$x++;
}
print_r($col);
/* it will have the following output
Array (
[firstcolumn] => firstcolumn
[secondcolumn] => secondcolumn
[thirdcolumn] => thirdcolumn
)
*/
Or you can number the columns from zero. This help when using it in conjunction with
mysql_fetch_row to get an array. You don't have to remember which number of the array a
certain column is.
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql
error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
$colname = mysql_fetch_row($qColumnNames);
$col[$colname[0]] = $x;
$x++;
}
print_r($col);
/* it will have the following output
Array (
[firstcolumn] => 0
[secondcolumn] => 1
[thirdcolumn] => 2
)
*/
To use it in conjuction with mysql_fetch_row:
$row = mysql_fetch_row("SELECT * from table1",$db) or die("mysql error");
You can now call $row[col[firstcolumn]]. This becomes useful when you have a lot of columns.
----
Manual Page -- http://www.php.net/manual/en/function.mysql-list-fields.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53525
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53525&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53525&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53525&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53525&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53525&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53525&report=yes
Search -- http://master.php.net/manage/user-notes.php