PHP is a very popular server-side scripting language that can connect and interact with various types of databases. Whether you are developing a website, web application or processing data, you need to use a database. This article will summarize some commonly used PHP functions that can help you connect and manipulate databases.
This function is used to connect to the MySQL database and returns a connection object. It requires passing 4 parameters: database host name, user name, password and database name. The sample code is as follows:
$host = "localhost"; $username = "root"; $password = ""; $dbname = "test"; $conn = mysqli_connect($host, $username, $password, $dbname); if (!$conn) { die("连接失败: " . mysqli_connect_error()); }
This function is used to close the open database connection. The sample code is as follows:
mysqli_close($conn);
This function is used to send SQL queries or commands to the MySQL database. The sample 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>"; } }
This function is used to return the number of rows in the result set. The sample code is as follows:
$num_rows = mysqli_num_rows($result); echo "总共有 " . $num_rows . " 条记录。";
This function is used to return a row from the result set as an associative array. You can use this function to retrieve query results row by row. The sample code is as follows:
while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; }
This function is used to return a row from the result set as an associative array or a numeric array. The sample code is as follows:
while ($row = mysqli_fetch_array($result)) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; }
This function is used to return the ID number of the last inserted record. The sample code is as follows:
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@example.com')"; if (mysqli_query($conn, $sql)) { $last_id = mysqli_insert_id($conn); echo "新纪录插入成功,最后插入的记录ID是: " . $last_id; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
Summary
The above are some PHP functions related to database connection. These functions can be used to connect to the database, execute queries, obtain data, and perform other common operations. They are essential tools for working with databases. Whether you are accessing MySQL, SQLite, Oracle, or another database, these functions are universal and can help you manage and manipulate your data.
The above is the detailed content of Summary of common functions for connecting to database in PHP. For more information, please follow other related articles on the PHP Chinese website!