php如何取数据库中内容
推荐于2018-03-22 · 知道合伙人软件行家
试编写代码如下:
<?php
//从数据库根据 id 获取颜色
function getColor($db, $id)
{
if ($result = $db->query("SELECT * FROM color where id='" . $id . "'"))
{
$row = $result->fetch_assoc();
return $row['color'];
}
return '#000000';
}
$mysqli = new mysqli("localhost", "test", "test", "room");
if ($mysqli->connect_error) {
printf("数据库连接错误: %s\n", mysqli_connect_error());
exit();
}
?>
<table border="1" cellspacing="0">
<tr>
<td bgcolor="<?php echo getColor($mysqli,'1')?>">1</td>
</tr>
<tr>
<td bgcolor="<?php echo getColor($mysqli,'2')?>">2</td>
</tr>
<tr>
<td bgcolor="<?php echo getColor($mysqli,'3')?>">3</td>
</tr>
</table>
<?php
$mysqli->close();
?>
你用的什么数据库?如果使用mysql,建议参照以下代码试试。
<?php
//定义常量
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASS, '111111');
define(DB_DATABASENAME, 'room');
define(DB_TABLENAME, 'color');
//数据库表的列名
$dbcolarray = array('id', 'color');
//mysql_connect
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("connect failed" . mysql_error());
mysql_select_db(DB_DATABASENAME, $conn);
//读取表中纪录条数
$sql = sprintf("select count(*) from %s", DB_TABLENAME);
$result = mysql_query($sql, $conn);
if ($result)
{
$count = mysql_fetch_row($result);
}
else
{
die("query failed");
}
echo "表中有$count[0] 条记录<br />";
$sql = sprintf("select %s from %s", implode(",",$dbcolarray), DB_TABLENAME);
$result = mysql_query($sql, $conn);
//表格
echo '<table id="Table" border=1 cellpadding=10 cellspacing=2 bordercolor=#ffaaoo>';
//表头
$thstr = "<th>" . implode("</th><th>", $dbcolarray) . "</th>";
echo $thstr;
//表中的内容
while ($row=mysql_fetch_array($result, MYSQL_ASSOC))//与$row=mysql_fetch_assoc($result)等价
{
echo "<tr>";
$tdstr = "";
foreach ($dbcolarray as $td)
$tdstr .= "<td>$row[$td]</td>";
echo $tdstr;
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
mysql_close($conn);
$mysqli = new mysqli("localhost", "test", "test", "room");
if ($mysqli->connect_error) {
printf("数据库连接错误: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SELECT id,color FROM `room`");
?>
<table border="1" cellspacing="0">
<?php
foreach($row = $result->fetch_assoc()){
?>
<tr>
<td bgcolor="<?php echo $row['color']; ?>"><?php echo $row['id']; ?></td>
</tr>
<tr>
<?php
}
?>
</table>
<?php
$mysqli->close();
?>