PHP/MYSQL: showing data out of 2 tables - php

This is my first question and I tried to make it clear enough so you guys/girls can understand it. If I am missing something or doing something wrong please let me know! Its my first question.
What I want:
I want it to show the voornaam out of the table Klanten to show next to the other ones out of the table onderwerpen. For example I want the voornaam to show next to the henk and koken. So I expect it to show the data out 2 different tablesin the block you can see on the pic.
I tried using a foreach loop with 2 conditions but that it not possible. So I was wondering what the solution in this case needs to be. Because It works with 1 condition in the foreach but it is not possible to do this with 2 conditions.
What I have tried:
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Onderwerpen</h3>
</div><!-- /.box-header -->
<div class="box-body">
<?php
$onderrwerp = $app->get_onderwerpen();
$klantten = $app->get_klanten();
foreach($onderrwerp as $onderwerp and $klantten as $klant){
echo '<div class="well well-sm">';
echo '' . $onderwerp['voornaam'].'';
echo '<h3>'.$onderwerp['naam'].'</h3><br>';
echo '' .$onderwerp['naam'].'';
echo '</div>';
}
?>
The code:
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Onderwerpen</h3>
</div><!-- /.box-header -->
<div class="box-body">
<?php
$onderrwerp = $app->get_onderwerpen();
foreach($onderrwerp as $onderwerp){
echo '<div class="well well-sm">';
echo '<h3>'.$onderwerp['naam'].'</h3><br>';
echo '' .$onderwerp['naam'].'';
echo '</div>';
}
?>
The functions:
public function get_onderwerpen(){
$getOnderwerp = $this->database->query("SELECT * FROM onderwerpen ORDER BY id ASC");
$onderwerpen = $this->database->resultset();
return $onderwerpen;
}
public function get_klanten(){
$getKlant = $this->database->query("SELECT * FROM klanten ORDER BY punten DESC");
$klanten = $this->database->resultset();
return $klanten;
}

So you have two tables. they are connected using the ledenpagina_id field I assume looking at your data.
What you are looking for is to JOIN the two tables so that with one query you can fetch the data you want and then do a loop to show the data:
SELECT *
FROM klanten JOIN onderwerpen
ON klanten.lendenpagina_id = onderwerpen.lendenpagina_id
You can then add WHERE clause, ORDER_BY and so on.

Related

PHP [ sorting data from database as collapsible bootstrap 4 cards ] [duplicate]

This question already has answers here:
List records grouped by category name
(2 answers)
Closed 2 years ago.
As the title says i'm developing shopping cart for a website and the cart contains all the products that been ordered from different companies like this :- screenshot
so as you see i'm trying to sort all products that is from the same company underneath each other as the specific company bill my question how can i accomplish that ?
what i have tried :-
nothing to mention actually i'm really so confused here i don't now what i'm going to (loop for or something like that .. )
i hope i explained what i want to accomplish, if not (screenshot)
code :- php PDOquery
<?
$accountid = '8';
require_once '..\Config.php';
// WHERE chemicalcom='$variable' OR name='$variable'
$dbCon = "mysql:host=$host;dbname=$db_name";
$variable = "Efexor";
$PDOCon = new PDO($dbCon, $username, $password);
$query = $PDOCon->prepare("SELECT * FROM basket WHERE accountid ='$accountid'");
$query->execute();
$basketItems = $query->fetchAll();
?>
code :- index.php
<? foreach($basketItems as $item){
echo'<h3>Bill('.$item['companyexported'].')</h3>
<div class="card">
<div class="row">
<div class="col-6"><img src="'.$item['imgpath'].'" class="productimg" alt=""></div>
<div class="col-auto">
<div class="card-title">
<div class="row">'.$item['name'].'</div>
<div class="row">'.$item['chemicalcom'].'</div>
<div class="row">'.$item['concentration'].'</div>
<br>
<div class="row">'.$item['price'].' $
</div>
<span class="badge badge-info qty">'.$item['qty'].'</span>
</div>
</div>
</div>
</div>';}?>
Thanks .
First, you will need to update your sql to order by the company, that will make the php simpler.
SELECT * FROM basket WHERE accountid ='$accountid' order by companyexported
then in your php, you only want to show the company once, so you create an empty variable and check it. If that variable doesn't contain a matching company name, show the company and set that variable to the current company name.
<?
$curr_co = "";
foreach($basketItems as $item){
if($curr_co != $item['companyexported']){
echo '<h3>Bill('.$item['companyexported'].')</h3>';
$curr_co = $item['companyexported'];
}
echo '<div class="card">
<div class="row">
<div class="col-6"><img src="'.$item['imgpath'].'" class="productimg" alt=""></div>
<div class="col-auto">
<div class="card-title">
<div class="row">'.$item['name'].'</div>
<div class="row">'.$item['chemicalcom'].'</div>
<div class="row">'.$item['concentration'].'</div>
<br>
<div class="row">'.$item['price'].' $
</div>
<span class="badge badge-info qty">'.$item['qty'].'</span>
</div>
</div>
</div>
</div>';}?>

issue when ifisset added to code

some explenation
http://koopjesidee.nl/images/6755185029021696.jpg
in my database i have a column named new_label
when its a new product its set as new
when no new product the colums is empty
i want the class="main-label new-label" to be disabled when there nothing in that column
now as you see from the image, there is always a orange cirkel (as set in class main-label) even when column is empty
This is my code
<!-- select products from database -->
<?php
$query = "select * from contentwhere cat = 4 order by rand() LIMIT 18";
$result = $db->query($query);
while($row = $result->fetch_array())
{
$url =detail($row);
<!-- content on main page -->
echo '
<div class="item">
<div class="product-item">
<div class="main-label new-label"><span>'.$row['new_label'].'</span></div>
<div class="product-image"><img src="'.$row['picture_big'].'" alt="'.$row['name'].'"></div>
<div class="product-item-details">
<div class="product-item-name"> '.$row['name'].' </div>
<div class="price-box"> <span class="price">€'.$row['price'].'</span> <del class="price old-price">'.$row['from_price'].'</del> </div>
</div>
</div>
</div>';
}?>
I want add if isset like this so when there is no text in class=new-label class main-label new-label is disabled column in my database is new_label
<div class="item">
<div class="product-item">
<!-- ISSUE -->
if (isset($_row['new_label']!='')) {
<div class="main-label new-label"><span>'.$row['new_label'].'</span></div>;
} else {
<div class="main-label new-label"><span></span></div>;
}
<!-- HTTP ERROR 500 -->
<div class="product-image"><img src="'.$row['picture_big'].'" alt="'.$row['name'].'">
You cannot use isset() on the result of an expression, it can only be a variable. In fact, it will result in a fatal error if you try (which is probably why you received a 500 server error).
So you can probably change this line:
if (isset($_row['new_label']!='')) {
To this:
if (isset($_row['new_label'])) {
isset() returns a boolean anyway, so it doesn't make sense to compare it to a string.
Read more: http://php.net/manual/en/function.isset.php
SOLVED MYSELF GUYS
'.$row['new_label'].'';} ?>
thanks anyway

Return Value in Column B Table 2, where column A Table 1, matches Column A Table 2

What I'm trying to do: Where category (projects) matches id (markets) echo category (markets).
Table 1 Sample (projects table)
Table 2 Sample (markets table)
Sample of PHP Code
$num_rec_per_page=5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$category= GET('category');
if ($category !== null) {
$sql = "SELECT * FROM projects WHERE category='$category' LIMIT $start_from, $num_rec_per_page";
} else {
$sql = "SELECT * FROM projects LIMIT $start_from, $num_rec_per_page";
}
$sql_query = mysql_query($sql);
$post = $sql_query;
$sql1 = "SELECT * FROM markets";
$sql_query1 = mysql_query($sql1);
$marketsinfo = mysql_fetch_array($sql_query1);
In my code below, I've tried putting a while loop within the main while loop since we have to find out what category its in then display it for each blog post.
It only worked for the first result, and then I did some research online and found that it is very poor design to do this.
Where I'm currently at with displaying the result (see code in between hyphens):
<!-- Blog - Start -->
<?php while ($post = mysql_fetch_array($sql_query)) {?>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 blog blog_altered blog_left">
<div class="row">
<!-- Blog Image - Start -->
<div class=" col-lg-6 col-md-6 col-sm-10 col-xs-12 pic inviewport animated delay1" data-effect="fadeIn">
<img alt="blog-image" class="img-responsive" src="<?php echo $post['imageoutside'] ?>">
</div>
<!-- Blog Image - End -->
<!-- Blog Info - Start -->
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 inviewport animated delay1" data-effect="fadeIn">
<div class="info">
----------------------------------------------------------------------
<span class="date">
<?php
if($post['category'] === $marketsinfo['id']){
echo $marketsinfo['category'];
}
?>
</span>
----------------------------------------------------------------------
<h4 class="title"><?php echo $post['title'] ?></h4>
<p><?php echo $post['summary'] ?></p>
<a class="btn btn-primary text-on-primary" href="projects/readmore.php?job=<?php echo $post['job'] ?>">Read More</a>
</div>
</div>
<!-- Blog Info - End -->
</div>
</div>
<?php } ?>
<!-- Blog - End -->
Hope I've been thorough enough without being confusing. How can a noob accomplish this? I'll take any pointers you have!!
If you use a join, you can get the category text in one query and avoid all the looping in PHP.
A LEFT Join will return all records from Projects and only those records which match from markets. So if a projects category doesn't exist in markets, a NULL value will be returned.
If you used a INNER JOIN, only records which have corresponding values in BOTH tables would be returned.
Rule of thumb: get the data you need from the database in 1 trip when you need it. Format in PHP, Datagrab in SQL. Don't get more than you need, and don't get less.
SELECT P.Job, M.ID as Markets_ID, M.Category, P.Title
FROM projects P
LEFT JOIN Markets M
on P.Category =M.ID
WHERE P.category='$category'
LIMIT $start_from, $num_rec_per_page"
Note: you will need to put a table alias on category in the where clause. I'm assuming your passing in the ID so P.Category was used.
do you want join table projects with tables market by category?
may be u can do this
SELECT p.id as id
, m.category as category
from projects as p
left
join markets as m
on p.category = m.id
WHERE m.category='$category'
LIMIT $start_from
, $num_rec_per_page

How do I retrieve certain information from database using the ID of the table to extract certain information?

I am currently doing a small web project and am struggling to get individual names from the database to appear in different panels of my website. There are 18 different names in the table I need and I need to display them in 18 individual panels as shown here Screenshot of Panels.
I am using MvC and have this SQL statement in my model -
public function fetchMonarch($Monarch, $MonarchID)
{
$sqlQuery = "SELECT * FROM monarchy WHERE Monarch = '" . $Monarch ."'AND MonarchID = '".$MonarchID."'";
$statement = $this->_dbHandle->prepare($sqlQuery); //Prepare PDO statement
$statement->execute(); //Executes PDO statement
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[] = new LoginData($row);
}
return $dataSet;
}
How would I set it up in my controller so that I can access the names I want to in each panel using Session ?
Any ideas of how to do this even if you think I maybe going about this incorrectly would be a massive help as I have hit a snag.
This is my panel code within the HTML -
<div id="monarch1">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Panel Title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
</div>
<div id="monarch2">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
</div>
I believe the solution you are after is something like this:
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[$row['MonarchID'] = new LoginData($row); // note the ID
}
Then within your HTML:
foreach ($dataSet as $id=>$monarch){
echo '<div id="monarch2">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">'.$monarch->objectData.'</h3>
</div>
<div class="panel-body">
'.$monarch->objectData.'
</div>
</div>
</div>';
}
$monarch->objectData would reference your keys in LoginData($row) or alternatively store a new key in $allData['MonarchID'] = $row; and then foreach on $alldata and instead of $monarch->objectData you would use $monarch['FieldInfo'].
If you need to specifically place your elements - use ordering in the SQL or alternatively you can access $dataSet['MonarchID']->objectData to place your content in specific places.

php pass id into modal

I'm stuck again! So hopefully you awesome people can help me...
So far what I have is a search function that queries the database, and returns results, which works fine, and then the user can click one of the results, which takes them through to a new detailed page of what they clicked, for example a brand. Then on the detailed page, it returns all of that brands details (using $_GET['id']) and a new set of data, from a relational table, with a list of all the offers corresponding to that brand, which also works. But then I get stuck, I want the user to be able to click on each offer, and have the details of that offer load into a modal... I've tried using the $_GET['id'] for the offers id, but obviously, with it being on the same page (i presume), it passes the id of the brand / parent instead of the offer.
This is the code that calls back all the offers relating to the brand
$offers_sql = 'SELECT * FROM codes WHERE client_id LIKE :client_id AND CURDATE() between start AND expiry';
$offersq = $db->prepare($offers_sql);
$offers_params = array(':client_id' => $id);
$offersq->execute($offers_params);
$results = $offersq->fetchAll(PDO::FETCH_ASSOC);
if(count($results) < 1) {
$output = "<h4>no current offers available</h4>";
}
else {
foreach($results as $r) {
$title = $r['title'];
$code = $r['textcode'];
$offer_id = $r['id'];
$expiry = $r['expiry'];
$date = new DateTime($expiry);
$output .= '<h4>' . $title . '</h4><hr>';
}
}
} catch (PDOException $e) {
echo "failed to load offers";
}
?>
and this is the code i was using for the modal
require('inc/connect/config.php');
include('inc/result.php');
$page_title = "Title - " . $name . " Offers";
include('inc/style.php');
include('inc/header.php');
include('inc/offers.php');
?>
<!-- Intro Section -->
<section class="intro-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3 class="navbar-fixed-top">Latest Deals</h3>
<h1><?php echo $name; ?></h1>
</div>
</div>
</div>
</section>
<section class="offer-section">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-3 col-lg-6 col-lg-offset-3">
<?php echo $output; ?>
</div>
</div>
</div>
</section>
<div class="md-modal md-effect-flip" id="offer">
<div class="md-content">
<h4><?php $offer = (int) $_GET['id'];
echo $offer ?></h4>
<button type="submit" class="modal-btn md-close navbar-fixed-bottom" value="submit"><p>close</p></button>
</div>
</div>
<?php include('inc/footer.php'); ?>
The code that returns the details of the brand is on a separate page, but i can include that if necessary.
What am i doing wrong? Please go easy on me, I am relatively new to php.
Thanks in advance
Kaylee
Make Changes, Where Output is declared in else condition. (Changes Done)
$output='<h4><a class="OfferIdClass" data-OfferID="<?echo $offer_id;?>" href="#offer" data-modal="offer" data-toggle="modal">'.$title.'</a></h4>';
// Add This to footer.php (Changes Done)
<div class="md-modal md-effect-flip" id="offer">
<div class="md-content">
</div>
</div>
//Add this below in that page, where you are clicking Modal.
//Changes Done
<script>
$('.OfferIdClass').click(function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").html(result); //Here, Changes Done
}});
});
</script>
//Create one Open-Offer.php page. (Changes Done)
Open-Offer.php
<?
extract($_GET);
<h4><?php $offer = (int) $_GET['id'];
echo $offer ?></h4>
<button type="submit" class="modal-btn md-close navbar-fixed-bottom" value="submit"><p>close</p></button>
?>

Categories