dpdkqls6399 2014-11-12 11:37
浏览 43
已采纳

如何在SELECT查询PDO中使用数组/内爆

i have a function that returns user data from the database. But I want to return only the selected row, for instance username, so i created an array for that, giving the option to echo $userdata['anything']. see the code:

$session_user_id = $_SESSION['user_id'];
    $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name'); } 

and

function user_data($user_id){

$pdo = new PDO("mysql:host=localhost;dbname=MYDATABASE;", "MYUSERNAME", "MYPASSWORD");
$data = array();
$user_id = (int)$user_id;

$func_num_args = func_num_args();
$func_get_args = func_get_args();

if ($func_num_args > 1) {
    unset($func_get_args[0]);
    $fields = '`' . implode(', ', $func_get_args) . '`';
    echo $fields;
    $stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");
    $stmt->execute(array(':user_id' => $user_id, ':fields' => $fields));
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    print_r($data);
}
}

The problem is that this doesn't work. It returns

Array ( [0] => Array ( [`user_id, username, password, first_name, last_name`] => `user_id, username, password, first_name, last_name` ) )

However, replacing :fields with for instance 'username' does work. Is it possible to use this implode?

  • 写回答

1条回答 默认 最新

  • dongsisui7562 2014-11-12 11:59
    关注

    Change:

    $stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");
    

    to:

    $stmt = $pdo->prepare("SELECT $fields FROM `users` WHERE `user_id` = :user_id");
    

    and remove $fields from the execute parameter array.

    Parameterized placeholders are only for values.

    UPDATE

    Also this line is wrong:

    $fields = '`' . implode(', ', $func_get_args) . '`';
    

    This will output a ` outside the the field list rather than each column name.

    Try removing them like this:

    $fields = implode(', ', $func_get_args);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀