嗨,我正在尝试制作一个小型 php 应用程序,例如 gridview,下面给出的代码可以正常工作,但我希望在创建该类的实例期间应该更改列名称
<?php
class datasource
{
public $cell;
function __construct($sql,$my)
{
if($my===false)
{
die("error: Could not connect ot the server".mysqli_connect_error());
}
else
{
if($result = $my->query($sql))
{
if($result->num_rows>0)
{
echo "<table border='1' cellspacing='0' cellpadding='0'>";
while($row=$result->fetch_array())
{
echo "<tr>";
$this->getname();
//echo "<td>".$row['OrderID']."</td>"; working
echo "<td>".$row[$this->cell]."</td>"; // at this line undefined index is shown
echo "</tr>";
}
echo "</table>";
$result->close();
}
else
{
die("error No Records Found");
}
}
else
{
die("error");
}
}
}//function connect
}
?>
<?php
$mysqli = new mysqli("localhost","root","9889922527","demo");
if($mysqli===false)
{
die("error".mysqli_connect_error());
}
else
{
$sql = "select * from `order`";
$n = new datasource($sql,$mysqli);
$n->cell = 'OrderID';
var_dump($n->cell);
}
$mysqli->close();
?>
在给定的代码中,不显示任何数据,并显示 undefined index 警告
最佳答案
这是因为您在通过构造函数调用查询后定义单元格值。
在类中创建另一个函数来进行查询。 然后在调用sql函数之前定义单元格值。
function __construct($sql,$my)
将此行替换为以下内容
function sqlFn($sql,$my)
然后
$n = new datasource($sql,$mysqli);
$n->cell = 'OrderID';
将上面替换为以下内容
$n = new datasource();
$n->cell = 'OrderID';
$n->sqlFn($sql,$mysqli);
关于php - 在php中使用类获取mysql表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311830/