Home >Backend Development >PHP Problem >How to query book title with PHP
As a web development language, PHP excels at querying databases. Today, we will introduce how to use PHP to query book titles in the database.
First, we need to connect to the database. In PhpMyAdmin, we can see the name of the database, username and password. Here is the basic code to connect to the database:
$servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检查连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully";
Now, we have successfully connected to the database. Next, we need to query the tables within it to get the data we need. The following is the basic code of the query table statement:
$sql = "SELECT * FROM books"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // 输出每行数据 while($row = mysqli_fetch_assoc($result)) { echo "书名: " . $row["title"]. "<br>"; } } else { echo "0 结果"; }
In the above code, we will query all books in the books table and output their titles. You can modify the query statement according to your own needs.
If you only need to query a specific book title, you can use the following code:
$sql = "SELECT * FROM books WHERE title='Book Name'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "书名: " . $row["title"]. "<br>"; } } else { echo "0 结果"; }
In the above code, we only query books with the title "Book Name".
You can also use PHP variables as query conditions. For example:
$bookname = "Book Name"; $sql = "SELECT * FROM books WHERE title='$bookname'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "书名: " . $row["title"]. "<br>"; } } else { echo "0 结果"; }
In this example, we use the $bookname variable as the query condition, and its value is "Book Name".
In short, it is very easy to use PHP to query book titles in the database. Just connect to the database and write your query to easily get the data you need.
The above is the detailed content of How to query book title with PHP. For more information, please follow other related articles on the PHP Chinese website!