相关免费学习推荐:mysql视频教程
数据库中有数据表hacker,现在我们要将hacker表中的数据查询出来并在页面上显示,代码如下:<?php
// 连接数据库
$mysqli = mysqli_connect("localhost","root","123",'student'); //mysqli_close($con);
$mysqli ? print 'yes!
':print "no!
";
$sql = $mysqli -> query('use student');
$sql = $mysqli -> query('set name utf8');
// 创建数据表
$sql = $mysqli -> query("create table hacker(
id char(6) not null,
name char(8) not null,
chinese float not null,
math float not null,
english float not null
)");
if($sql == true){
echo '成功创建hacker表!
';
}else{
echo '创建hacker表失败!'.$mysqli->error.'
';
}
// 添加数据——hacker
// $sql = "insert into hacker values('1','张三','10','20','30');";
// $sql .= "insert into hacker values('2','李四','66','77','88');";
// $sql .= "insert into hacker values('3','王二','55','44','33');";
// $sql .= "insert into hacker values('4','麻子','22','55','77')";
// $rows = $mysqli->affected_rows;
// if($rows == 3){
// echo "添加数据成功。
";
// }else{
// echo '添加失败。'.$mysqli->error."
";
// }
$sql = $mysqli -> query("insert into hacker
values('2','李四','66','77','88')
");
$rows = $mysqli->affected_rows;
if($rows == 1){
echo "添加数据成功。
";
}else{
echo '添加失败。'.$mysqli->error."
";
}
$sql = $mysqli -> query("insert into hacker
values('3','王二','55','44','33')
");
$rows = $mysqli->affected_rows;
if($rows == 1){
echo "添加数据成功。
";
}else{
echo '添加失败。'.$mysqli->error."
";
}
$sql = $mysqli -> query("insert into hacker
values('4','麻子','22','55','77')
");
$rows = $mysqli->affected_rows;
if($rows == 1){
echo "添加数据成功。
";
}else{
echo '添加失败。'.$mysqli->error."
";
}
// 数据查询
$sql = $mysqli->query("select * from hacker");
if($sql){
// echo '有数据!
';
$rows = $sql->num_rows;
echo '查询结果共有'.$rows.'条记录
';
echo "
序号 | 姓名 | 语文 | 数学 | 英语 |
---|
";
if($rows){
while($row = $sql->fetch_assoc()){
// echo 'id = '.$row['id'].'
name = '.$row['name'].'
chinese = '.$row['chinese'].'
math = '.$row['math'].'
english = '.$row['english'].'
';
echo "
".$row['id']."".$row['name']."".$row['chinese']."".$row['math']."".$row['english']."";
}
echo "
";}else{
echo '没有您要找的数据。
';
}
}else{
echo 'MySQL语句有误。
'.$mysqli->error.'
';
}?>