I am trying to follow help found in this question: how can i return multiple database record from a class in OOP programming but I cannot seem to get it working properly.
I have a database table called 'jobs' and I want to retrieve all the data from that table display it to my users.
As of right now, when I use this code:
/* Get All Jobs */
public function getJobs($page) {
$db = new DBConnection;
$str = new str_format;
$validate = new data_validation;
$sql = "SELECT * FROM jobs ORDER BY job_id DESC";
$paginate = new Paginate($db, $sql, $page);
$result = $paginate->get_results();
$jobArr = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row = $validate->escapeArray($row);
$job = new Job($db);
$job->$row['job_id'];
$job->$row['job_title'];
$job->$row['date'];
$job->$row['industry'];
$job->$row['company'];
$job->$row['photo'];
$job->$row['content'];
$jobArr[] = $job;
return $jobArr ;
}//close while loop
/*=== build the pagination links ===*/
echo "<div class='pagination_container'>";
echo "<span class='pagination'>";
echo $paginate->show_pages();
echo "</span>";
echo "</div>";
/*=== end build pagination links ===*/
}
I only get 1 entry and a bunch of errors that look like this Notice: Undefined property: Job::4ドル in /home/hirestar/public_html/builder/classes/job.class.php on line 54
The class is named Job
if that has anything to do with it. But I cannot seem to get this work properly.
How can I return all the jobs in my database from this function?
1 Answer 1
First off, you are calling return
within your while loop, so it will bail out on the first loop execution. This is why you are only getting one result. You should call return after the while loop so that you can build your entire array.
Second, you are likely getting the Undefined property
errors because of this code:
$job->$row['job_id'];
$job->$row['job_title'];
$job->$row['date'];
$job->$row['industry'];
$job->$row['company'];
$job->$row['photo'];
$job->$row['content'];
Here you are probably wanting to do something like:
$job->job_id = $row['job_id'];
Right now what you are trying to do is read the property from $job
with a name equal to the value of $row[*]
. So say the row_id
is 4, you are in essence performing:
$job->4;
which is obviously meaningless.