我会切入追逐。此时我只能通过此类实现数据库连接。我无法进行查询。你能告诉我如何使这个工作和/或告诉我如何以更好的方式重新编码它。
<?php
class database{
public $dbHost = '';
public $dbUser = '';
public $dbPass = '';
public $dbName = '';
public $db;
public function __construct(){}
public function dbConnect(){
$mysqli = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);
/* check connection */
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo 'connection made';
}
/* close connection */
$mysqli->close();
}
public function query($sql){
$query = $sql;
self::preparedStatement($query);
}
public function preparedStatement(){
if ($stmt = $mysqli->prepare($query)){
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
}
public function __destruct(){}
}
?>
答案 0 :(得分:1)
这对我有用。我评论了我的变化。
<?php
class database{
public $dbHost = '';
public $dbUser = '';
public $dbPass = '';
public $dbName = '';
public $db;
public function __construct(){}
public function dbConnect(){
### not $mysqli
$this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);
/* check connection */
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo 'connection made';
}
/* close connection */
### $this->db->close(); // DO NOT close the connection here!
}
public function query($sql){
$query = $sql;
self::preparedStatement($query);
}
public function preparedStatement($query){ ### parameter $query added
if ($stmt = $this->db->prepare($query)){ ### not $mysqli->prepare()
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
}
public function __destruct(){}
}
### Test code
/*
$db = new Database();
$db->dbHost = '127.0.0.1';
$db->dbUser = 'root';
$db->dbPass = 'root';
$db->dbName = 'test';
$db->dbConnect();
$db->query('SELECT * FROM test');
*/
?>
答案 1 :(得分:0)
您已省略参数:
public function preparedStatement($query)
(这个方法实际上 应该是静态的)
下次尝试在询问之前调试代码。即使是简单的echo
语句也可以在这里完成。
编辑:,即使这样也行不通。我认为你误解了变量范围的概念。 $mysqli
应该是该类的实例变量,因为如果您只是将其设置为preparedStatement()
作为局部变量,它将不会保留到__construct()
。