dqqy64515 2011-12-12 22:06
浏览 34
已采纳

php服务使用jquery ajax执行sql命令

<?php

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json'); 

$mysql = mysql_connect('corte.no-ip.org', 'hostcorte', 'xxxx');
mysql_select_db('fotosida');

if((isset($_POST['GetPersons'])))
{

if(isset($_POST['ID'])) {
    $query = sprintf("SELECT * FROM persons WHERE id='%s'",
        mysql_real_escape_string($_POST['ID']));
} else {
    $query = "SELECT * FROM persons";
}

$res = mysql_query($query);

while ($row = mysql_fetch_assoc($res)) {

    for ($i=0; $i < mysql_num_fields($res); $i++) {
        $info = mysql_fetch_field($res, $i);
        $type = $info->type;

        if ($type == 'real')
            $row[$info->name] = doubleval($row[$info->name]);

        if ($type == 'int')
            $row[$info->name] = intval($row[$info->name]);
    }

    $rows[] = $row;
}

echo json_encode($rows);


}

mysql_close($mysql);
?>

This works ok for generating a json object based on a database query. Im not very familiar with PHP, so i would like some feedback from you before i proceed with this. Is this a good way of calling the database using ajax? Other alternatives? Frameworks maybe?Are there any security problems when passing database queries like UPDATE, INSERT, SELECT etc using an ajax HTTPPOST? Thanks

  • 写回答

4条回答 默认 最新

  • douhui8454 2011-12-12 22:55
    关注

    To simplify CRUD operations definitely give REST a read.

    As mentioned, stop using the @ (AKA "shut-up") operator in favor of more robust validation:

    if(isset($_GET['key'])){
        $value = $_GET['key'];
    }  
    

    Or some such equivalent.

    Using JavaScript/AJAX, aggregate and send your request data, such as IDs and other parameters, from the form fields into a JSON object. Not the built query. The only time the client should be allowed to manipulate directly executed SQL is if you're creating an web based SQL client. Architect your URLs meaninfully (RESTful URLs) so that your HTTP request can be formed as:

    GET users/?id=123
    
    DELETE photos/?id=456
    

    Or alternatively:

    GET users/?id=123
    
    GET photos/?method=delete&id=456
    

    Server-side, you're going to receive these requests and based on parameters from the session, the request, etc., you can proceed by firing parametrized queries:

    switch($method){
        case 'get':
            $sql = 'SELECT * FROM `my_table` WHERE `id` = :id';
            break;
        case 'delete':
            $sql = 'DELETE FROM `my_table` WHERE `id` = :id';
            break;
        default:
            // unsupported
    }
    // interpolate data from $_GET['id'] and fire using your preferred
    // database API, I suggest the PDO wrapper.
    

    See PDO

    Generate output as necessary, and output. Capture on client-side and display.

    Always validate and filter user input. Never send and execute raw SQL queries, or concatenate raw user input into SQL queries.


    With regard to your question, here's a possible snippet:

    (Note -- I haven't tested it, nor rigorously reviewed it, but it should still serve as a guide -- there is a lot of room for improvement, such as refactoring much of this logic into reusable parts; functions, classes, includes, etc.)

    header('Cache-Control: no-cache, must-revalidate');
    header('Content-type: application/json');
    
    $error = array();
    
    // get action parameter, or use default
    if(empty($_POST['action']))
    {
        $action = 'default_action';
    }
    else
    {
        $action = $_POST['action'];
    }
    
    // try to connect, on failure push to error
    try
    {
        $pdo = new PDO('mysql:dbname=fotosida;host=corte.no-ip.org', 'hostcorte', 'xxxx');
    }
    catch(Exception $exception)
    {
        $error[] = 'Error: Could not connect to database.';
    }
    
    // if no errors, then check action against supported
    if(empty($error))
    {
        switch($action)
        {
            // get_persons action
            case 'get_persons':
                try
                {
                    if(!isset($_POST['id']))
                    {
                        $sql = 'SELECT * FROM `persons`';
                        $stm = $pdo->prepare($sql);
                        $stm->execute();
                    }
                    else
                    {
                        $sql = 'SELECT * FROM `persons` WHERE `id` = :id';
                        $stm = $pdo->prepare($sql);
                        $stm->execute(array(
                            'id' => (int) $_POST['id'],
                        ));
                    }
                    $rows = array();
                    foreach($stm->fetchAll() as $row)
                    {
                        $rows[] = $row;
                    }
                }
                catch(Exception $exception)
                {
                    $error[] = 'Error: ' . $exception->getMessage();
                }
                break;
    
            // more actions
            case 'some_other_action':
                // ...
                break;
    
            // unsupported action
            default:
                $error[] = 'Error: Unsupported action';
                break;
        }
    }
    
    // if errors not empty, dump errors
    if(!empty($error))
    {
        exit(json_encode($error));
    }
    
    // otherwise, dump data
    if(!empty($rows))
    {
        exit(json_encode($rows));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元