With the continuous development of the Internet, the application of databases is becoming more and more widespread. As a server-side scripting language, PHP provides many practical functions when processing database data. Let's take a look at several database processing functions commonly used in PHP.
This function is used to connect to the MySQL database. Before using this function, you need to install MySQL and create the corresponding database. The specific code is as follows:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully";
This function is used to execute SQL query statements. The specific code is as follows:
$sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>"; } } else { echo "0 results"; }
This function is used to return the ID generated by the last insert operation. The specific code is as follows:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@gmail.com')"; $result = mysqli_query($conn, $sql); $id = mysqli_insert_id($conn); echo "New record created successfully. Last inserted ID is: " . $id;
This function is used to return the number of rows affected by the last SQL query. The specific code is as follows:
$sql = "UPDATE users SET name='Jack' WHERE id=1"; $result = mysqli_query($conn, $sql); $affected_rows = mysqli_affected_rows($conn); echo "Affected rows: " . $affected_rows;
This function is used to close the connection with the MySQL database. The specific code is as follows:
mysqli_close($conn);
The above are several database processing functions commonly used in PHP. With the help of these practical functions, we can easily connect to the database, perform SQL queries, insert data, return IDs and other operations, which provides convenience and convenience for the development of database applications.
The above is the detailed content of Database processing function of PHP function. For more information, please follow other related articles on the PHP Chinese website!