function insert_data($array){
$dbh=new PDO('sqlite:C:\test.sqlite');
$sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
$q = $dbh->prepare($sql);
$q->execute($array);
$dbh=null;
}
我想将C:\test.sqlite
定义为常量。
define('db_name','C:\test.sqlite');
但是我不能在我的函数insert_data中使用常量。
function insert_data($array){
$dbh=new PDO("sqlite:db_name");
$sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
$q = $dbh->prepare($sql);
$q->execute($array);
$dbh=null;
}
发生错误:
Fatal error: Call to a member function execute() on a non-object in....
我不想把这个函数写成格式:
function insert_data($array,$db){
$dbh=new PDO("sqlite:{$db}");
$sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
$q = $dbh->prepare($sql);
$q->execute($array);
$dbh=null;
}
如何解决?
答案 0 :(得分:0)
定义变量 - $db = 'C:\test.sqlite';
并将其global
。
function insert_data($array){
global $db;
$dbh=new PDO("sqlite:{$db}");
$sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
$q = $dbh->prepare($sql);
$q->execute($array);
$dbh=null;
}