New mysqli php
Here is an example of how to use the mysqli
extension in PHP to connect to a MySQL database and perform queries:
Connecting to the database
<?php
// Create a new mysqli object
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (". $mysqli->connect_errno. ") ". $mysqli->connect_error;
exit();
}
?>
In this example, we create a new mysqli
object and pass in the following parameters:
localhost
: the hostname or IP address of the MySQL serverusername
: the username to use for the connectionpassword
: the password to use for the connectiondatabase
: the name of the database to connect to
We then check the connection using the connect_errno
and connect_error
properties of the mysqli
object. If the connection fails, we display an error message and exit the script.
Performing a query
<?php
// Perform a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
// Check if the query was successful
if (!$result) {
echo "Query failed: (". $mysqli->errno. ") ". $mysqli->error;
exit();
}
// Fetch the results
while ($row = $result->fetch_assoc()) {
echo $row["username"]. "\n";
}
// Free the result set
$result->free();
?>
In this example, we perform a query using the query
method of the mysqli
object. We pass in the query string as a parameter.
We then check if the query was successful using the errno
and error
properties of the mysqli
object. If the query failed, we display an error message and exit the script.
If the query was successful, we fetch the results using the fetch_assoc
method of the mysqli_result
object. We loop through the results and print out the values.
Finally, we free the result set using the free
method of the mysqli_result
object.
Closing the connection
<?php
// Close the connection
$mysqli->close();
?>
In this example, we close the connection using the close
method of the mysqli
object.
Error handling
The mysqli
extension provides several ways to handle errors, including:
mysqli::connect_errno
: returns the error number of the last connection attemptmysqli::connect_error
: returns the error message of the last connection attemptmysqli::errno
: returns the error number of the last query attemptmysqli::error
: returns the error message of the last query attempt
You can use these properties to check for errors and display error messages to the user.
Security considerations
When using the mysqli
extension, it's important to take steps to secure your database connection and queries. Here are a few best practices to keep in mind:
- Use prepared statements to prevent SQL injection attacks
- Use parameterized queries to prevent SQL injection attacks
- Use secure passwords and avoid hardcoding them in your code
- Limit the privileges of the database user account used by your script
- Use a secure connection (e.g. SSL/TLS) to encrypt data in transit