In this tutorial, you will learn some fundamental PHP MySQL functions and perform various operations on a database.
PHP MySQL Connect Function
PHP provides the mysqli_connect function that allows you to establish a connection to the MySQL server.
The following example shows how to use the mysqli_connect function.
$SERVERNAME = "localhost";
$USERNAME = "root";
$PASS = "password";
$DB = "db_name";
$conn = new mysqli($SERVERNAME, $USERNAME, $PASS, $DB);
if ($conn->connect_error) {
die("Connection fail...[Error!]" . $conn->connect_error);
}
echo "Connection Established...[OK]"
?>
The function accepts the hostname, username, and password to the MySQL cluster. You can also pass the target database to use.
PHP MySQL Select_DB Function
The following important function you need to be aware of is the select_db function.
The function takes the syntax as shown below:
You pass the name of your target database where the specified queries will be executed. It returns a Boolean true or false if the operation is successful or fails.
PHP MySQL Close Function
The MySQLi Close function allows you to close an already opened connection to the database.
The function takes a simple syntax as:
PHP MySQL Query Function
The MySQLi query function is convenient. It is used to execute queries on a database. It executed CRUD queries on the database such as Insert, Select, Update, and Delete.
The function syntax is as shown:
PHP MySQL num_rows Function
The PHP mysqli_num_rows function is a simple built-in function that returns the number of rows from a query. It accepts a result from a specified query and returns the number of rows.
The syntax of the function can be expressed as:
PHP MySQL fetch_array Function
This is another beneficial function that returns the result of a query as an array. It can produce a numerical or associative array.
The syntax of the function is as:
You can learn more about how to use this function by checking our tutorial on this topic.
PHP MySQL change_user Function
As the name suggests, this function is used to change the user of the specified connection to a database.
The syntax as is:
The function takes the target username, password, and database to use.
PHP MySQL connect_error Function
This function returns a description of the error from the last connection. It is handy when you want to display messages about connections to the database.
The syntax is as:
if ($conn->connect_error) {
die("Connection fail...[Er]" . $conn->connect_error);
PHP MySQL Info Function
The info function returns the information about the last query in the database.
Conclusion
This guide provides you with the basics of PHP MySQL functions and how to interact with MySQL databases.
Thank you for reading.