duanlu5055 2015-05-29 00:01
浏览 375

使用PDO从MySQL数据库获取信息

I'm trying to connect to a MySQL database using PHP (with PDO) but I'm not that familiar with PHP so I'm a little stuck. I'm trying to search one of my databases for all occurrences of $userid and then store the $crn associated with it in an array but I don't really know how to go about that. Here's what I have so far...

$sthandler = $conn->prepare('SELECT userid FROM users WHERE userid=' . $userid);
    $sthandler->execute(array('username'));

    if($sthandler->rowCount() > 0)
    {
        // User exists, get user's courses from database and returns array of CRNs
        for(int i = 0; i < rowCount; i++)
        {
            $sthandler = $conn->prepare('SELECT crn FROM usercourses WHERE userid=' . $userid);
            $sthandler->execute(array($USER => $crnArray));
        }            
    }
  • 写回答

2条回答 默认 最新

  • douye2110 2015-05-29 00:12
    关注

    The point of PDO is to prevent concatenating the query string like you're currently doing. It's supposed to be used used to prepare the statements.

    $sthandler = $conn->prepare('SELECT userid FROM users WHERE userid= :user_id');
    if($sthandler->execute(array(':user_id' => $user_id))) {
        if($sthandler->rowCount() > 0)
        {
            // User exists, get user's courses from database and returns array of CRNs
            for(int $i = 0; $i < rowCount; $i++)
            {
                $sthandler = $conn->prepare('SELECT crn FROM usercourses WHERE userid= :user_id';
                $sthandler->execute(array(':user_id' => $user_id));
            }            
        }
    }
    

    You're trying to execute with random data in the arrays.

    One more thing, you should wrap your queries in a try/catch statement, to handle any potential errors:

    try {
        // run query and all
    }
    catch (PDOException $e){
        // echo out the error if there is one.
        echo $e->getMessage();
    }
    

    And the last note, while you're at it. You should explicitly turn on errors when constructing your PDO object!

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致