Home >Backend Development >PHP Problem >How to implement multi-table query in php
How to implement multi-table query in php
Multi-table joint query means that the result of the query needs to be multiple table contents, and establish their relationship as a temporary table.
Multi-table joint query cannot be indexed to optimize the query speed, so it is generally not recommended to use it.
1. Use mysqli_connect to connect to the database
<?php header("Content-Type: text/html;charset=utf-8"); $dbhost = 'localhost'; // mysql服务器主机地址 $dbuser = 'root'; // mysql用户名 $dbpass = 'root'; // mysql用户名密码 $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('连接失败: ' . mysqli_error($conn)); } // 执行查询 ?>
2. Execute multi-table query statements
// 设置编码,防止中文乱码 mysqli_query($conn , "set names utf8"); // 多表查询 $sql = 'select * from table1,table2'; mysqli_select_db( $conn, 'DEMO' ); $retval = mysqli_query( $conn, $sql ); if(! $retval ) { die('无法读取数据: ' . mysqli_error($conn)); } while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) { echo $row; } mysqli_close($conn);
More multi-table query methods:
1. Ordinary method
select * from table1,table2
2. left join right join Waiting method
select * from table1 t1 left join table2 t2 on t1.id = t2.id
3, UNION method
select * from table1 union select * from table2
4, Nested query method
select * from table1 where id in (select pid from table2 where pid > 10)
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to implement multi-table query in php. For more information, please follow other related articles on the PHP Chinese website!