首先,我要感谢所有关注这篇文章的人。我将代码从php5迁移到php7时遇到了问题。我实际上不知道我的代码中出了什么问题
class database {
public function __construct () {
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'crm');
}
public function view_chart(){
$data = mysqli_query($conn, "select * from t_chart");
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
view_chart()
不起作用,但它也可以在php4中运行。这里的任何人都可以告诉我这段代码出了什么问题?我非常感谢与此问题相关的任何答案。谢谢。
答案 0 :(得分:0)
您必须将$conn
声明为类成员变量,以便可以从其他类函数访问。
<强>执行:强>
class database {
public $conn; // added
public function __construct () {
$this->conn = mysqli_connect("localhost", "root", ""); // modified
mysqli_select_db($this->conn, 'crm'); // modified
}
public function view_chart(){
$data = mysqli_query($this->conn, "select * from t_chart"); // modified
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
foreach($db->view_chart() as $x){
echo "<option value='$x[id_chart_cat]'>$x[chart_name]</option>";
}
答案 1 :(得分:0)
当我将PHP脚本更新为PHP7时,我遇到了
的问题mysqli_fetch_array()
你应该用类似
的功能替换它mysqli_fetch_assoc()
答案 2 :(得分:0)
您是否先检查并确保正在建立连接?以及我如何在7中总是这样做
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
然后你可以做
<?php
$query = "SELECT * FROM whatever";
$result = $conn->query($query);
$hasil = [];
?>
然后你应该能够做到
while($row = $result->fetch_assoc()){
$hasil[] = $row;
}
return $hasil;
然后进入你的foreach ...不确定这是你想要的,但希望它有所帮助