dqxz96998 2013-09-21 10:54
浏览 28
已采纳

生成查询到数据库的php函数[关闭]

Very basic question, I am making functions that will generate queries to database. I have two approaches to this and I don't know which is better.

First is making one bigger function to generate any query I need, so basically:

function generateQuery($object, $queryType, $tableName, $conditions = null) {
    //Then in here some more complex code that generates query,
    //some of stuff like double if shorthands etc, for example:

    $string = ($queryType === "INSERT") ? "INSERT INTO {$table} (" : (($queryType === "UPDATE") ? "UPDATE {$table} SET" : "SELECT");

    //So all the code for generating INSERT, UPDATE and SELECT in one function
    //full of conditions.
}

Or I could just write seperate function for each type of query.

In the end, the first solution is not that complicated at all, and the second one would make some repetition in code, but still it does feel kind of wrong.

Then again I want to use PDO transactions later, so I will have a function like so:

function launchQueries($list) {
    $this->handler->beginTransaction();

    for($i = 0; $i < count($list); $i++)
    {
        $this ->launchQuery($list[i]->object, $list[i]->$table, $list[i]->queryType, $list[i]->conditions);
    }
    $this->handler->commit();
}

Or something like that, not sure this exact code would work, since I haven't made it yet.

Anyway, with query generation in one function I can just pass queries in list and do one loop to generate and execute them all. But it still feels wrong. Is it done like this at all, or am I missing different, better solutions?

  • 写回答

1条回答 默认 最新

  • dongyu5482 2013-09-21 10:59
    关注

    What feels wrong to me is reinventing the wheel.

    What about using a solid, existing library such as Doctrine DBAL?

    It's cross-platform, and provides convenience methods such as insert(), update() and delete():

    $conn->insert('user', array('username' => 'jwage'));
    $conn->update('user', array('username' => 'jwage'), array('id' => 1));
    $conn->delete('user', array('id' => 1));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端