想要将函数从Mysql转换为PDO

时间:2016-09-11 17:39:54

标签: mysql pdo

function get_country($code){

$query = mysql_query("SELECT country FROM `list_countries` WHERE `code`='".$code."' LIMIT 1");
$country = mysql_fetch_array($query);

return $country['country'];

}

PDO非常新,并且完全不知道如何将其从mysql函数转换为PDO函数。任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

您需要随身携带PDO数据库连接处理程序:)从您的代码我建议将其设置为全局,或者您可以为所有功能添加其他参数。

$dbconn = new PDO("mysql:host=localhost;dbname=your_db","your_user","your_password");

// this line is important - throw an exception if there is an error
$dbconn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

function get_country( $dbconn, $code ) {
    $res = $dbconn->prepare('SELECT country FROM `list_countries` WHERE `code`=? limit 1');
    $res->execute( array( $code) )
    $country = $res->fetch();
    return $country['country'];
}