简体   繁体   English

PHP OOP Mysql查询

[英]PHP OOP Mysql Query

I'm quite new to PHP OOP and I have a question regarding a simple MYSQL query. 我是PHP OOP的新手,我对一个简单的MYSQL查询有疑问。 I have an index.php page where I want to output my results from my query.class file. 我有一个index.php页面,我想从query.class文件输出我的结果。

Here is my method, 这是我的方法,

 public function Query($rowName) {

   $q = mysql_query("SELECT * from p_tuts");

   while($row = mysql_fetch_array($q)) {

       echo $row[$rowName];
   }
 }

Now this works fine and I can call it though my index.php file 现在这工作正常,我可以通过我的index.php文件调用它

$Database->Query('tut_content');

But my issue is I want to wrap each content block in DIV containers and don't want to have to echo the HTML code in the class file, so I want to really echo the row's data in the index file, but unsure how to do this. 但我的问题是我想将每个内容块包装在DIV容器中,并且不希望在类文件中回显HTML代码,所以我想在索引文件中真正回显行的数据,但不确定如何做这个。

Kind regards 亲切的问候

Pass the rows back as an array. 将行作为数组传回。

public function Query($colName) {

    $q = mysql_query("SELECT * from p_tuts");
    $rows = array();
    while($row = mysql_fetch_assoc($q)) {
        $rows[] = $row[$colName];
    }
    return $rows;
}

It's better this way anyway, because it keeps database code away from output code (ie echo ). 无论如何,这样做更好,因为它使数据库代码远离输出代码(即echo )。

Then output it like so: 然后像这样输出:

<?php
$results = $Database->Query('tut_content');
foreach ($results as $result): ?>
    <div><?php echo $result; ?></div>
<?php endforeach; ?>

You dont want to be doing the echo in your class. 你不想在你的课堂上做回声。

You want to return the row... 你想要归还那一行......

This way 这条路

 $Database->Query('tut_content'); 

Can be wrapped in the DIV / whatever you need... 可以包裹在DIV /你需要的任何东西......

OOP functions are the same as normal function. OOP功能与普通功能相同。 The function as you have it only echos $row[$rowname] . 你只有它的功能echos $row[$rowname] You either want to modify it to have it echo <div>$row[$rowname]</div> or have it return the row values as an array: 您要么修改它以使其回显<div>$row[$rowname]</div>要么让它将行值作为数组返回:

while($row = mysql_fetch_array($q)) {
   $output[] = $row[$rowName];
}
return $output;

use the MVC pattern. 使用MVC模式。

http://php-html.net/tutorials/model-view-controller-in-php/ http://php-html.net/tutorials/model-view-controller-in-php/

the database belongs to the Model 数据库属于Model

Good Luck 祝好运

Or you can use my favorite database layer http://dibiphp.com/ . 或者您可以使用我最喜欢的数据库层http://dibiphp.com/ It's small but smart :-) 它很小但很聪明:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM