一次偶然的机会,一客户代码基于PHP5开发,发给我处理代码问题,无耐本地测试环境早已升级成了PHP7,打开页面就报如下错误:
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in dir/index.php:8 Stack trace: #0 {main} thrown in dir/index.php on line 8
很明显,PHP7已经抛弃了mysql_connect,如何兼容呢?下面贴出兼容代码:
<?php if(!function_exists('mysql_connect')){ function mysql_connect($dbhost, $dbuser, $dbpass){ global $dbport; global $dbname; global $mysqli; $mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); return $mysqli; } function mysql_select_db($dbname){ global $mysqli; return mysqli_select_db($mysqli,$dbname); } function mysql_fetch_array($result){ return mysqli_fetch_array($result); } function mysql_fetch_assoc($result){ return mysqli_fetch_assoc($result); } function mysql_fetch_row($result){ return mysqli_fetch_row($result); } function mysql_query($query){ global $mysqli; return mysqli_query($mysqli,$query); } function mysql_escape_string($data){ global $mysqli; return mysqli_real_escape_string($mysqli, $data); } function mysql_real_escape_string($data){ return mysql_real_escape_string($data); } function mysql_close(){ global $mysqli; return mysqli_close($mysqli); } }
注意,上面$dbhost可能需要带正确的端口。