Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...