
请点击输入图片描述
新建一个php文件,命名为test.php,用于讲解php如何选择要 *** 作的数据库。
请点击输入图片描述
在test.php文件中,使用header()方法将页面的编码格式设置为utf-8,避免输出中文乱码。
请点击输入图片描述
在test.php文件中,使用mysql_connect()函数,通过账号和密码创建一个数据库的连接。
请点击输入图片描述
在test.php文件中,再使用mysql_select_db()函数选择要 *** 作的数据库test,选择数据库成功,则返回true,否则,返回false。最后,通过if语句判断结果。
请点击输入图片描述
在浏览器打开test.php文件,查看结果。
请点击输入图片描述
END
总结:
1、创建一个test数据库。
2、使用mysql_connect()函数创建一个数据库的连接。
3、再使用mysql_select_db()函数选择要 *** 作的数据库test,并通过if语句判断结果。
试编写代码如下:
<?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()
?>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)