简体   繁体   中英

Calling PDO query within a function

I'm 'doomsday' (mysql_ depreciation!) prepping some of my older applications that take the use of mysql_ extentions. I am currently converting them into PDO.

I use a lot of functions to make my work easy. However I cant get the $db->query within a function to work. For example I'm converting this function:

function GetAccount($account_id){
    $Query = mysql_query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
    if (mysql_num_rows($Query) > 0){
        $Result = mysql_fetch_assoc($Query);
        return $Result;
    } else {
        return false;
    }
}

Into this PDO function.

function GetAccount($account_id){
    global $db;
    $Result = $db->query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
    if (count($Result) > 0){
        return $Result;
    } else {
        return false;
    }
}

I have established a PDO connection outside of this function, which works fine with queries outside of any function.

The problem for the second (PDO) function is that the $Result is empty. A var_dump returs: bool (false).

What am I forgetting/doing wrong?

Thank you :)

Fixed it, new function:

function GetAccount($account_id){
    global $db;
    $Result = $db->prepare("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
$Result->execute();
$Result = $Result->fetch();

    if (count($Result) > 0){
        return $Result;
    } else {
        return false;
    }
}

The only thing I did was :

$Result->prepare("query stuff");
$Result->execute();
$Result = $Result->fetch();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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