简体   繁体   English

pdo变量在mysql函数中未定义

[英]pdo variable is undefined in mysql function

I have an index.php which is like: 我有一个index.php是这样的:

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 is: mysql.php是:

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;
    }
}

And it appears, that $pdo from function is undefined. 看来,来自函数的$ pdo是未定义的。 Even if i remove try-catch. 即使我删除try-catch。 The only way i fixed it - i sent $pdo as a parameter to function, but it seems to be wrong. 我修复它的唯一方法-我将$ pdo作为参数发送给函数,但这似乎是错误的。 Any suggestions guys? 有什么建议吗?

PHP allows you to create local variables within a function without needing to do anything to declare them. PHP允许您在函数内创建局部变量,而无需执行任何操作来声明它们。 Just start using a variable, and it's assumed to be a local variable. 刚开始使用变量,并且假定它是局部变量。

This means if you want to access a global variable inside a function, you must declare it explicitly: 这意味着,如果访问函数内部的全局变量,则必须显式声明:

function checkIfMailExists($email)  {
    global $pdo;
    . . .

Sending a PDO connection as a parameter is actually the only sane way to do this. 实际上,发送PDO连接作为参数是唯一明智的方法。 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 知道可以使用global关键字确实很高兴,但是编写可以维护的代码的最佳方法是显式声明依赖关系,并对其进行类型提示

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) {}

Read more here about PDO and prepared statements. 在此处阅读有关PDO和准备好的语句的更多信息。 Notice how I took advantage of named parameters to ensure that no sql injection is possible from this code. 请注意,我是如何利用命名参数来确保此代码中不可能进行sql注入的。

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

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