php sql分离

时间:2023-03-09 17:16:34
php sql分离

sql.php

<?php
$con = mysql_connect("localhost","root","root");
mysql_select_db("my_db", $con); $sql=array(
"all"=>"select * from tables",
"where"=>"select * from tables where id = {id}",
"page"=>"select * from tables limit {a},{b}",
"add"=>"INSERT INTO tables (name) VALUES ('{name}')"
); ?>

json.php

<?php
include("sql.php"); foreach ($sql as $key=>$value){
if(@$_GET['action']==$key){
$a = str_replace("{","\".\$_GET['",$value);
$b = str_replace("}","'].\"",$a);
}
} eval("\$sql = \"".$b."\";");$result = mysql_query($sql);
while(@$row = mysql_fetch_array($result)){
$json = json_encode($row);
echo $json;
} ?>

php sql分离

php sql分离

php sql分离

不管是什么查询的sql语句,根据json_encode这个方法都可以变成json字符串(把sql语句整个当做是一个变量-先不考虑安全性)

但是呢,在不考虑安全性的前提下还是有两点地方不太好

第一:如果把sql语句当成传参的话,url不美观

第二:如果是根据不同的传参指定不同的sql语句的话,会有一大堆的if判断

所以,这个东西相当于(路由+orm)最最简单的模型(orm部分相当于没写,就一个“{}”)

有什么用呢?比如明天就要上百个接口,来不及写程序了。。。O(∩_∩)O哈哈~