douzhuan1169 2017-04-30 04:30
浏览 49
已采纳

PHP / PDO - 使用变量赋值作为fetch-statement

Okay - so I have a custom function

selectQuery($query, $fetch = 'fetch', $rowCount = 1, 
              $onlyRowCount = false, $outputerror = false)

Which works fine. However, I have one particular query where the fetch-method is fetchAll(PDO::FETCH_COLUMN,0), and if I pass that as the $fetch-value in the function-call and try to use that in the output, it just returns NULL(because it doesn't work - the query works fine if run directly, or hard-coded).

So, what I'm asking, is there a way to use a value of a variable (which, at least to start with, is a string) to assign a fetch method?

I've tried the following:

$stmt->fetchAll(PDO::FETCH_COLUMN,0); //works, but is hard-coded

$stmt->$fetch //returns NULL

$stmt->{$fetch} //returns NULL

So, is there a way to use that variable $fetch as the assignment directly? Casting the variable to something, or some other way?

  • 写回答

4条回答 默认 最新

  • donglizuo8892 2017-04-30 05:08
    关注

    This function is horrible. That long tail of parameters alone! And the lack of prepared statements. And a database related function that decides on its own whether to output an error or not, as though database interaction is something different from other code.

    Do yourself a favor, make this function this way

    function query($query, $parameters = []) {
        $pdo = // here your way of getting a PDO instance. 
        // DON't TELL ME YOU ARE CREATING A NEW ONE EVERY TIME
        if (!$parameters)
        {
             return $this->query($sql);
        }
        $stmt = $pdo->prepare($sql);
        $stmt->execute($parameters);
        return $stmt;
    }
    

    This is ALL you need and it's MUCH better than you have at the moment.

    Returning a statement is the key. It lets you to attach any fetch method you like to the function call - the most natural way of getting different result types from such a function. Or not to fetch anything at all, if a query happens to be UPDATE or INSERT.

    Want a row count?

    $count = query("DELETE FROM usars")->rowCount();
    

    want a fetch?

    $user = query("select * from users where id=?", [$id])->fetch();
    

    want fetchAll with PDO::FETCH_COLUMN? here you are

    $users = query("select name from users")->fetchAll(PDO::FETCH_COLUMN);
    

    Simple, usable, flexible, readable and secure.

    If you don't know how to make this function connect only once, here is a link to a simple PDO wrapper I wrote. Note the examples section. It is so exciting that I'd better put it here:

    # Table creation
    DB::query("CREATE temporary TABLE pdowrapper 
               (id int auto_increment primary key, name varchar(255))");
    
    # Prepared statement multiple execution
    $stmt = DB::prepare("INSERT INTO pdowrapper VALUES (NULL, ?)");
    foreach (['Sam','Bob','Joe'] as $name)
    {
        $stmt->execute([$name]);
    }
    $id = DB::lastInsertId());
    
    # Getting rows in a loop
    $stmt = DB::run("SELECT * FROM pdowrapper");
    while ($row = $stmt->fetch())
    {
        echo $row['name'], PHP_EOL;
    }
    
    # Getting one row
    $id  = 1;
    $row = DB::run("SELECT * FROM pdowrapper WHERE id=?", [$id])->fetch();
    
    # Getting single field value
    $name = DB::run("SELECT name FROM pdowrapper WHERE id=?", [$id])->fetchColumn();
    
    # Getting array of rows
    $all = DB::run("SELECT name, id FROM pdowrapper")->fetchAll(PDO::FETCH_KEY_PAIR);
    
    # Update
    $new = 'Sue';
    $count = DB::run("UPDATE pdowrapper SET name=? WHERE id=?", [$new, $id])->rowCount();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿