简体   繁体   English

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

[英]Getting information from a MySQL database using PDO

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. 我正在尝试使用PHP(带有PDO)连接到MySQL数据库,但是我对PHP不太熟悉,所以有点卡住了。 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. 我试图在我的数据库中搜索所有出现的$ userid,然后将与其关联的$ crn存储在一个数组中,但我真的不知道该怎么做。 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));
        }            
    }

I advise you to check the documentation on PDO and PDOStatement for more detailed information. 我建议您检查有关PDOPDOStatement的文档以获取更多详细信息。

I guess you're already connected to your database through PDO ? 我想您已经通过PDO连接到数据库了吗? (else see PDO::__construct()) (否则请参见PDO :: __ construct())

With a prepared query you better "bind" ($sthandler->bindParam()) your parameters instead of concatenating them, like so 使用准备好的查询,您可以更好地“绑定”($ sthandler-> bindParam())您的参数,而不是将它们串联在一起,就像这样

$sthandler = $conn->prepare('SELECT userid FROM users WHERE userid= :user_id');
$sthandler->bindParam(':userid', $userid, PDO::PARAM_INT);

I don't quite understand the rest of your code though. 我不太了解您的其余代码。 Maybe isn't it complete. 也许还不完整。 You make a loop on something that is supposed to always be a unique result (i hope for you, "userid" is a unique primary key). 您在应该总是唯一的结果上循环(我希望您,“ userid”是唯一的主键)。

If this loop is actually useless, then maybe you should consider making only 1 query to get both user and courses at the same time, by using a join between the tables : 如果此循环实际上没有用,那么您可能应该考虑通过使用表之间的联接来只查询1个查询,以同时获取用户和课程:

SELECT u.userid, c.crn FROM users u INNER JOIN usercourses c ON u.userid = c.userid WHERE u.userid= :user_id

And from this result, get anything you want. 从这个结果中,得到您想要的任何东西。 Yes you will have duplicated data in your result (userid on each row of different courses), but it's still a better way than doing 2 seperate queries. 是的,您的结果中将有重复的数据(不同课程的每一行上的用户ID),但这仍然是比进行2个单独查询更好的方法。

Consider using $sthandler->fetch() or $sthandler->fetchAll() to get every results and organize them into an array, as it suits you : 考虑使用$sthandler->fetch()$sthandler->fetchAll()来获取每个结果并将它们组织成一个数组,因为它适合您:

$rows = $sthandler->fetchAll(PDO::FETCH_ASSOC); // FETCH_ASSOC will return the results as array with columns' name as keys.
// Do your loop on the array $rows to process it

Or 要么

while( $row = $sthandler->fetch(PDO::FETCH_ASSOC) ) {
     // do whatever you like with each row
}

Also take Darren's advice to wrap your PDO queries with try/catch to avoid any errors. 还要听达伦的建议,用try/catch包裹您的PDO查询,以避免出现任何错误。

The point of PDO is to prevent concatenating the query string like you're currently doing. PDO的要点是防止像当前那样连接查询字符串。 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/catch语句中,以处理任何潜在的错误:

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对象时,您应该显式打开错误!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM