Below is the code in question. I'm trying to get a simple division from two columns, but in an already existing (and functioning) php query set up. I can not seem to get it to work no matter what I do. I am not a strong coder by any means. The code outputs a capital S.
<?php
include("db_reader.php");
$data = '';
$query = "SELECT * FROM users WHERE team like 'Replay%'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result) > 0)
{
$number = 1;
while($row = mysql_fetch_assoc($result))
{
$kdresult = "SELECT (kills / deaths) AS kdresult FROM users WHERE team like 'Replay%'";
$data .= '
<div class="col-xs-12 col-sm-12 col-md-3">
<div id="memberCard-1" class="card">
<div class="face front">
<div class="panel panel-default text-center" style="border: 1px solid red;">
<div class="panel-heading" style="background-color:#000;color:#ff0000;">
<h3 class="panel-title">'.$row['name'].'</h3>
</div>
<ul class="list-group">
<li class="list-group-item">Position</li>
<li class="list-group-item">Info</li>
<li class="list-group-item"></li>
<li class="list-group-item">Kills: '.$row['kills'].'</li>
<li class="list-group-item">Deaths: '.$row['deaths'].'</li>
<li class="list-group-item">KD: '.$kdresult['kdresult'].'</li>
It looks like your $kdresult is a query but it's not being run anywhere.
Could you change your $query to be:
$query = "SELECT kills, deaths, kills/deaths AS kdresult FROM users WHERE team like 'Replay%'";
It's better practice to specify the columns you actually need in a SELECT statement rather than SELECT *. This also means your data is in a single query and not in two queries.
Related
I have these cards with data that comes from a database. This is the reason it is in a while loop.
Now my problem is that I don't have a clue how to add pagination to this. If some of you guys have any suggestions or answers please let me know.
$start_from = ($page - 1)*$record_per_page;
$query = "SELECT organisation_name, organisation_logo, organisation_url FROM `organisations`";
$result = mysqli_query($conn, $query);
if ($result ->num_rows > 0) {
echo '<div id="myItems">';
echo '<div class="row">';
while ($row = $result-> fetch_assoc()) {
echo '
<div class="col-md-6">
<div class="card rounded-lg mt-3">
<div class="card-body p-0 shadow">
<div class="row">
<div class="col-md-4 p-0">
<img src="../img/';
if ($row['organisation_logo'] == '') {
echo 'stock/no-image-icon.png"';
} else {
echo 'uploads/'.$row['organisation_logo'].'"';
}
echo 'class="border p-3" style=" width: 150px; height: 150px;">
</div>
<div class="col-md-8">
<h3 class="card-title mt-3">'.$row["organisation_name"].' <a class="text-dark" href="http://'.$row["organisation_url"].'" target="_blank"><i class="fas fa-external-link-alt" style="font-size: 18px;"></i></a></h3>
<p>Current active surveys: <b>0</b></p>
<b>View <i class="fas fa-arrow-circle-right"></i></b>
</div>
</div>
</div>
</div>
</div>';
}
echo '</div>';
}
else {
echo 'nothing here';
}
You need to use LIMIT and OFFSET functionality in your SQL query. Limit determines how many elements you want to show on one site. Offset is point from where you want to get your items. So, for example – if You want 5 items, and you are on page 3, you have to add LIMIT 5 OFFSET 10. You calculate offset with (page_number-1) * limit equation. If you want to count how many pages you have, you must get total pages number, and use something like $pages = ceil($total / $limit). There are a lot of examples on stackoverflow.
I think this one can be very helpful – Simple PHP Pagination script
You also don't need to do all the calculation on your own, there are plany of pagination library for PHP, check look for them.
Hope it helps you a little.
Solved!!
Thanks, guys. This was my first question on here. Let me know if I'm not formatting this correctly or something. Here's my finished code:
Answer:
$sql = 'SELECT a.*, GROUP_CONCAT(t.name) as track_name FROM albums AS a LEFT JOIN tracks AS t ON a.album_id = t.album_id GROUP BY a.album_id';
foreach ($conn->query($sql) as $row) { ?>
<div class="container">
<div class="row">
<div class="col-6">
<img src="../images/<?= $row['album_cover']?>" alt="Card image cap" style="width:100%;">
<!--shadow-->
<div class="shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body" style="padding-left:10px;">
<h4 class="card-title"><?= $row['album_name'] ?></h4>
<b><?= print_r($row['album_name'] . ' (' . $row['record_label'] . ') (' . $row['year_released'] . ')', true); ?><br><br></b>
<ul class="list-group list-group-flush">
<?php
$tracks = explode(",", $row['track_name']);
$numTracks = count($tracks);
$i = 0;
while ($i < $numTracks) { ?>
<li class="list-group-item">
<?php
echo $tracks[$i];
$i++;
?>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
Question (Solved): I am working on a project for school. I have to revamp an existing discography site (Queen) using php. The part I'm stuck on now is pulling album info from a database and using it to populate the page with each album along with the track names for the album. I have my album info in one table called albums, and all the tracks for every album in another table called tracks, with album_id as a foreign key.
I can get to the point where it's generating the album title from the album table in my database, but I have no idea how to get the tracks for each album.
This is my SQL query:
$sql = '
SELECT a.album_id
, a.album_name
, a.year_released
, a.record_label
, a.album_cover
, t.name
, t.album_id
FROM albums AS a
LEFT
JOIN tracks AS t
USING (album_id)
';
And here is the part in that is supposed to generate the albums:
<?php
foreach ($conn->query($sql) as $row) { ?>
<div class="col-6">
<img src="../images/<?= $row['album_cover']?>" alt="Card image cap" style="width:100%;">
<!--shadow-->
<div class="shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body" style="padding-left:10px;">
<h4 class="card-title"><?= $row['album_name'] ?></h4>
<b><?= print_r($row['album_name'] . ' (' . $row['record_label'] . ') (' . $row['year_released'] . ')', true); ?><br><br></b>
<ul class="list-group list-group-flush">
<li class="list-group-item">Innuendo</li> <!-- these are just placeholders for the tracks because I don't know what to do here! -->
<li class="list-group-item">I'm Going Slightly Mad </li>
<li class="list-group-item">Headlong</li>
<li class="list-group-item">I Can't Live With You</li>
<li class="list-group-item">Don't Try So Hard </li>
<li class="list-group-item">Ride The Wild Wind</li>
<li class="list-group-item">All God's People</li>
<li class="list-group-item">These Are The Days Of Our Lives</li>
<li class="list-group-item">Delilah</li>
<li class="list-group-item">The Hitman</li>
<li class="list-group-item">Bijou</li>
<li class="list-group-item">The Show Must Go On </li>
</ul>
</div>
</div>
</div>
<?php
}
?>
As it stands, my page is being populated by the same album info over and over because the foreach is iterating through every row in both tables. How do I generate specific tracks based on unique albums?
Try using ON instead of USING:
$sql = 'SELECT * FROM albums AS a LEFT JOIN tracks AS t ON a.album_id = t.album_id';
This should join the two tables correctly. If there are multiple tracks for each album you will need to either query them separately or join the tracks into a group using GROUP_CONCAT. Here would be the query to accomplish this:
$sql = 'SELECT a.*, GROUP_CONCAT(t.name) as track_name FROM albums AS a LEFT JOIN tracks AS t ON a.album_id = t.album_id GROUP BY a.album_id';
Just as a side note I HIGHLY recommend using PDO for all sql related things. Here is a link to set it up and use it for safer sql queries: https://www.w3resource.com/php/pdo/php-pdo.php
ADDED TO LOOP THROUGH TRACKS
First you would need to take the variable and explode it into an array (place inside your loop):
$tracks = explode(',',$row['track_name']);
foreach($tracks as $track_name){
echo $track_name;
}
Now you should be able to do anything you want with these tracks. You could easily place them in a table or in a div.
You call $conn->query($sql) every loop which will return the whole result set again. Also, use while loop like below, not foreach loop since $conn->query() return a mysqli_reuslt object, not an array.
$sql = 'SELECT a.album_id, a.album_name, a.year_released, a.record_label, a.album_cover, t.name, t.album_id
FROM albums AS a LEFT JOIN tracks AS t USING (album_id)';
$result = $conn->query($sql) // return a mysqli_result object
while($row = $result->fetch_assoc()) {
// Your loop content
}
If you insist on using foreach loop:
$result = $conn->query($sql) // return a mysqli_result object
$rows=$result->fetch_all(MYSQLI_ASSOC); //return an array
foreach($rows as $row) {
//content
}
Two ways in which you could approach this problem:
Have 2 loops - the first looping through a simple query to the albums table (no joins), then within that loop perform a second query to the database to get all the tracks. (The downside being that you will be making more queries to the database)
Alternatively, change your query so you are selecting from the tracks table and then the join is on the albums table. To have it so the album title is only printed once for each album, you would need to sort the tracks by album, and then have an if statement to check when the loop has started processing a different album.
You must change your design a little.
First you get the first row get the album data and the first track
After that you grap the rest of the track and close the html tags
$sql = 'SELECT a.album_id, a.album_name, a.year_released, a.record_label
,a.album_cover, t.name, t.album_id
FROM albums AS a LEFT JOIN tracks AS t USING (album_id)';
$result = $conn->query($sql) // get a result from the mysql server
$row = $result->fetch_assoc();
?>
<div class="col-6">
<img src="../images/<?= $row['album_cover']?>" alt="Card image cap" style="width:100%;">
<!--shadow-->
<div class="shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-body" style="padding-left:10px;">
<h4 class="card-title"><?= $row['album_name'] ?></h4>
<b><?= print_r($row['album_name'] . ' (' . $row['record_label'] .
') (' . $row['year_released'] . ')', true); ?><br><br></b>
<ul class="list-group list-group-flush">
<li class="list-group-item"><?= $row['name']?></li>
<?php
//get the rest of teh tracks
while($row = $result->fetch_assoc()) {?>
<li class="list-group-item"><?= $row['name']?></li>
<?php
} //end if While
?>
</ul>
</div>
</div>
</div>
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.
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.
I have a donation site and a little bit stuck on finding what percent of the Donation Goal that the Current Donations are at?
In my MySQLi database I have two columns - donation_goal (numerical eg. 500) and current_raised (numerical eg. 20.00).
What I need to do is find and display how much in percentage has been raised currently out of the donation goal. So if £10 was donated and the goal was £100 it would display 10%. But it would do this each time the page was loaded.
I display each page with the code below and need to find a way to add this feature to this code below:
<?php
$sql = "SELECT * FROM pages ORDER BY RAND() LIMIT 3";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
$page_name = $row['page_name'];
$count = strlen($page_name);
if($count < 27){
$space = '<br> <br/>';
} else {
$space = '';
}
$page_dp = $row['page_dp'];
$donation_goal = $row['donation_goal'];
$current_raised = $row['current_raised'];
?>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="pageimg/<? echo $page_dp; ?>" style="width:348px;height:233px;" alt="Page Image">
<div class="caption">
<h3><? echo $page_name; ?> <? echo $space; ?></h3>
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%">10%
<span class="sr-only">10% Complete (success)</span>
</div>
</div>
<p><b>£<? echo $donation_goal; ?>.00</b> Target | <b>£<? echo $current_raised; ?></b> Raised</p>
Here is a little info about this current topic, please help us raise more than we can! We need your help!
<p>Donate Now Details</p>
</div>
</div>
</div>
<?
}
?>
I have tried adding this code to the mix, but receiving errors so am pretty sure I have no idea how to add it correctly:
$sql = "SELECT * FROM pages, COUNT( current_raised ) AS test, concat(round(( current_raised/donation_goal * 100 ),2),'%') AS percentage ORDER BY id DESC LIMIT 3";
This just gave out errors. Any ideas of how to do this efficiently with short code?
If you would like to calculate the percentage of the dontation from the goal you could do this directly in your query:
SELECT page_dp,
donation_goal,
current_raised,
ROUND(current_raised/donation_goal*100) percentage
FROM pages
ORDER BY RAND()
LIMIT 3
Then you only need to output the percentage within your loop:
<span class="sr-only"><?php print $row['percentage']; ?>% Complete (success)</span>
Is this what you want?
SELECT p.*, pc.cr / donation_goal
FROM pages p CROSS JOIN
(SELECT SUM(current_raised) as cr FROM pages) pc
ORDER BY RAND()
LIMIT 3;