简体   繁体   中英

php pdo mssql prepared statement

I'm having trouble on using a pdo based function

my GetCurrentLanguage() function returns an int of 0 or 1

public function GetCurrentLangName()
{
    $stmt = $GLOBALS['website']->prepare("SELECT * FROM available_languages WHERE id = :id");
    $stmt->bindParam(':id', $this->GetCurrentLanguage(), PDO::PARAM_INT);

    $stmt->execute();
    $fetch = $stmt->fetchAll();
    return $fetch['name'];
}

and is not working, it returns

Notice: Undefined index: name

If you're expecting many rows, you could have just loop it.

public function GetCurrentLangName()
{
    $data = array():
    $stmt = $GLOBALS['website']->prepare("SELECT * FROM available_languages WHERE id = :id");
    $stmt->bindParam(':id', $this->GetCurrentLanguage(), PDO::PARAM_INT);

    $stmt->execute();
    $fetch = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach($fetch as $row) {
        $data[] = $row['name'];
    }
    return $data;
}

This function ( ->fetchAll() ) returns a multi-dimentional array. May look like this:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => lang
        )

    [1] => Array
        (
            [id] => 2
            [name] => lang
        )
)

Could have used print_r()/var_dump() on $fetch and you'll see what it yielded.

you should set parameter as a param you want to bind.

public function    GetCurrentLangName($id)
{
    $stmt =     $GLOBALS['website']-    >prepare("SELECT * FROM     available_languages WHERE id = :id");
    $stmt->bindParam(':id', $id,     PDO::PARAM_INT);

$stmt->execute();
$fetch = $stmt->fetchAll();
return $fetch['name'];

}

fetchAll() returns two dimensional array, so instead of returning $fetch['name']; it should be return $fetch[0]['name']; or better use fetch to return a single row :

$fetch = $stmt->fetch();
return $fetch;

then use function like this:

$data  = GetCurrentLangName();
$language = $data['name'];

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