话不多说, 直接上代码
<br />
<font size='1'><table class='xdebug-error xe-deprecated' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )span> Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\unit1\json1.php on line <i>5i>th>tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stackth>tr>
<tr><th align='center' bgcolor='#eeeeec'>#th><th align='left' bgcolor='#eeeeec'>Timeth><th align='left' bgcolor='#eeeeec'>Memoryth><th align='left' bgcolor='#eeeeec'>Functionth><th align='left' bgcolor='#eeeeec'>Locationth>tr>
<tr><td bgcolor='#eeeeec' align='center'>1td><td bgcolor='#eeeeec' align='center'>0.0000td><td bgcolor='#eeeeec' align='right'>242216td><td bgcolor='#eeeeec'>{main}( )td><td title='C:\wamp\www\unit1\json1.php' bgcolor='#eeeeec'>..\json1.php<b>:b>0td>tr>
<tr><td bgcolor='#eeeeec' align='center'>2td><td bgcolor='#eeeeec' align='center'>0.0000td><td bgcolor='#eeeeec' align='right'>242688td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connecta>
( )td><td title='C:\wamp\www\unit1\json1.php' bgcolor='#eeeeec'>..\json1.php<b>:b>5td>tr>
table>font>
[{"0":"Test1","product":"Test1","1":"Hello","questions":"Hello"},{"0":"","product":"","1":"","questions":""},{"0":"Test1","product":"Test1","1":"Venky","questions":"Venky"},{"0":"","product":"","1":"","questions":""}]
其实我们本意只想传下面的json数据
[{"0":"Test1","product":"Test1","1":"Hello","questions":"Hello"},{"0":"","product":"","1":"","questions":""},{"0":"Test1","product":"Test1","1":"Venky","questions":"Venky"},{"0":"","product":"","1":"","questions":""}]
那上面多出来的html代码都是什么鬼?
那就再来看下PHP代码
header('Content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('testdb');
$select = mysql_query('select * from questions');
$rows = array();
while($row=mysql_fetch_array($select))
{
$rows[] = $row;
}
echo json_encode($rows);
?>
返回的json字符串中, 有个关键词, “Deprecated”, 代表 “不建议使用”.PHP给出的解释是: mysql_connect() 这个方法在将来的某个时间会被彻底移除掉.
而且, 在声明一点, 返回的json数据走的是error方法,至于为什么会返回正确的数据,这就得问大神了.
解决方案如下
使用PDO或者mysqli_connect();
PDO代码:
// header('Content-type:application/json');
// 连接数据库
$dsn = 'mysql:dbname=dbtest1;host=127.0.0.1';
$user = 'root';
$password = '';
try {
$dbh = new PDO('mysql:dbname=dbtest1;host=127.0.0.1', $user, $pass);
$dbh = new PDO($dsn, $user, $password);
foreach($dbh->query('SELECT * from tb_test1') as $row) {
print_r($row[0]);
print_r("\n");
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}
?>
我自己用的是PDO,本以为能好了, 结果还是报类似的错: 一大堆html代码+返回数据
后来把PDO对象的第一个参数由常量改为变量后, 就好了, 如下:
$dbh = new PDO($dsn, $user, $pass);
公司同事给出了一个猜测性解释——PDO实例在后续操作中可能会影响到参数改变, 常量不可变, 变量可变, 所以常量填进去后会报错.
谨以此文,抛砖引玉,希望大神来探讨.