我想使用mysqli从数据库中获取数据。
class.php
class main{
public $host="localhost";
public $username="root";
public $password="";
public $db_name= "db_tvw";
private $img_path = 'slider_img_upload/';
public function __construct(){
$this->run= new mysqli($this->host, $this->username, $this->password, $this->db_name);
if (mysqli_connect_errno()){
echo "database connection is fail";
exit;
}
}
public function select_data_from_db($table_name ,$run){
$stmt=$run->prepare("SELECT * FROM ".$table_name);
$stmt->execute();
$result = $stmt->get_result();
$total_count=$result->num_rows;
$result= array();
if($total_count>0){
while ($row = mysqli_fetch_array($query)) {
$result[] = $row;
}
}
return $result;
}
index.php
<?php $myrow=$obj->select_data_from_db("home_slider",$run); ?>
<tr>
<td><?php echo $myrow['id']; ?> </td>
<td><?php echo $myrow['title']; ?> </td>
<td><?php echo $myrow['description']; ?> </td>
</tr>
我遇到的错误:
Notice: Undefined variable: run in
D:Xampphtdocsadminslider_fetch_data.php on line 24.
Fatal error: Call to a member function prepare() on null in
D:Xampphtdocsadminconfig.php on line 116.
因为在您的class.php上,您使用此代码初始化运行
$this->run= new mysqli($this->host, $this->username, $this->password, $this->db_name);
我认为您不需要
public function select_data_from_db($table_name ,$run){}
删除第二个参数
应该是这个
public function select_data_from_db($table_name){}
这是正确的代码(如果我没有错,而mysqli工作(
class.php
class main{
public $host="localhost";
public $username="root";
public $password="";
public $db_name= "db_tvw";
private $img_path = 'slider_img_upload/';
public function __construct(){
$this->run= new mysqli($this->host, $this->username, $this->password, $this->db_name);
if (mysqli_connect_errno()){
echo "database connection is fail";
exit;
}
}
public function select_data_from_db($table_name){
$stmt=$this->run->prepare("SELECT * FROM ".$table_name);
$stmt->execute();
$result = $stmt->get_result();
$total_count=$result->num_rows;
$result= array();
if($total_count>0){
while ($row = mysqli_fetch_array($query)) {
$result[] = $row;
}
}
return $result;
}
...
在index.php上
<?php $myrow=$obj->select_data_from_db("home_slider"); ?>
<tr>
<td><?php echo $myrow['id']; ?> </td>
<td><?php echo $myrow['title']; ?> </td>
<td><?php echo $myrow['description']; ?> </td>
</tr>
<?php
$myrow = new main();
$myrow=$obj->select_data_from_db("home_slider",$myrow->run);
?>
<tr>
<td><?php echo $myrow['id']; ?> </td>
<td><?php echo $myrow['title']; ?> </td>
<td><?php echo $myrow['description']; ?> </td>
</tr>
您可以尝试