/    Sign up×
Community /Pin to ProfileBookmark

creating table using mysql

Hi,
I’m stuck with the logic. I have two tables. One is artist second songs. Artist table has 8 artist and song table has 14 songs.
For each artist, you must display their name and the number of songs accredited to them. This part i have done.
but i’m struggle get the logic for summary.
A summary of the songs and artists on the system should also be displayed on each view. The summary should inform the user of the total number of songs and the total number of active artists in the system.

I don’t know how to display the sumary in the table. Basically I don’t know how to construct the query for all the information to get that in one table.
this what I have so far but it only display artist with the song accredited to them plus is multiple table not in one table because of the while loop it return only one table at time.

[code=php]// Construct the query
$sql = “SELECT a.name, COUNT(s.artist_id) FROM artist a JOIN song s
ON (s.artist_id = a.id)
GROUP BY a.name ASC”;

// Execute the query, assigning the result to $result
$result = mysqli_query($link,$sql);

// If the query failed, $result will be “false”, so we test for this, and exit if it is
if ($result === false) {
exit($lang[‘mysqli_error’]);
}

// Gather the author HTML for later
$artists = ”;

// Check if the query returned anything
if (mysqli_num_rows($result) == 0) {
// Pass an error message to the error template which will appear in place of authors
$msg = $lang[’empty_result_error’];
$artists .= $msg;

} else {
// Loop through $result, converting each record from the result set to an array which we assign to $row
while ($row = mysqli_fetch_assoc($result)) {

// We can now access the values in $row using the database column names as array keys

// Echo the escaped string to the page
$pass1 = str_replace(‘[+name+]’, htmlentities($row[‘name’]), $tpl_c);
$pass2 = str_replace(‘[+songs+]’, htmlentities($row[‘COUNT(s.artist_id)’]), $pass1);
$artists .= $pass2;
}
}
// We are finished with the result set, so no point keeping it in memory
mysqli_free_result($result);

// As we are doing no more database querying, we can also close the connection now.
mysqli_close($link);[/code]

Hopefully it does make sence.

thanks.

to post a comment
PHP

14 Comments(s)

Copy linkTweet thisAlerts:
@NogDogFeb 12.2018 — Seems like the simplest approach would be a couple counter variables you could increment in the while loop.
[code=php]
$num_artists = $num_songs = 0;
while(/* ... */) {
$num_artists++;
$num_songs += $row['COUNT(s.artist_id)'];
// rest of the stuff you do in the loop...
}
// output or save the numbers in $num_artists and $num_songs as desired
[/code]

_
Copy linkTweet thisAlerts:
@marcellioauthorFeb 12.2018 — Ok that could work but for this to construct the query I'm gonna need full join to get all two tables otherwise I don't get all artist or all songs in the database right?

/////

/////
Copy linkTweet thisAlerts:
@ginerjmFeb 12.2018 — I don't know what you are trying to do but your first post shows some code that makes absolutely no sense. What are you doing with those "str_replace" calls? They aren't exactly the correct syntax and you are looping thru the results without accomplishing anything permanent that I can see. I don't have a clue what you are doing with $artists - sometimes you put an error message(?) in it, other times you save the $pass2 value in it. Those str_replaces are just bizarre. You seem to be missing the replacement value and from my guess are taking the result of the first call and overwriting it with the results of the second call. AND neither one of those str_replace calls seems to do anything.

From the manual:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Your syntax looks nothing like this.

As for your question in the last post - why don't you make the first query a better one?

<i>
</i>"SELECT a.id, a.name, a.otherfield, a.anotherfield,....,
s.otherfield, s.anotherfield, COUNT(s.artist_id) as songs FROM artist a
left outer JOIN song s ON (s.artist_id = a.id)
GROUP BY a.id ASC";


This should (?) give you more of the data that is in the tables so that you can construct a proper html table to display all that you want to see.
Copy linkTweet thisAlerts:
@marcellioauthorFeb 12.2018 —  first post shows some code that makes absolutely no sense. What are you doing with those "str_replace" calls? [/QUOTE]

Those str_replace() line of codes are exchanging placeholders for the real content for HTML. I have template that is pure HTML codes with placeholders. Those line of codes replace those placeholders and when I call my HTML template it will show me nice page and that way I have clear php page full of codes and function without any html codes. Anyway I'm not allow to use HTML in my php file.

It is advance technique for php and mysql module that I'm taking now.



/////
Copy linkTweet thisAlerts:
@NogDogFeb 12.2018 — Not knowing what you actually do with $artists later, it's difficult to say whether whatever problem you are having is how $artists is being populated by your DB query results, or whether it's an issue with your template code/format/whatever.
Copy linkTweet thisAlerts:
@marcellioauthorFeb 12.2018 — ok guys this is the link to the project website http://titan.dcs.bbk.ac.uk/~mzacha02/w1tma/index.php

if you click on artist you will see the outcome for now. If you remember once I have post the problem with multiple table and then you told me to fetch the function with array and get your table.

This time I have my template so I can't use the previous function but I can rebuild the function for my template. I would see a problem there. Im strugle to get query right. But I think I will create to tables and that will solve the problem and get into database twice. I wanted to access to database only once and put everything in one table put I don't know how to do it so I think will have to create function where will be one table and then on php file eneter to database again and this time create second table only for summary of songs and artist.

This is the rest of the php code so now you can see what I'm doing with those $artist.

Template is just normal table with <tr><th> and <td> tags as you useally will create table.



/*

-----------Build our HTML page------------------

*
/

// Set our variable for the placeholders in our header.html

$page_title = 'Artists page';

$heading = 'Welcome at the Artists page.';

$content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pulvinar ligula vel nisl ultricies venenatis. Integer eu suscipit nibh. Duis interdum nibh auctor ullamcorper vehicula. Fusce tincidunt dapibus fermentum. Nulla aliquam lacinia quam eget posuere. Suspendisse tempor neque et vulputate rutrum. Quisque consequat elementum dui, sit amet pellentesque velit dignissim eget. Pellentesque accumsan lobortis elit sed dapibus. Etiam sed tellus turpis. Pellentesque leo lectus, hendrerit id nibh non, vulputate luctus ex. Nunc dignissim pharetra dui, ac lobortis odio imperdiet sed. Ut id odio a tortor porta consectetur. Morbi scelerisque vehicula felis, nec scelerisque est tincidunt vitae. Aenean dapibus orci erat, a elementum tellus congue quis. In porttitor maximus vestibulum.';

$pass1 = str_replace('[+page_title+]', $page_title, $tpl_a);

$pass2 = str_replace('[+header+]', $heading, $pass1);

$final = str_replace('[+content+]', $content, $pass2);

//diplays our template file with all placeholders

$content = $final . $artists . $tpl_b;

echo $content;[/QUOTE]






///////
Copy linkTweet thisAlerts:
@NogDogFeb 12.2018 — Well, if I were going to do it, I'd just use something like this:
[code=php]
<?php
// bunch of code up to executing the query, then...
?>
<table>
<tr><th>Name of Artist</th><th>Number of Songs</th></tr>
<?php
while ($row = mysqli_fetch_assoc($result)) {
printf(
"<tr><td>%s</td><td>%d</td></tr>n",
htmlentities($row['name']),
$row['num_songs'] // or whatever alias you want to use for that count field
);
}
?>
</table>
<?php
// rest of script...
[/code]

(I suggest using an alias for that count field, e.g. something like:

[FONT=Courier New]SELECT a.name, COUNT(s.artist_id) [COLOR="#FF0000"]as num_songs[/COLOR] FROM . . .[/FONT]

)

_
Copy linkTweet thisAlerts:
@ginerjmFeb 12.2018 — Yeah - good luck with this. Your latest post only confuses me MORE! $tpl_b??? Where did THAT come from?

Never mind - I don't want to know.
Copy linkTweet thisAlerts:
@marcellioauthorFeb 12.2018 — nogDog i would have done probably the same thing but I'm not allow to use HTML in php file. All HTML tags have to be put in the template with placeholder and call the template later and fill up with the content.


Ginerjm haha don't worry it is too much I know and is complex task. btw. $tpl_b is the template of footer. On top I 'm calling my template of header which is $tpl_a and $tpl_b is footer and $tpl_c is body but it doesn't matter those as those are only templates to calling out at the end to create dynamic web page. I will have to do it with two tables and maybe after that with css align as one table hahaha we will see. I already have the second table where is the summary but I was just trying to get all in one table.

Btw. I have create view in sql of those two tables and that way I get the summary of all songs and artist but the problem is all is under one column. Do you guys have any idea why is that? and why is not in two column.

This is the sql summary table
[CODE]create view summary as
SELECT count(a.id) as 'number of artist'
from artist a
LEFT JOIN song s ON a.id = s.id
union
select count(s.id) as 'number of song'
from song s
LEFT JOIN artist a ON s.id = a.id[/CODE]



but like I said above it give me the data all under one column and not two as I'm declaring above in the code. One column should be [COLOR="#FF0000"]'number of artist'[/COLOR] and the second column should be [COLOR="#FF0000"] 'number of song'[/COLOR]




/////
Copy linkTweet thisAlerts:
@ginerjmFeb 12.2018 — Why don't you use the sample query I gave you?
Copy linkTweet thisAlerts:
@marcellioauthorFeb 12.2018 — i will try later this week .. right now i don't have time to play with it as I have to get ready for information system management test on Wednesday.

that query above is just another code what i have said that maybe i will have to do two access into the database to get all information. what i need is if you scroll on top and read the post you will understand what the college want from me to do.

basically, create artist page where the only artist with song accredited to them can be displayed and then also all summary of the artist in the database and summary of songs in the database to display.

if you look at the link i have the artist and the songs just need to add the summary there. it is so complex or is it just for me i don't know. I though someone here can help me with the logic to build that as i have run out of the logic with this.




////
Copy linkTweet thisAlerts:
@ginerjmFeb 13.2018 — If you order the query results correctly you can just do counts of things as you loop thru and display the results, placing the summary where it needs to be.
Copy linkTweet thisAlerts:
@marcellioauthorFeb 17.2018 — Just to let you all know that I figure out how to merge everything into one table as I wanted to.

Here is the link to the final outcome of the website.

http://titan.dcs.bbk.ac.uk/~mzacha02/w1tma/index.php?page=artists

[COLOR="#B22222"]ginerjm[/COLOR] that code for SQL couldn't work because when I tried to count the summary of artists it couldn't give me the sum of artists but it was giving me sum of the songs that artists were accredited to them. The reason is FK in songs table is artists_id. Therefore I had to access to database again and create view only for all artists in the table union with all songs in the table.

At the bottom of the website, you can see the number of how many artists are in the artists table and how many songs in the songs table.

Hopefully that makes sense. Thanks anyway for the help.

Btw. to the table I had to just create template with start of the table and template for end of the table. I fetch all the data only with body of the table template. The outcome is as you can see on the website.


This can be thread can be closed.


///
Copy linkTweet thisAlerts:
@rootFeb 18.2018 — I don't know what you are trying to do but your first post shows some code that makes absolutely no sense.[/QUOTE]
if you read the OP's post [B]For each artist, you must display their name and the number of songs accredited to them. This part i have done.

but i'm struggle get the logic for summary.[/B]
then it becomes apparent this is course work of some sort.
×

Success!

Help @marcellio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...