0%

php 服务器 数据库查询

最近用PHP写服务器,都忘了PHP了

看以前的代码,mysql_connect 什么的都不推荐使用了!T^T

源代码

(当然这是本地的测试版,服务器版数据库名用户名密码都改了)

  • 使用参数化查询防止sql注入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php   
header("Content-type: text/html; charset=utf-8");//设置统一输出编码为utf-8

$building = $_POST['building'];
$week = $_POST['week'];
$startTime = $_POST['startTime'];
$endTime = $_POST['endTime'];

$conn=new mysqli("localhost","root","","rucHelper"); //数据库连接

if ($conn->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

$conn->query("SET NAMES utf8"); //设置读取数据后的编码
//var_dump($conn);
$stmt=$conn->prepare('SELECT distinct classroom FROM allcourse WHERE building =? and classroom not in (SELECT distinct classroom FROM allcourse where building =? and week =? and (startTime >=? and startTime<=? or endTime >=? and endTime <=?) ) order by classroom');
$stmt->bind_param("ssddddd",$building,$building,$week,$startTime,$endTime,$startTime,$endTime);//参数化查询
$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
printf("%s\n", $row['classroom']);
//var_dump($row);
}
$conn->close(); //关闭数据库连接
?>


 

接口

method: post

  • week: 星期 int

    • 1 ~ 7
  • building : 教学楼名称 str

    • 公共教学一楼
    • 公共教学二楼
    • 公共教学三楼
    • 公共教学四楼
    • 明德主楼
    • 明德商学楼
    • 明德国际楼
    • 明德法学楼
    • 明德新闻楼
    • 求是楼
  • startTime: 起始节数 int

    • 1~15
  • endTime: 终止节数 int

    • 1~15

返回:

  • 每一行为即为一个空教室

 

样例(url请自行修改)

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*-coding:utf-8 -*-
'''
author: hrwhipser
date : May 16, 2015
'''
import requests

url = 'http://localhost/phpService.php'
data ={
'week': '3',
'building':'公共教学二楼',
'startTime':1,
'endTime':15,
}
r = requests.post(url,data=data)
print r.text


输出:

1
2
3
4
5
6
7
8
2205
2313
2319
2320
2407
2415
2417
2418

 

PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php 
header("Content-type: text/html; charset=utf-8");
$url = "http://localhost/phpService.php";
$post_data = array ("building" => "公共教学二楼",
"week" => "2",
"startTime"=>"1",
"endTime"=>"10");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
?>
请我喝杯咖啡吧~