MySQL/PHP Count - php

I have 2 MySQL tables, one for storing albums and the other for songs. I am displaying a list of albums in a table, and I want to be able to add a column called songs to display the number of songs in this album. The way I have it now just messes up my table:
Thanks for everyone's help!

Assuming that "playlist" is what you consider an album and the first while loop iterates on playlists, I'd rewrite your code like this:
while($row = mysql_fetch_array($rs)) {
echo "<tr>\n";
echo "<td>".$row['playlist_id']."</td>";
// Assuming playlist_id is an integer value in your database
$query = "
SELECT Playlist_id, COUNT(Playlist_id) AS songCount
FROM ws_music
WHERE Playlist_id = ". intval ($row['playlist_id']) ."
GROUP BY Playlist_id
";
$result = mysql_query($query) or die(mysql_error());
// No need for the second while loop
$row2 = mysql_fetch_array($result);
echo "<td>There are ". $row2['songCount'] ." ". $row2['Playlist_id'] ." song.</td>";
echo "</tr>";
}

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

Php Echo Multiple Rows In A Random Order

I have 2 MySql Tables. Videos and Photos. When a user uploads a file it gets stored in one of the tables depending on the file.
heres the code:
index.php:
getVideos($conn);
getPhotos($conn);
get.inc.php:
function getVideos($conn) {
$sql = "SELECT * FROM videos ORDER BY date desc";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<div class='video-box'><p>";
echo $row['title']."<br>";
echo "by:";
echo $row['uid']."<br>";
echo $row ['videofile'];
echo "</p>";
}
}
function getPhotos($conn) {
$sql = "SELECT * FROM photos ORDER BY date desc";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<div class='photo-box'><p>";
echo $row['title']."<br>";
echo "by:";
echo $row['uid']."<br>";
echo $row ['photofile'];
echo "</p>";
}
}
there are 3 videos and 2 photos in my database curently *
When I have the code as I do Now all 3 of the videos from my database appear first on the the home page then when you slide down the 2 photos appear at the bottom.
How do I make it So the photos and videos are mix and are dispalyed by the date they were uploaded (newest at the top older at the bottom.) Without them being separated like they are now. Please Help.
- Thanks in advance
You can use UNION
SELECT * FROM
(SELECT id, date, videofile as file FROM videos
UNION
SELECT id, date, photofile as file FROM photos) t
ORDER BY t.date;
Here you can play with example: http://sqlfiddle.com/#!9/92c8fc/1/0
Altough it is possible it will probably be better to store this information just in one table. If you need to preserve information about what is video file and what is photo you can just add another column where you store this kind of meta data.

How can i simplify this php mysql count code and reduce queries?

I have database with 8 different product category for download.
pic, app, ebo, tem, des, cod, mus, cat
I'd like to count clients total downloaded products and total downloads of each product category.
Maximum daily limit downloads for category product is 3.
When user log in should see how many downloads remain.
Here is working code
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." products.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'pic'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ." downloaded pictures";
$leftovers = 3 - $row['sum'];
echo " $leftovers pictures remain for download";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'app'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ."downloaded applications";
$leftovers = 3 - $row['sum'];
echo " $leftovers applications remain for download.";
echo "<br />";
}
$query = "SELECT CO.... This procedure repeat eight times for different product category.
result
You have downloaded 12 products.
3 downloaded pictures 0 pictures remain for download.
1 downloaded applications 2 applications remain for download.
3 downl.......
You could use a GROUP BY statement to group your results.
SELECT COUNT(`Product`) AS `Sum`, `Product`
FROM `service_downloads`
WHERE `client_id` = '<client_id>'
GROUP BY `Product`
Then you can use one while statement to loop through each product:
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['Sum'] ."downloaded " . $row['Product'];
$leftovers = 3 - $row['Sum'];
echo " $leftovers " . $row['Product'] . " remain for download.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum,product FROM service_downloads where client_id like '$client' GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." ".$row['product'];
echo "<br />";
}
This should work
You should breakdown the quantity of downloads per category in one query:
SELECT product,COUNT(*)
FROM service_downloads
WHERE client_id like '$client';
I also don't think you need to use LIKE; you probably want to use =
You can get a single result set with all the sums in it with this query.
SELECT COUNT(*) as sum, product
FROM service_downloads
WHERE client_id = '$client'
AND PRODUCT IN ('pic', 'app', 'abc', 'def', 'ghi')
GROUP BY product WITH ROLLUP
ORDER BY product NULLS FIRST
This will give you one row for each specific product and a summary (rollup) row with a NULL value in the product column.
If this query takes a long time create an index on (client, product) and it should go pretty fast.
If you are showing this data frequently, which is what it sounds like, then you should have a separate table that represents those SUMs and is index by CLIENT_ID.
You can then increment/decrement that value each time you add a new entry.
For example, when you add a new row to service_downloads with an entry in 'pic' for CLIENT_ID 1, then you would also increment this shortcut table:
UPDATE service_counts SET pic=pic+1 WHERE client_id=1;

Returning results from every "user" grouped for pagnation of dompdf

I have two tables in mysql.
people is an identification table of users.. names/etc
trans is a transaction table, what the users have done (add/subtract balances)
I am wanting to return every "ident" from people, then search trans for that ident's matching rows, and then after all are returned, echo the page break, so each person gets their own page print out. (there shouldn't be so many transactions that a page is not enough..) Also to subquery the balance remaining (trans has both credits and debits, could be positive or negative).
Structure:
people.id #(not queried, unique/auto-increment)
people.name
people.location
people.ident #(assigned number that is same as trans.ident)
trans.id #(not queried, unique/auto-inc)
trans.date
trans.ident
trans.amount
trans.description
Queries:
$query = "SELECT people.ident, people.name, people.location, trans.ident, trans.date, trans.amount, trans.description FROM people LEFT JOIN trans ON people.ident = trans.ident";
$balance = mysql_result(mysql_query("SELECT SUM(amount) FROM trans WHERE ident = $ident", $dblink), 0);
$result = mysql_query($query) or die(mysql_error());
Echo results:
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['ident']. " - ". $row['amount']. " - " .row['description'];
echo('<div style="page-break-before: always;"></div>');
}
This will print out each transaction, and they are sorted by the ident, but with div after each...
I would like to print out the name and location, also their remaining balance ( once on a div.. and then trans under like so:
<div class="user">['name'] ['location'] $balance</div> #These aren't rows, just a single return
<div class="trans">$row['amount']. " - ". $row['description'];</div>
<div style="page-break-before: always;"></div>
Thanks for any assistance!
Well, that is going to be a little bit difficult because you can not always be sure that the name/location for a person inside the people table is actually for the same person/location. Your database is not completely normalised.
That being said, you can do what you want with a few small changes to your query and some PHP code :)
$query = "SELECT people.ident, people.name, people.location,
trans.ident, trans.date, trans.amount, trans.description
FROM people LEFT JOIN trans ON people.ident = trans.ident
ORDER BY peeople.name, people.location, trans.ident";
Echo results:
$lastName = null;
$lastLocation = null;
while($row = mysql_fetch_array($result)){
if (($lastName !== $row['name']) or ($lastLocation != $row['location'])) {
echo $row['name']. " - ". $row['ident']. " - ". $row['amount']. " - " .row['description'];
$lastName= $row['name'];
$lastLocation = $row['location'];
}
/* ... output the transaction line ... */
echo('<div style="page-break-before: always;"></div>');
}

php print 10 results of an array

i have a question for you guys.
im trying to print an array where it would display 10 values of the table acording to user.
this is what i have so far and it displays only the first row,
session_start();
// Retrieve all the data from the table
$result = mysql_query("SELECT name,location,login_id FROM table WHERE login_id = $user[login_id]")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo " name ".$row['name'];
echo " located ".$row['location'];
.....
how can i display the first 10 rows?
help would be apreciated.
thank you for reading.
also add "limit 10" to the query.
SELECT name,location,login_id FROM table WHERE login_id = $user[login_id] LIMIT 10
session_start();
// Retrieve all the data from the table
$result = mysql_query("SELECT name,location,login_id FROM table WHERE login_id = $user[login_id] LIMIT 10")
or die(mysql_error());
while($row = mysql_fetch_array( $result )){
echo " name ".$row['name'];
echo " located ".$row['location'];
}
And This will work only if your login_id is not unique and multiple rows can have the same login_id
You have to call mysql_fetch_array repeatedly to get all the row from the result set:
while(($row = mysql_fetch_array( $result ))) {
echo " name ".$row['name'];
echo " located ".$row['location'];
}
See further examples in the documentation.
If you really want to get only the first 10 rows, have a look at #Yasser Souri's answer (you still have to loop though).

Categories