Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

php - pdo variable is undefined in mysql function

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...