note 96075 modified in function.mysql-fetch-array by danbrown
| From: | danbrown@php.net | Date: | Mon, 08 Feb 2010 13:57:09 +0000 |
| Subject: | note 96075 modified in function.mysql-fetch-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165750@lists.php.net to get a copy of this message | ||
Hey this is a simple function where you pass your table name and any number of coloumns you want and
it will fetch the coloumns and return as a table.
<?php
//function
function fetch_records($table_name, $fields){
$conn = mysql_connect("localhost", "root", "");
$select_db = mysql_select_db("db", $conn);
if(!$conn){
return "Not able to connect to dabase....";
}
$table = "<table border='0' cellpadding='5'
cellspacing='5'>";
$cols = implode (', ', $fields);
$sql = "select $cols from $table_name";
$run = mysql_query($sql);
if($run){
if(mysql_num_rows($run) == 0){
return "Sorry. No records found in the database";
}
else {
while($arr = mysql_fetch_array($run, MYSQL_ASSOC)){
$table .= "\t\t<tr>\n";
foreach ($arr as $val_col) {
$table .=
"\t\t\t".'<td>'.$val_col.'</td>'."\n";
}
$table .= "\t\t</tr>\n";
}
$table .= "</table>";
return $table;
}
mysql_free_result($run);
}
return "There was an error while fetching the records. Please contact site
administrator.";
}
//how to call the function
$table = "product_master";
$cols = array("product_name", "product_image", "product_price");
echo fetch_records($table, $cols);
?>
--was--
Hey this is a simple function where you pass your table name and any number of coloumns you want and
it will fetch the coloumns and return as a table.
//function
function fetch_records($table_name, $fields){
$conn = mysql_connect("localhost", "root", "");
$select_db = mysql_select_db("db", $conn);
if(!$conn){
return "Not able to connect to dabase....";
}
$table = "<table border='0' cellpadding='5'
cellspacing='5'>";
$cols = implode (', ', $fields);
$sql = "select $cols from $table_name";
$run = mysql_query($sql);
if($run){
if(mysql_num_rows($run) == 0){
return "Sorry. No records found in the database";
}
else {
while($arr = mysql_fetch_array($run, MYSQL_ASSOC)){
$table .= "\t\t<tr>\n";
foreach ($arr as $val_col) {
$table .=
"\t\t\t".'<td>'.$val_col.'</td>'."\n";
}
$table .= "\t\t</tr>\n";
}
$table .= "</table>";
return $table;
}
mysql_free_result($run);
}
return "There was an error while fetching the records. Please contact site
administrator.";
}
//how to call the function
$table = "product_master";
$cols = array("product_name", "product_image", "product_price");
echo fetch_records($table, $cols);
http://php.net/manual/en/function.mysql-fetch-array.php