0

I have a dance contest site and each user can login and add dance moments, in my html table with all moments from all users i have all the data but i want in a html column to add "number of dancers for each moment added by the logged user id".

I have this:

$c = mysql_query("SELECT * FROM moments");
$dancers = 0;
while($rows = mysql_fetch_array($c)){
    for($i = 1; $i <= 24; $i++){
        $dan_id = 'dancer'.$i;
        if($rows[$dan_id] != "" || $rows[$dan_id] != null )
            $dancers++;
    }   
}
echo "<th class="tg-amwm">NR of dancers</th>";
echo "<td class='tg-yw4l'>$dancers</td>";

phpMyAdmin moments table: has id, clubname, category, discipline, section, and this: enter image description here

But this process is count all the dancers names from all users moments. Example for this process: You have a total of 200 dancers !

I want the process to count for me all dancers names for each moment added in the form not a total of all entire users moments, something like this: if user john has two moments added: Moment 1: 5 dancers - moment 2: 10 dancers, and so on for each user.

Francisco
  • 10,918
  • 6
  • 34
  • 45
Fido
  • 17
  • 7
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 06 '16 at 16:48
  • i'm new learner, thanks for advice Jay – Fido May 06 '16 at 16:50
  • 1
    Consider normalizing your database... comma-separated lists of values in a column is bad design, and why do you need to store a count as well as a list of names? Can't you count up the names in a list? – Mark Baker May 06 '16 at 16:50
  • Please adapt your comments to the user's apparent level of expertise. @Fido is obviously very new to PHP and mySql. – Webomatik May 06 '16 at 17:16
  • You have a FOR() loop inside your WHILE() loop. What is the FOR() loop for? – Webomatik May 06 '16 at 17:23
  • Can you make-it right? – Fido May 06 '16 at 17:26
  • You can use this query `SELECT dan_id, COUNT(*) AS moment FROM moments GROUP BY dancer_id` and you'll have the result of number of rows for each `dancer_id` (each one represent a "moment", I guess..) – Alon Eitan May 06 '16 at 17:35
  • is not working, it gives me ''0'' – Fido May 06 '16 at 17:43
  • It's unclear because your question doesn't describe the structure of the table. Try running this query directly (Using phpMyadmin, mysql workbench or any other...) `SELECT dan_id, COUNT(*) AS moments_count, * FROM moments GROUP BY dancer_id` it should give you the results of the number of rows per the `dan_id` field – Alon Eitan May 06 '16 at 17:51
  • In phpmyadmin moments table i have this: id , dancer1,dancer2, dancer3,...dancer24 – Fido May 06 '16 at 17:56

1 Answers1

2

Let me try to put you in the right way (it seems a long post but I think it's worth the beginners to read it!).

You have been told in the comments to normalize your database, and if I were you and if you want your project to work well for a long time... I'd do it.

There are many MySQL normalization tutorials, and you can google it your self if you are interested... I'm just going to help you with your particular example and I'm sure you will understand it.

Basically, you have to create different tables to store "different concepts", and then join it when you query the database.

In this case, I would create these tables:

database diagram

categories, dance_clubs, users and dancers store "basic" data.

moments and moment_dancers store foreign keys to create relations between the data.

Let's see the content to understand it better.

mysql> select * from categories;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Hip-hop/dance |
+----+---------------+

mysql> select * from dance_clubs;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | dance academy |
+----+---------------+

mysql> select * from users;
+----+-------+
| id | name  |
+----+-------+
|  1 | alex  |
+----+-------+

mysql> select * from dancers;
+----+-------+
| id | name  |
+----+-------+
|  1 | alex  |
|  2 | dan   |
|  3 | mihai |
+----+-------+

mysql> select * from moments;
+----+--------------+---------------+-------------------+
| id | main_user_id | dance_club_id | dance_category_id |
+----+--------------+---------------+-------------------+
|  1 |            1 |             1 |                 1 |
+----+--------------+---------------+-------------------+
          (user alex)  (dance acad..)     (Hip-hop/dance)

mysql> select * from moment_dancers;
+----+-----------+-----------+
| id | moment_id | dancer_id |
+----+-----------+-----------+
|  1 |         1 |         1 | (moment 1, dancer alex)
|  2 |         1 |         2 | (moment 1, dancer dan)
|  3 |         1 |         3 | (moment 1, dancer mihai)
+----+-----------+-----------+

Ok! Now we want to make some queries from PHP.

We will use prepared statements instead of mysql_* queries as they said in the comments aswell.

The concept of prepared statement can be a bit hard to understand at first. Just read closely the code and look for some tutorials again ;)

Easy example to list the dancers (just to understand it):

// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];

$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Here we explain MySQL which will be the query
$stmt = $conn->prepare("select * from dancers");
// Here we explain PHP which variables will store the values of the two columns (row by row)
$stmt->bind_result($dancerId, $dancerName);

// Here we execute the query and store the result
$stmt->execute();
$stmt->store_result();

// Here we store the results of each row in our two PHP variables 
while($stmt->fetch()){
    // Now we can do whatever we want (store in array, echo, etc)
    echo "<p>$dancerId - $dancerName</p>";
}

$stmt->close();
$conn->close();

Result in the browser:

dancers list

Good! Now something a bit harder! List the moments:

// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];
$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to read the "moments", but we have their main user and dancers in other tables
$stmtMoments = $conn->prepare("
    select
        moments.id,
        (select name from users where users.id = moments.main_user_id) as main_user,
        (select name from dance_clubs where dance_clubs.id = moments.dance_club_id) as dance_club,
        (select name from categories where categories.id = moments.dance_category_id) as dance_category,
        (select count(*) from moment_dancers where moment_dancers.moment_id = moments.id) as number_of_dancers
    from moments
    ");
// Five columns, five variables... you know ;)
$stmtMoments->bind_result($momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers);

// Query to read the dancers of the "moment" with id $momentId
$stmtDancers = $conn->prepare("
    select
        dancers.name as dancer_name
    from
        dancers join moment_dancers on dancers.id = moment_dancers.dancer_id
    where
        moment_dancers.moment_id = ?
    ");

$stmtDancers->bind_param("i", $momentId);
$stmtDancers->bind_result($momentDancerName);

// Executing the "moments" query
$stmtMoments->execute();
$stmtMoments->store_result();

// We will enter once to the while because we have only one "moment" right now
while($stmtMoments->fetch()){

    // Do whatever you want with $momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers
    // For example:

    echo "<h3>Moment $momentId</h3>";
    echo "<p>Main user: $momentMainUser</p>";
    echo "<p>Dance club: $momentDanceClub</p>";
    echo "<p>Category: $momentDanceCategory</p>";
    echo "<p>Number of dancers: $momentNumberOfDancers</p>";
    echo "<p><strong>Dancers</strong>: ";

    // Now, for this moment, we look for its dancers
    $stmtDancers->execute();
    $stmtDancers->store_result();
    while($stmtDancers->fetch()){

        // Do whatever you want with each $momentDancerName
        // For example, echo it:

        echo $momentDancerName . " ";
    }

    echo "</p>";
    echo "<hr>";
}

$stmtUsers->close();
$stmtMoments->close();

$conn->close();

Result in browser:

moments list

And that's all! Please ask me if you have any question!

(I could post the DDL code to create the database of the example with the content data if you want)

Edited: added dancers table. Renamed moment_users to moment_dancers. Changed functionality to adapt the script to new tables and names.

nanocv
  • 2,227
  • 2
  • 14
  • 27
  • Thank you nanocv for your hard work, apreciate your reply! One question, in my table alex dan & mihai they are not users, are dancers added by a logged user, when a user sign-up a moment they write some dancers names in a form, from 1 to 24 dancers, and i dont know how to count those dancers names, in myphpmyadmin table each dancer has one column : dancer1 | dancer2 | dancer3 and so on.. – Fido May 07 '16 at 04:23
  • @Fido It's not hard work for me, I like doing this! And yesterday I had some free time as you can see ;) Sorry if I insist with this way to make this application, but I promise you this is the good way! That's not a good practice at all to have a fixed number of columns to store a variable number of dancers in each moment (you will have a LOT of null cells in your database). I have edited my answer and created a 'dancers' table to store them in the right way (you can see it easily in the diagram). – nanocv May 07 '16 at 07:41
  • 1
    @nanocv -good on you for making a real effort to explain the principles and benefits of normalisation – Mark Baker May 07 '16 at 10:13