PHP与数据库的连接以及操作

mysql中如何将两个表关联查询;或者是3个表关联查询:

/数据库中如何查两张表/

select user.name ,goods.price from user join goods on user.gid=goods.gid;

select from user where gid in (select gid grom goods);
select
from user where gid in (1,2,3);

/数据库中,三张表/

有表:学生表(学号,姓名,性别,年龄),课程表(课程号,课程名),修课表(学号,课程号,成绩)

SELECT 姓名,课程名,成绩
FROM 学生表 JOIN 修课表 ON 学生表.学号=修课表.学号
JOIN 课程表 ON 课程表.课程号=修课表.课程号
WHERE 成绩>80

PHP连接数据库一共有8步:

1 连接数据库:

$link=mysqli_connect('localhost','root','');
//var_dump($link);

2 判断是否连接成功

if(!$link){
    exit('数据库连接失败');
}

3 设置字符集

mysqli_set_charset($link,"utf8");

4 选择数据库

mysqli_select_db($link,'acc');

5 准备sql语句

$sql="select * from pro ";

6 发送数据语句

$res=mysqli_query($link,$sql);
var_dump($res);

7 处理结果集

$result=mysqli_fetch_assoc($res);
var_dump($result);

8 关闭数据库

mysqli_close($link);

相关代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
header("content-type:text/html;charset=utf-8");
$line=mysqli_connect("localhost","root","");
if(!$line){
exit("数据库连接失败");
}
mysqli_set_charset($line,"utf8");
$bd=mysqli_select_db($line,"acc");
$str="select * from pro1";
$res=mysqli_query($line,$str);
echo '<table width="600" border="1">';
echo '<th>编号</th><th>用户名</th><th>资金</th><th>性别</th><th>操作</th>';
while($rows=mysqli_fetch_assoc($res)){
echo '<tr>';
echo '<td>'.$rows['id'].'</td>';
echo '<td>'.$rows['name'].'</td>';
echo '<td>'.$rows['age'].'</td>';
echo '<td>'.$rows['sex'].'</td>';
echo '<td><a href="del.php?id='.$rows['id'].'">删除</a><a href="update.php?id='.$rows['id'].'">修改</a></td>';
echo '</tr>';
}
echo "</table>";
mysqli_close($line);
Fork me on GitHub