I'm pretty new to PHP OOP and i have to make a small web app for school.
One of the things i'm trying to do right is to select data from the database and display it in my front-end. I figured out how to display a single row but i wanted to display all rows in the table. How can i do that?
My function:
public function listJobs(){
$myDb = $this->_controlPanel->getMyDb();
$query = "Select * FROM jobs_offers";
$result = $myDb->performQuery($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$this->title=$row['title'];
$this->description=$row['description'];
$this->category=$row['category'];
$this->budget=$row['budget'];
}
My front-end:
<?php
header ('Content_type: text/html; charset=ISO-8859-1');
require_once ('utils/Autoloader.php');
session_start();
if (empty($myControlPanel)) {
try {
$myControlPanel = new classes_ControlPanel();
$myControlPanel->setMyDb(new classes_DbManager());
$myDbManager = $myControlPanel->getMyDb();
}
catch (Exception $e) {
echo $e->getMessage();
die();
}
}
$log = new classes_UserManager($myControlPanel);
$select = $log->listJobs();
$title = $log->title;
$description = $log->description;
$category = $log->category;
$budget = $log->budget;
?>
<body>
<div class="container-fluid">
<h2>
<h2><?php echo $title; ?> </h2>
<h2><?php echo $description; ?> </h2>
<h2><?php echo $category; ?> </h2>
<h2><?php echo $budget; ?> </h2>
</div>
First, the result will return an array of objects (PDO). You would want to return this array to your view. Or, in your case as a property of the object and not the single row like you did above.
Next, You want to use a foreach or while loop in the view. If you are using PDO (Php Data Object) you can do the following.
while($job = $result->fetch_assoc()) {
{
?>
<div class="container-fluid">
<h2>
<h2><?= $job->title; ?> </h2>
<h2><?= $job->description; ?> </h2>
<h2><?= $job->category; ?> </h2>
<h2><?= $job->budget; ?> </h2>
</div>
<?php
}
(Short Tags (<?=$var?>) are equivalent to <?php echo $var?>)
Reference: http://www.w3schools.com/php/php_mysql_select.asp
Related
I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
I have 2 SQLite- tables, one containing articles and one containing image URL's.
What I'd like to do is to do a foreach() to show the articles in order and show a set number of random images next to the article.
The images should be selected by checking similarity between the Article's and image's categories (column in the table) and then randomized. (The article catergory could be for example 'motorboats' and the img category 'boat').
How do I show the results from two different arrays?
The code for the articles is:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?>
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
To add the second array, I tried this, which didn't work, it only showed the results from the first array multiple times:
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt2 = $db->prepare('SELECT * FROM Object;');
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
<?php foreach($res as $article): ?>
<?php foreach($res2 as $object): ?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<?php echo $object['img'];?> <!-- For testing. The images should be filtered and a a few random images would be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
I guess it's not possible to use nested foreach() like this.
How will I manage this?
Also, If anyone knows on top of their head how to match the similarities between the arrays as described above, I'd be greatful. If not, I'll deal with this later.
You can fall a function inside the first foreach a pass category of the article to that function. Now in that functino collect all images in an array related
to the passed category and then return it by randomizing it. Code below ..
<?php foreach($res as $article): ?>
<?php
$img = get_img($article['category']);
?>
<div class="artikelContent">
<?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<img src="<?php echo $img; ?>" /> <!-- The return result will be shown here -->
<div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
</div>
<?php endforeach; ?>
<?php
function get_img($category){
$stmt2 = $db->prepare('SELECT * FROM Object WHERE category = '.$category);
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$rnd = array();
foreach($res2 as $object){
$rnd[] = $object['img'];
}
$n = rand(0,(count($rnd)-1));
return $rnd[$n];
}
?>
I am working in CodeIgniter framework and I have tried to apply all the other solutions I found on stack but I could not make it work so here is my problem...
I am trying to retrieve a record from MySQL database table called 'questions' based on uri segment. Then I am trying to display this record in a view. As far as I can tell, the uri segment is passed along everywhere it needs to be, and record is retrieved from database.
The problem comes up when I am trying to access the data from the controller, in my view.
Error I am getting for each echo in my loop in 'view_thread_view' is
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_thread_view.php
Any solutions would be greatly appreciated.
Here is my code:
Controller thread
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
Model data_model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , 'qid' , $quest));
{
return $q;
}
}
View view_thread_view
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
</div>
EDIT: QUESTION ANSWERED
Thanks to Girish Jangid fixed the problem this is the working code:
Controller
function view_thread()
{
$quest = $this->uri->segment(3);
echo $quest;// for checking if uri segment is passed
//$data = array();
if($query = $this->data_model->get_thread($quest))
{
$data['records'] = $query;
}
$this->load->view('view_thread_view', $data);
}
Model
public function get_thread($quest)
{
if($q = $this->db->get_where('questions' , array('qid' => $quest)));
{
return $q;
}
}
View
<div title="question_view">
<h1>Question View<h1>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $data->uname
?>
</div>
<?php endforeach; ?>
</div>
</div>
You should user db function to fetch results, please use CodeIgniter db Query Results functions, like this
if($records->num_rows() > 0){
foreach($records->result() as $data){
if(isset($data->title)) echo $data->title;
}
}
For more detail please read CodeIgniter Query Result function
Query Results
Try this code
<div title="question_view">
<h1>Question View<h1>
<?php if($records->num_rows() > 0) { ?>
<?php foreach($records->result() as $data) : ?>
<div>
<h2>Title</h2>
<?php
echo $data->title;
?>
</div>
<div>
<h2>Question</h2>
<?php
echo $data->contents
?>
</div>
<div>
<h2>Tags</h2>
<?php
echo $data->tags
?>
</div>
<div>
Thread owner
<?php
echo $records->uname
?>
</div>
<?php endforeach; ?>
<?php } ?>
</div>
$records is an array, not an object, therefore you cannot do $records->uname. You probably meant $data there too.
Edit: On second look, it appears $data is an array as well! Arrays are accessed via ['key'] not ->key
Also, your code is way over complicated.
<?php
foreach($records as $data){
$string = <<<STR
<div>
<h2>Title</h2>
{$data['title']}
</div>
...etc
STR;
echo $string;
}
http://www.php.net/manual/en/language.types.string.php
I have a query that selects 3 rows; but I only want to display the one row at a time, use the data from that row, then move to the next row, then repeat. How would this be accomplished? Table has 4 items in it.
PHP:
<?php
$server = "secret";
$user = "secret";
$pass = "secret";
$db = "secret";
$con=mysqli_connect($server,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'SELECT * FROM news ORDER BY id DESC LIMIT 3';
mysqli_select_db($con, $db);
$query = mysqli_query($con, $sql);
$number = 1;
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
mysqli_close($con);
?>
Attempt to display:
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
?>
Output of attempt:
Test
||
7/14/13
News 1
Testing to see if this will work lalalalalla
NOTE: Tried to repeat the attempt to see if it would work, but it displayed same as output but with a second one that was a duplicate except said News 2
Desired output look:
Newest Title | Newest Date
Newest news. Etc. Insert Big Paragraph of news here etc etc.
2nd Newest Title | 2nd Newest Date
2nd Newest news. Etc. Insert Big Paragraph of news here etc etc.
3rd Newest Title | 3rd Newest Date
3rd Newest news. Etc. Insert Big Paragraph of news here etc etc.
The problem is that you are overwriting your variables with each while() loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
}
so when you try to echo $id, $title, $news_date, and $post, you will only get the last row data
you either need to add your html in the while loop -
while ($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$title = $result['title'];
$news_date = $result['news_date'];
$post = $result['post'];
?>
<div name='title'><?php echo $title; ?></div> || <div name='news_date'><?php echo $news_date; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post; ?></p>
<?php
$number++;
}
or save them to an array
$id = array();
$title = array();
$news_date = array();
$post = array();
while ($result = mysqli_fetch_array($query)) {
$id[] = $result['id'];
$title[] = $result['title'];
$news_date[] = $result['news_date'];
$post[] = $result['post'];
}
and then access the array in your display
<div name='title'><?php echo $title[$number-1]; ?></div> || <div name='news_date'><?php echo $news_date[$number-1]; ?></div>
<p>News <?php echo $number; ?></p>
<p><?php echo $post[$number-1]; ?></p>
<?php
$number++;
?>
I used [$number-1] as I assume $number is starting at 1, and arrays are 0 based
edit here are ways to echo your html. It would be beneficial to visit the php documentation, as all of this is there. In these I set $number back to 0, but you can change it back to 1, and just change each of the $number->$number-1, and the $number+1->$number
using a for loop - http://php.net/manual/en/control-structures.for.php
<?php
for($number=0;$number<count($title);$number++){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a foreach loop - http://php.net/manual/en/control-structures.foreach.php
<?php
foreach($title as $number => $value{
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
}
?>
using a while loop - http://php.net/manual/en/control-structures.while.php
<?php
$number = 0;
while($number<count($title){
?>
<div name='title'><?php echo $title[$number]; ?></div> || <div name='news_date'><?php echo $news_date[$number]; ?></div>
<p>News <?php echo $number+1; ?></p>
<p><?php echo $post[$number]; ?></p>
<?php
$number++;
}
?>
each of the above was done by closing out of php, and writing the html, and then opening php again. You could also just stay in php, and echo the html - http://php.net/manual/en/function.echo.php
<?php
for($number=0;$number<count($title);$number++){
echo "<div name='title'>".$title[$number]."</div> || <div name='news_date'>".$news_date[$number]."</div>";
echo "<p>News ".($number+1)."</p>";
echo "<p>".$post[$number]."</p>";
}
?>
Having a little trouble displaying data from a table. Been looking at my code for the past few hours and can't seem to see the problem. What I am trying to do is when a team is clicked on it will go into the players table and display any player that has that team name on the team page. I keep getting a blank page:
index.php
This is the case that launches the team_view.php
case 'view_team':
$team = $_GET['name'];
$teams = get_players_by_team($team);
include('team_view.php');
break;
team_view.php
<?php include '../../view/header.php'; ?>
<?php include '../../view/sidebar_admin.php'; ?>
<div id="content">
<h1>Team Roster</h1>
<!-- display product -->
<?php include '../../view/team.php'; ?>
<!-- display buttons -->
</div>
<?php include '../../view/footer.php'; ?>
team.php
<?php
$team = $team['name'];
$first = $player['first'];
$last = $player['last'];
$age = $player['age'];
$position = $player['position'];
$team = $player['team'];
?>
<table>
<?php foreach ($players as $player) :
?>
<tr>
<td id="product_image_column" >
<img src="images/<?php echo $player['player_id']; ?>_s.png"
alt=" ">
</td>
<td>
<p>
<a href="?action=view_player&player_id=<?php echo
$player['player_id']; ?>">
<?php echo $player['first']; ?>
<?php echo $player['last']; ?>
</a>
</p>
</td>
</tr>
<?php endforeach; ?>
</table>
product_db.php
<?php
function get_players_by_team($team) {
global $db;
$query = 'SELECT * FROM players
WHERE team = :team';
try {
$statement = $db->prepare($query);
$statement->bindValue(':team', $team);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
display_db_error($e->getMessage());
}
}
You never define $players it looks like what you are expecting to be $players is actually $teams.
$teams = get_players_by_team($team);
Additionally youre using $player at the top of the script instead of inside the loop which makes no sense.