Mixing MySQL APIs in PHP
The MySQL PHP API provides two interfaces for interacting with MySQL databases: mysql_ and mysqli_. While it may seem convenient to mix these APIs, this practice is strictly discouraged.
Cannot Mix APIs
Fundamentally, mysql_ and mysqli_ are separate APIs with distinct architectures and incompatible resource types. As such, you cannot use functions from one API on resources created by the other.
Example Error
The example code provided demonstrates the issue when attempting to mix the two APIs:
$con=mysql_connect("localhost", "root" ,"" ,"mysql"); if( mysqli_connect_errno( $con ) ) { echo "failed to connect"; }else{ echo "connected"; } mysqli_close($con); // Error: Incompatible resource type
This code attempts to use mysqli_connect_errno() on a resource created by mysql_connect(), resulting in a mismatch.
Checking Connection Validity
To check whether a connection is valid, use the corresponding API's error reporting function:
Conclusion
It is essential to adhere to API boundaries when working with different MySQL interfaces. Using incompatible functions or resources can lead to errors and unpredictable behavior.
The above is the detailed content of Why Should I Avoid Mixing `mysql_` and `mysqli_` APIs in PHP?. For more information, please follow other related articles on the PHP Chinese website!