pdo变量在mysql函数中未定义 [英] pdo variable is undefined in mysql function

查看:149
本文介绍了pdo变量在mysql函数中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个index.php,就像:

I have an index.php which is like:

require_once("../resources/config.php");
require_once(LIBRARY_PATH . "/mysql.php");
...
if(checkIfMailExists($email)) {
    $error = true;
    $errormsg = "This e-mail is already in use!";
}

mysql.php是:

mysql.php is:

try {
    $pdo = new PDO('mysql:host=' . $config['db']['db1']['host'] . ';dbname=' . $config['db']['db1']['dbname'], $config['db']['db1']['username'], $config['db']['db1']['password']);
}catch(PDOException $e){
    echo "Cant connect to mysql DB!";
}

function checkIfMailExists($email)  {
    $query = "SELECT * FROM users WHERE email = '".$email."'";
    $num = $pdo->query($query);
    if($num->rowCount() > 0){
        return true;
    }else{
        return false;
    }
}

看来,来自函数的$ pdo是未定义的.即使我删除try-catch. 我修复它的唯一方法-我将$ pdo作为参数发送给函数,但这似乎是错误的.有什么建议吗?

And it appears, that $pdo from function is undefined. Even if i remove try-catch. The only way i fixed it - i sent $pdo as a parameter to function, but it seems to be wrong. Any suggestions guys?

推荐答案

发送PDO连接作为参数实际上是唯一可行的方法.很高兴知道您可以使用global关键字,但是编写可以维护的代码的最佳方法是明确声明依赖关系,并且

Sending a PDO connection as a parameter is actually the only sane way to do this. It is indeed good to know that you could use the global keyword, but the optimal way to write code that is possible to maintain is explicitely stating dependencies, and type-hinting them

function mailExists (PDO $pdo, $email)  {
    $sql = 'SELECT * FROM users WHERE email = :email';
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':email', $email, PDO::PARAM_STR);
    $stmt->execute();
    return $stmt->rowCount() > 0;
}
if (mailExists($pdo, $email) {}

此处了解更多有关PDO和准备好的语句的信息.请注意,我是如何利用命名参数来确保此代码中不可能进行sql注入的.

Read more here about PDO and prepared statements. Notice how I took advantage of named parameters to ensure that no sql injection is possible from this code.

这篇关于pdo变量在mysql函数中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆