cod*_*blr 0 php mysql oop resultset
我正在尝试创建一种更简洁的方式来进行数百个db调用.我不是每次想要输出单个字段时都写出整个查询,而是尝试将代码移植到一个完成所有查询工作的类中.这是我到目前为止的课程:
class Listing {
/* Connect to the database */
private $mysql;
function __construct() {
$this->mysql = new mysqli(DB_LOC, DB_USER, DB_PASS, DB) or die('Could not connect');
}
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$info = $result->fetch_object() or die('Could not create object');
return $info;
}
}
Run Code Online (Sandbox Code Playgroud)
这样可以轻松地从单行访问我想要的任何信息.
$listing = new Listing;
echo $listing->getListingInfo('','Books')->title;
Run Code Online (Sandbox Code Playgroud)
这将输出"书籍"类别中第一个列表的标题.但是如果我想输出该列表的价格,我必须再次调用getListingInfo().这会对db进行另一次查询,并再次仅返回第一行.
这比每次编写整个查询简洁得多,但我觉得我可能经常调用db.有没有更好的方法从我的类输出数据,并且仍然可以简洁地访问它(可能将所有行输出到数组并返回数组)?如果是,怎么样?