我一直在使用这个课程:
<?
class DbConnector {
var $theQuery;
var $link;
function DbConnector() {
$host = 'localhost';
$db = 'my_db';
$user = 'root';
$pass = 'password';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
// get some results
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
function last_id($query) {
return mysql_insert_id($query);
}
}
?>
我正在使用它进行大量查询并且工作正常,尽管我正在尝试使用此查询插入:
global $db;
$query = $db->insert("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
它给了我这个错误:
Not Found
The requested URL /horh_new/id/<br /><b>Fatal error</b>: Call to a member function insert() on a non-object in <b>/Applications/MAMP/htdocs/horh_new/addit.php</b> on line <b>52</b><br /> was not found on this server.
虽然当我不使用上面的那个类时,请改用它:
$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
echo mysql_insert_id();
mysql_close($con);
工作正常。谁能告诉我班上有什么问题?我真的很感激。
答案 0 :(得分:2)
你应该这样做
global $db;
$db = new DbConnector();
或者使用它的更好方法是
添加类DbConnector的静态函数,它将在整个请求中仅创建单个实例
public static function getInstance(){
static $instance = null;
if($instance === null){
$instance = new DbConnector();
}
return $instance;
}
并将此课程用作
$db = DbConnector::getInstance();
$db->insert($query);
答案 1 :(得分:2)
在使用之前需要实例化对象
$db = new DbConnetor();
现在你可以进行插入
虽然我建议首先添加一个__construct方法来连接数据库
class DbConnector {
public function __construct() {
// connect to db here
}
答案 2 :(得分:0)
你确定$ db包含你班级的一个实例吗?也许只是在调用$ db-&gt; insert()之前执行$ db的var_dump()并查看它是否已设置。