这段代码是利用PHP 传递base64处理后的SQL 语句 生成JSON 便于第三方应用调用,可根据实际情况转换成XML
BASE64主要是为了避免传递乱码,和简单加密使用,可以换成自己编写的加密语句。
<?php include_once("conSQL.php"); //这段代码将mySQL的记录集转换成JSON $SQL = $_SERVER['QUERY_STRING']; $SQL=base64_decode($SQL); $STR="["; $r=mysqli_query($cn,$SQL); $fields = mysqli_num_fields($r); //取得记录集的数字 for($count=0;$count<$fields;$count++)//通过循环列出字段名 放在数组里 { $field = mysqli_fetch_field($r); $字段[$count]=$field->name; } while($s=mysqli_fetch_row($r)) { $STR=$STR. "{"; //遍历数组 for($count=0;$count<$fields;$count++) { $STR=$STR. '"'. $字段[$count]. '":'; $STR=$STR. '"'.$s[$count].'",'; } $STR=mb_substr($STR,0,mb_strlen($STR,"utf-8")-1,"utf-8");//去掉最后一个字符 $STR=$STR. "},\n"; } $STR=mb_substr($STR,0,mb_strlen($STR,"utf-8")-2,"utf-8"); $STR=$STR. ']'; echo $STR; mysqli_close($cn); ?>
执行结果:
[{"title":"AA","Name":"na1","idd":"1"}, {"title":"Abb","Name":"na2","idd":"2"}, {"title":"测试数据","Name":"nana3","idd":"3"}, {"title":"标题1","Name":"姓名1","idd":"4"}, {"title":"标题2","Name":"姓名2","idd":"5"}]
后来发现用自带函数
json_encode
就可以了,代码更简洁 后面的参数是显示中文用的
header("Content-Type: application/json; charset=UTF-8"); include_once("conMySQL.php"); $SQL="select lx,count(idd) as sl from book group by lx"; $STR="["; $r=mysqli_query($cn,$SQL); $outp = array(); $outp = $r->fetch_all(MYSQLI_ASSOC); echo json_encode($outp,JSON_UNESCAPED_UNICODE);
发表评论