Home > Backend Development > PHP Tutorial > Can MySQL's `mysql_` and `mysqli_` APIs Be Used Together in PHP?

Can MySQL's `mysql_` and `mysqli_` APIs Be Used Together in PHP?

Mary-Kate Olsen
Release: 2025-01-04 11:21:35
Original
381 people have browsed it

Can MySQL's `mysql_` and `mysqli_` APIs Be Used Together in PHP?

Can MySQL APIs Be Mixed in PHP?

Mixing MySQL APIs in PHP is not recommended. PHP provides two MySQL API extensions: mysql_ and mysqli_. These extensions are separate and their resources are incompatible.

The code you provided demonstrates the issue:

$con = mysqli_connect("localhost", "root" ,"" ,"mysql");

if( mysqli_connect_errno( $con ) ) {
    echo "failed to connect";
}else{
    echo "connected";
}

mysql_close($con);
echo "Done";
Copy after login

This code results in the following error:

Connected
Warning: mysql_close() expects parameter 1 to be resource, object given in D:\************.php on line 9
Done
Copy after login

This error occurs because mysql_close() expects a MySQL resource as input, but you are providing a mysqli resource.

Solution:

To resolve this issue, use only one MySQL API extension consistently throughout your code. If you are using the mysqli_ extension, use mysqli_connect() and mysqli_close() to open and close the connection. Similarly, if you are using the mysql_ extension, use mysql_connect() and mysql_close().

Checking Connection Validity:

Both mysql_connect_errno() and mysqli_connect_errno() can be used to check if the connection is valid. If the returned value is 0, the connection is valid. Otherwise, there is an error.

Example:

$con = mysqli_connect("localhost", "root" ,"" ,"mysql");

if( mysqli_connect_errno( $con ) ) {
    echo "failed to connect: " . mysqli_connect_error();
}else{
    echo "connected";
}
Copy after login

The above is the detailed content of Can MySQL's `mysql_` and `mysqli_` APIs Be Used Together in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template