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条)

报告相同问题?

悬赏问题

  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。