[PHP 作为iOS后台Json格式HTTP通信及文件上传的实现]
1.数据库连接 configmysql.php
<?php $q = mysql_connect("localhost:8889","root","root"); if(!$q) { die('Could not connect: ' . mysql_error()); } mysql_query("set names utf8"); //以utf8读取数据 //mysql_select_db("myDB",$q); //选择数据库 ?>
2.POST或GET请求,Json返回 selectuser.php
<? include("configmysql.php"); mysql_select_db("myDB",$q); //选择数据库 //GET或POST取的参数或者 $TEMPid=$_GET['userid']; //$TEMPid=$_POST['userid']; $sql = "select * from UserinfoTB where userid=".$TEMPid; $query = mysql_query($sql)or die(mysql_error()); while($row = mysql_fetch_array($query)){ $json = $row; } echo json_encode($json); ?>
3.多组数据 selectuser.php
<? include("configmysql.php"); mysql_select_db("chepaiDB",$q); //数据库 $TEMPid=$_GET['Driverid']; $sql = "select * from Driverinfo where Driverid=".$TEMPid; $query = mysql_query($sql)or die(mysql_error()); while($row = mysql_fetch_array($query)){ $json1 = $row; } $sql2 = "select * from Driverillegalinfo where IDriverid=".$TEMPid." order by Iid desc"; $query2 = mysql_query($sql2)or die(mysql_error()); $json2 = array(); $sum=0; while($row2 = mysql_fetch_array($query2)){ $json2['row'.$sum] = $row2; $sum++; } $newJson = json_encode( array_merge( array('info1' => $json1), array('info2' => $json2) ) ); echo $newJson; ?>
4.文件照片上传 upload_file.php
<? header("Content-type: text/html; charset=UTF-8"); include("configmysql.php"); mysql_select_db("chepaiDB",$q); //数据库 //POST获取键值对参数 $TEMPid=$_POST['Driverid']; echo "\nDriverid is ".$TEMPid."\n"; foreach ($_FILES as $_eachFile) { //file文件处理 if ($_eachFile["error"] > 0) { echo "错误: " . $_eachFile["error"] . "\n"; } else { echo "文件名: " . $_eachFile["name"] . "\n"; echo "类型: " . $_eachFile["type"] . "\n"; echo "大小: " . ($_eachFile["size"] / 1024) . " Kb\n"; } if (file_exists("uploadimage/" . $_eachFile["name"])) { echo $_eachFile["name"] . " 文件已经存在. "; } else { move_uploaded_file($_eachFile["tmp_name"], "uploadimage/" . $_eachFile["name"]); echo "文件已经被存储到: " . "uploadimage/" . $_eachFile["name"]."\n"; } } /* //file文件处理 if ($_FILES["file"]["error"] > 0) { echo "错误: " . $_FILES["file"]["error"] . "\n"; } else { echo "文件名: " . $_FILES["file"]["name"] . "\n"; echo "类型: " . $_FILES["file"]["type"] . "\n"; echo "大小: " . ($_FILES["file"]["size"] / 1024) . " Kb\n"; } if (file_exists("uploadimage/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " 文件已经存在. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploadimage/" . $_FILES["file"]["name"]); echo "文件已经被存储到: " . "uploadimage/" . $_FILES["file"]["name"]."\n"; } */ ?>
___________________________________________________
专注iOS/前端开发,广泛涉猎多种平台和技术,欢迎交流
可以在微博关注并@沈z伟