dongxing7530 2013-06-17 21:35
浏览 73
已采纳

使用PDO从MySQL数据库中获取多个变量的最佳方法

Okai, so I am trying to fetch multiple variables from the MySQL Database using PDO and I feel that I have to repeat myself alot in the code. Is there a neater way to write this or a more secure way?

Here is my code for the following example:

    $username = $_SESSION['username'];

    $db = new PDO('mysql:xxxxxxxx;dbname=xxxxxxxxxxxx', 'xxxxxx', 'xxxxxxx');

    // FETCH name VARIABLE
    $fetchname = $db->prepare("SELECT name FROM login WHERE username = :username");
    $fetchname->bindParam(':username', $username, PDO::PARAM_STR, 40);
    $fetchname->execute();
    $myname = $fetchname->fetchColumn();

    // FETCH age VARIABLE
    $fetchage = $db->prepare("SELECT age FROM login WHERE username = :username");
    $fetchage->bindParam(':username', $username, PDO::PARAM_STR, 40);
    $fetchage->execute();
    $myage = $fetchage->fetchColumn();

I wish to avoid having to repeat this FETCH for each variable from the same table...

  • 写回答

3条回答 默认 最新

  • douershuang7356 2013-06-17 21:38
    关注

    Have you tried the fetchAll method

    // FETCH name VARIABLE
    $fetch = $db->prepare("SELECT name, age FROM login WHERE username = :username");
    $fetch->bindParam(':username', $username, PDO::PARAM_STR, 40);
    $fetch->execute();
    $login = $fetch->fetchAll();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys