我想使用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:\Xampp\htdocs\admin\slider_fetch_data.php on line 24.
Fatal error: Call to a member function prepare() on null in
D:\Xampp\htdocs\admin\config.php on line 116.
答案 0 :(得分:0)
<?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>
你可以尝试一下
答案 1 :(得分:0)
因为在你的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工作)
on 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;
}
...
on 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>