Well ive just started delving into the world of OOP with php. Its going great but im having trouble using the arrays.
This is the problem: I have a database class and within it the methods are as follows
query method
database connection method
fetchArray method
im having trouble with the fetch array method. for example:
<?php
$test = new database();
$query = $test->query("select * from table);
while($fetch = $test->fetcharray($query)){
........stuff...this works, $fetch[1]...etc;
}
?>however, i wanted to create a function that will return some data that can be reused.
<?php
function test(){
$test = new database();
$query = $test->query("select * from table);
while($fetch = $test->fetcharray($query)){
return $fetch;
}
}
?>
this returns hopefully the whole array of stuff from the database and im trying to use a foreach loop so that i can extract which ever data i want and display in whatever way i want.
<?php
include("functions.php\");
$test = test();
foreach($test as $tests){
echo \"<a href=\\"
$tests[0]">$tests[1]</a>\";
}
?>but this doesnt work it is only out putting the first row in the database not all rows?






JeevesBond posted this at 17:36—3rd August 2007.
He has: 3,491 posts
Joined: Jun 2002
This is the problem:
<?phpreturn $fetch;
?>
return means: stop whatever you're doing and return a result. This code will only ever reach the first row. I would advise against building an array containing the entire resultset of a query, you'll probably get out of memory errors in PHP. Generally it's better to keep the resultset with the database server and request one line of the result at a time, much more efficient! If you really need to do it that way though, try:
<?phpfunction test() {
$test = new database();
$query = $test->query("SELECT * FROM table\");
while ($fetch = $test->fetcharray($query)) {
$all_fetches[] = $fetch;
}
return $all_fetches;
}
?>
It's certainly desirable to abstract database connectivity though, particularly if you're planning on supporting multiple database backends (MySQL, PostgreSQL, MS SQL Server etc.) so your idea is a good one.
a Padded Cell our articles site!