Reputation: 299
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
Upvotes: 0
Views: 4359
Reputation: 10091
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 (i.e. echo
).
Then output it like so:
<?php
$results = $Database->Query('tut_content');
foreach ($results as $result): ?>
<div><?php echo $result; ?></div>
<?php endforeach; ?>
Upvotes: 2
Reputation: 590
Or you can use my favorite database layer http://dibiphp.com/. It's small but smart :-)
Upvotes: 0
Reputation: 20102
use the MVC pattern.
http://php-html.net/tutorials/model-view-controller-in-php/
the database belongs to the Model
Good Luck
Upvotes: 0
Reputation: 27017
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;
Upvotes: 0
Reputation: 17992
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...
Upvotes: 0