问题
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?
回答1:
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.
回答2:
PHP allows you to create local variables within a function without needing to do anything to declare them. 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;
. . .
来源:https://stackoverflow.com/questions/43076432/pdo-variable-is-undefined-in-mysql-function