I'm quite new to PHP OOP and I have a question regarding a simple MYSQL query. I have an index.php page where I want to output my results from my query.class file.
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
$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.
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
).
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...
OOP functions are the same as normal function. The function as you have it only 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:
while($row = mysql_fetch_array($q)) {
$output[] = $row[$rowName];
}
return $output;
use the MVC pattern.
http://php-html.net/tutorials/model-view-controller-in-php/
the database belongs to the Model
Good Luck
Or you can use my favorite database layer http://dibiphp.com/ . It's small but smart :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.