Home >Backend Development >PHP Tutorial >Why Should I Avoid Mixing `mysql_` and `mysqli_` APIs in PHP?

Why Should I Avoid Mixing `mysql_` and `mysqli_` APIs in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 04:38:11304browse

Why Should I Avoid Mixing `mysql_` and `mysqli_` APIs in PHP?

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:

  • mysql_: mysqli_connect_error() or mysqli_connect_errno()
  • mysqli_: mysqli_error() or mysqli_errno()

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!

Statement:
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