In PHP, using MySQL databases for data manipulation is a very common requirement. The mysqli extension provides two ways to use process-oriented and object-oriented. The most basic operation is to establish a database connection through the connect() function, and then execute SQL statements using the mysqli_query() function. This article will introduce how to implement database connections and operations with mysqli_connect() and mysqli_query() functions.
mysqli_connect() is used to connect to the MySQL database server. Its commonly used parameters include: server address, user name, password, database name and port number. Examples are as follows:
<?php
$host = 'localhost'; // Database server address
$user = 'root'; // Database username
$pass = 'password'; // Database Password
$dbname = 'testdb'; // Database name
// Establish a connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
// Determine whether the connection is successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connection successfully";
?>
This code tries to connect to the MySQL database server, terminates if it fails and outputs an error message.
After the connection is successful, use the mysqli_query() function to execute SQL statements, such as query, insert, update and delete operations. The first parameter is the connection resource, and the second parameter is the SQL statement string.
Example: Query data
<?php
$sql = "SELECT * FROM users"; // Query statement
$result = mysqli_query($conn, $sql);
if ($result) {
// Iterate over the result set
while ($row = mysqli_fetch_assoc($result)) {
echo "username: " . $row['username'] . "<br>";
}
mysqli_free_result($result); // Release the result set
} else {
echo "Query failed: " . mysqli_error($conn);
}
?>
<?php
$sql = "INSERT INTO users (username, email) VALUES ('Zhang San', 'zhangsan@m66.net')";
if (mysqli_query($conn, $sql)) {
echo "Insert successfully,IDfor: " . mysqli_insert_id($conn);
} else {
echo "Insert failed: " . mysqli_error($conn);
}
?>
Here is a demonstration of how to insert a piece of data into the users table. Note that the domain name of the mailbox in the example has been replaced with m66.net .
After the operation is completed, it is best to close the database connection:
<?php
mysqli_close($conn);
?>
Use mysqli_connect() to establish a database connection;
Use mysqli_query() to execute SQL statements to implement the operation of adding, deleting, modifying and searching;
By judging the return value of the function, capture and process error information;
Release the result set in time and close the connection to ensure the effective utilization of resources.
Mastering the combination of these two functions can meet most basic database operation needs.