PHP is a commonly used server-side scripting language that is widely used in web development. In the process of web development, it is often necessary to interact with the database, and query statements are a crucial part of it. This article will introduce the advanced application guide of query statements in PHP, including connecting to the database, executing queries, processing results, etc., and provide specific code examples for reference.
In PHP, connecting to the database is the first step in the query statement. Normally, we use the two extensions PDO (PHP Data Objects) or mysqli (MySQL Improved) to connect to the database.
$host = 'localhost'; $dbname = 'mydatabase'; $username = 'root'; $password = ''; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
$host = 'localhost'; $dbname = 'mydatabase'; $username = 'root'; $password = ''; $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully";
After successfully connecting to the database, you can then execute the query statement to obtain required data.
$sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; }
After executing a query, the results usually need to be further processed, such as outputting to a page or performing other operations.
echo "<table border='1'>"; echo "<tr><th>Name</th><th>Email</th></tr>"; if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "<tr><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>"; } } else { echo "<tr><td colspan='2'>0 results</td></tr>"; } echo "</table>";
Through the introduction of this article, readers can understand how to apply query statements in PHP at an advanced level, including connecting to the database, executing queries, and processing results. etc., and learned specific code examples. In actual projects, proper use of these techniques can make data interaction more efficient and stable. Hope this article is helpful to readers!
The above is the detailed content of Advanced Application Guide for PHP Query Statements. For more information, please follow other related articles on the PHP Chinese website!