php学习笔记--3(连接mysql并查询结果)

DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `age` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `person` VALUES ('1', '张三', '20');
INSERT INTO `person` VALUES ('2', '李四', '30');
INSERT INTO `person` VALUES ('3', '王五', '50');


<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>mysql查询</title>
</head>

<body>

<?php
$host = "localhost";//服务器地址
$user = "root";//mysql用户名称
$password = "";//mysql用户密码
$conn=mysql_connect($host,$user,$password);  
if(!$conn) echo "<h1>失败!</h1>";
else echo "<h1>成功!</h1>";
?>
<table width="300" height="32" border="1" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" align="center">姓名:</td>
    <td width="50" align="center">年龄</td>
  </tr> 
<?php
mysql_select_db("php", $conn);
mysql_query("SET NAMES gbk");//指定数据库字符集,一般放在连接数据库后面
$result = mysql_query("SELECT * FROM person");//结果集
//迭代结果集 并显示
while($row = mysql_fetch_array($result))
  {
  echo "  
 <tr>
    <td align=\"center\">".$row['name']."</td>
    <td>".$row['id']."</td>
  </tr>"; 
  }
//释放资源
mysql_free_result($result);//释放结果级
mysql_close($conn);//释放连接
?> 
</table>
</body>
</html> 

你可能感兴趣的:(java,PHP,mysql)