Home > Backend Development > PHP Problem > How to implement multi-table query in php

How to implement multi-table query in php

angryTom
Release: 2023-02-27 13:20:01
Original
6440 people have browsed it

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 = &#39;localhost&#39;;  // mysql服务器主机地址
$dbuser = &#39;root&#39;;            // mysql用户名
$dbpass = &#39;root&#39;;          // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die(&#39;连接失败: &#39; . mysqli_error($conn));
}
// 执行查询
?>
Copy after login

2. Execute multi-table query statements

// 设置编码,防止中文乱码
mysqli_query($conn , "set names utf8");
 
 // 多表查询
$sql = &#39;select * from table1,table2&#39;;
 
mysqli_select_db( $conn, &#39;DEMO&#39; );
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
    die(&#39;无法读取数据: &#39; . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
    echo $row;
}
mysqli_close($conn);
Copy after login

More multi-table query methods:

1. Ordinary method

select * from table1,table2
Copy after login

2. left join right join Waiting method

select * from table1 t1 left join table2 t2 on t1.id = t2.id
Copy after login

3, UNION method

select * from table1 union select * from table2
Copy after login

4, Nested query method

select * from table1 where id in (select pid from table2 where pid > 10)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template