为什么它显示pdo undefined?

时间:2017-08-25 11:15:40

标签: php sql pdo undefined

我有一个用于db连接的脚本

<?php

//$dsn ='mysql:dbname=medicare;host=localhost';
$me = "root";
$password ="";

try{
$pdo = new PDO('mysql:host=localhost;dbname=medicare',$me,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo"Error!:".$e->getMessage()."<br>";
die();


}

?>

然后我有一个函数在db_operations类中添加数据

public static  function insert_admin($name,$pass){
// require_once("/connect.php");
$security = "?..H@Si./n/?";
$pass = md5($pass,PASSWORD_DEFAULT).$security;
$sql = "INSERT INTO admin(username,password)  VALUES(:username,:password)";

$stmt = $pdo->prepare($sql); (line 79)
$stmt->bindParam(':username',$name,PDO::PARAM_STR);
$stmt->bindParam(':password',$pass,PDO::PARAM_STR);
$stmt->execute();

$pdo = null;


}

但它已经显示

  

注意:未定义的变量:pdo in   第79行的F:\ xampp \ htdocs \ medicare \ Model \ class_db_operations.php

     

致命错误:在非对象中调用成员函数prepare()   第79行的F:\ xampp \ htdocs \ medicare \ Model \ class_db_operations.php   有人请帮忙。

2 个答案:

答案 0 :(得分:0)

调用$pdo->prepare()时没有定义<plugin> <groupId>org.wildfly.swarm</groupId> <artifactId>wildfly-swarm-plugin</artifactId> <version>${version.wildfly.swarm}</version> <configuration> <useUberJar>true</useUberJar> <debug>8000</debug> </configuration> <executions> <execution> <id>swarm-package</id> <phase>package</phase> <goals> <goal>package</goal> </goals> </execution> <execution> <id>swarm-start</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>swarm-stop</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ,您需要将其作为参数传递,或者将其作为属性在对象中使用,并使用其他方法进行设置。

答案 1 :(得分:0)

public static  function insert_admin($name,$pass){
// require_once("/connect.php");
global $pdo;
$security = "?..H@Si./n/?";
$pass = md5($pass,PASSWORD_DEFAULT).$security;
$sql = "INSERT INTO admin(username,password)  VALUES(:username,:password)";

$stmt = $pdo->prepare($sql); (line 79)
$stmt->bindParam(':username',$name,PDO::PARAM_STR);
$stmt->bindParam(':password',$pass,PDO::PARAM_STR);
$stmt->execute();

$pdo = null;


}

为什么你最后将$ pdo设置为null?