Home > Article > Backend Development > How to perform database queries using PHP built-in functions?
PHP built-in functions can be used to execute database queries, including: mysqli_query(): executes queries and returns results. PDOStatement: Prepare queries and bind parameters to prevent SQL injection. mysqli_affected_rows(): Get the number of rows affected by the query (using mysqli). PDOStatement::rowCount(): Gets the number of rows affected by the query (using PDO). mysqli_close(): Close the mysqli database connection. PDO: Automatically close the PDO connection after the script is executed.
Use PHP built-in functions to perform database queries
PHP provides a large number of built-in functions that can be used to perform database queries. This article explains how to use some commonly used PHP database built-in functions and provides practical examples.
Required tools:
Connect to the database:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "databasename"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { die("连接失败:" . $e->getMessage()); }
Use mysqli_query() function query:
$sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql);
Get query results:
if ($result) { while($row = $result->fetch(PDO::FETCH_ASSOC)) { echo "ID: " . $row["id"]. " 姓名: " . $row["name"]. "<br>"; } }
Use pdo to query data:
How to use this function Similar to the mysqli_query() function, but a PDOStatement object needs to be prepared in advance.
$stmt = $conn->prepare($sql); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "ID: " . $row["id"]. " 姓名: " . $row["name"]. "<br>"; }
Use pdo for prepared queries:
Prepared queries allow you to bind parameters to prevent SQL injection.
$sql = "INSERT INTO users (name, email) VALUES (?, ?)"; $stmt = $conn->prepare($sql); $stmt->execute([$name, $email]);
Use mysqli_affected_rows() Get the number of affected rows:
$num_rows = mysqli_affected_rows($conn); echo "受影响的行数:" . $num_rows;
Use PDO Get the number of affected rows Number of rows affected:
$num_rows = $stmt->rowCount(); echo "受影响的行数:" . $num_rows;
Use mysqli_close() Close the database connection:
mysqli_close($conn);
Use PDO Close the database connection:
There is no need to manually close the PDO connection. When the script is finished executing, it will automatically close.
The above is the detailed content of How to perform database queries using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!