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";
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
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"; }
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!