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:
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.
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:
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:
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:
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.
Related
I need help to make the best query posible here. I have the following Database:
+----+--------------+-----------------+------------------------------+
| id | reference_id | reference_field | value |
+----+--------------+-----------------+------------------------------+
| 1 | 6215 | title | Best recipe |
| 2 | 6215 | introText | Intro for best recipe |
| 3 | 6215 | fullText | Full text for best recipe |
| 4 | 6216 | title | Play Football |
| 5 | 6216 | introText | Intro for play football |
| 6 | 6216 | fullText | Full text for play football |
+----+--------------+-----------------+------------------------------+
I need to make a query where I group by reference_id and I should print the value by the reference_field, example of the output info:
Best recipe
Intro for best recipe
Full text for best recipe
Play Football
Intro for play football
Full text for play football
UPDATE
To accomplish this, I will print the query on the following way with PHP:
$result = $config->mysqli->query("SELECT * FROM table_name ORBER BY reference_id");
while($row = $result->fetch_array()) {
echo ('<h1>'.$row["title"].'</h1>');
echo ('<h1>'.$row["introText"].'</h1>');
echo ('<h1>'.$row["fullText"].'</h1>');
}
With the query above, I get all the records one by one (not grouped by the reference_id), in other hand if I do the query
SELECT * FROM table_name GROUP BY reference_id
How do I get the 3 values (title, introText, fullText) to print on the loop interaction in PHP?
As you can see with a normal "order by" or "group by" does not produce the proper result to print the values on the loop. What I see here is that on the result I should print the values of 3 records by each loop interaction in PHP instead print 3 fields of each records, does it make sense?
I think this is what you need:
SELECT value from TABLE_NAME
ORDER BY reference_id
You may want this:
select *
from your_table
order by reference_id, reference_field desc;
Create connection, do query and show the results:
<?php
$dbo = //Create db connection
$statement = $dbo->prepare("SELECT * FROM table_name ORBER BY reference_id");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r ($result);
echo "</pre>";
?>
I have these two tables which I'm trying to make an output of.
The first one **USERS** stores all information about a user, including an unique ID (androidID).
The second one gets input based on number of laps a user has taken, and will make one row pr lap.
What I'm trying to do is to output the last entry of a given androidID in **ROUNDS**, whith the corresponding name etc. from **USERS**
_____________________ _________________________
| **USERS** | | **ROUNDS** |
--------------------- -------------------------
| NAME | | ID(unique) |
| LASTNAME | | TIME |
| androidID(unique) | <----> | androidID(NOT unique) |
| ... | | ROUNDS |
This is how I'm quering the server
$result_users = $con->query(
"SELECT * FROM users"
);
$result_rounds = $con->query(
"SELECT * FROM Rounds ORDER BY laps desc"
);
I tried to numerous combination of the following. With no luck. My PHP skills is not the best, I'm afraid.
foreach ($result_users as $row_users) {
foreach ($result_rounds as $row_rounds) {
if($row_users['androidID'] == $row_rounds['androidID'] {
// Do some wizzardy
}
}
}
I have really hit a wall trying to connect the tables.
This would be the sql statement you want in your query.
SELECT * FROM `**USERS**` LEFT JOIN `**ROUNDS**`ON `**USERS**`.`androidID` = `**rounds**`.`androidID` ORDER BY `laps` desc 0,1;
I have a table consists of several fields (id, firstname, surname, username, search_count)
I've build a small search engine that search my table to find any match exists either in the firstname or in the surname and I am getting the results with no problems.
Now, what I am trying to do is to increment the search_count field by 1 every time there is a match!
For example let's say we have the following table users:
id | firstname | surname | username | search_count
1 | John | Mike | un1 | 0
2 | John | Jeff | un2 | 0
3 | Dale | John | un3 | 0
4 | Mike | Gorge | un4 | 0
and let's say we are searching for Jeff as a keyword
so, the query will return 1 record
what I want to do is to increment the search_count by 1 for match record
so the results will be something like as:
id | firstname | surname | username | search_count
2 | John | Jeff | un2 | `1`
and if we make a new search (e.g. John) the results should be something like:
id | firstname | surname | username | search_count
1 | John | Mike | un1 | 1
2 | John | Jeff | un2 | 2
3 | Dale | John | un3 | 1
I've tried several approach but with no luck.. So I appreciate any hints and help
here is my code...
<?php
// open the HTML page
include 'html_open.php';
// require the db connection
require '/inc/db.inc.php';
// require the error messages
require '/inc/echo.inc.php';
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
if (!empty($keyword)) {
// build our search query
$search_query = "SELECT * FROM `users` WHERE `firstname` = '".mysql_real_escape_string($keyword)."' OR `surname` = '".mysql_real_escape_string($keyword)."' ORDER BY `search_count` DESC";
// run the search query
$search_query_run = mysql_query($search_query);
// search results
$search_results_num = mysql_num_rows($search_query_run);
// check query return results
if ($search_results_num>0) {
echo 'Search engine returns <strong>[ '.$search_results_num.' ]</strong> result(s) for <strong>[ '.$keyword.' ]</strong>:<br>';
// retrieving the information found
echo '<ol>';
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
//$current_search_count = ;
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
}
echo '</ol><hr>';
include 'search_form.php';
} else {
echo '<hr>Search engine returns no result for <strong>[ '.$keyword.' ]</strong>, please try another keyword.<hr>'; // hint: no result found
include 'search_form.php';
}
} else {
echo $err20_002; // hint: must insert input
include 'search_form.php';
}
} else {
echo $err20_001; // hint: form has not been submitted
include 'search_form.php';
}
// close the HTML page
include 'html_close.php';
?>
P.S. I am new to PHP / MySQL and this is my first code :)
...
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
# add this following line
mysql_query('UPDATE `users` SET search_count=search_count+1 WHERE id='.$search_result_information['id']);
# Edit. Change result to show new number
$search_result_information['search_count']++; # this adds 1 to the value (does not affect stored data in database)
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
}
...
In your case you need to fetch the found values and perform an update statement adding +1 to the search_count column
$search_query = "SELECT id, firstname, surname, username, search_count FROM `users` WHERE `firstname` = '".mysql_real_escape_string($keyword)."' OR `surname` = '".mysql_real_escape_string($keyword)."' ORDER BY `search_count` DESC";
$search_query_run = mysql_query($search_query);
// search results
$search_results_num = mysql_num_rows($search_query_run);
// check query return results
if ($search_results_num>0) {
echo 'Search engine returns <strong>[ '.$search_results_num.' ]</strong> result(s) for <strong>[ '.$keyword.' ]</strong>:<br>';
// retrieving the information found
echo '<ol>';
while ($search_result_information = mysql_fetch_assoc($search_query_run)) {
//$current_search_count = ;
$update_search = "UPDATE users SET search_count = search_count + 1 WHERE id = {$search_result_information['id']}"; // so every `id` will increment its search_count with 1. You will need to select the rows once again, to take this count, or to manually increment in PHP
mysql_query($update_search);
echo '<li>'.$search_result_information['username'].'. This user has been searched: '.$search_result_information['search_count'].' times before.</li>';
P.S.: Using mysql_* lib is strongly NOT recommended. As you can see from the red box in the official documentation http://www.php.net/manual/en/function.mysql-query.php you should choose one of the current actually supported APIs
I have two tables. The first table holds simple user data and has the columns
$username, $text, $image
(this is called "USERDATA").
The second table holds information about which users "follow" other users, which is set up with the columns
$username and $usertheyfollow
(this is called "FOLLOWS").
What I need to do is display the data individually to each user so that it is relevant to them. This means that userABC for instance, needs to be able to view the $text and $image inputs for all of the users whom he/she follows. To do this, I believe I need to write a sql query that involves first checking who the logged in user is (in this case userABC), then selecting all instances of $usertheyfollow on table FOLLOWS that has the corresponding value of "userABC." I then need to go back to my USERDATA table and select $text and $image that has a corresponding value of $usertheyfollow. Then I can just display this using echo command or the like...
How would I write this SQL query? And am I even going about the database architecture the right way?
With tables like so:
userdata table
______________________________
| id | username | text | image |
|------------------------------|
| 1 | jam | text | image |
+------------------------------+
| 2 | sarah | text | image |
+------------------------------+
| 3 | tom | text | image |
+------------------------------+
follows table
_____________________
| userId | userFollow |
|---------------------|
| 1 | 2 |
+---------------------+
| 1 | 3 |
+---------------------+
and use the following SQL:
SELECT userdata.text, userdata.image FROM follows LEFT JOIN userdata ON follows.userFollow = userdata.id WHERE follows.userId = 1
will get all the text and images that user with id '1' follows
As it turns out, neither of these answers were right. #jam6459 was closest.
The correct answer is the following:
SELECT userdata.text, userdata.image, follows.userFollow
FROM userdata
LEFT JOIN follows ON follows.userFollow = userdata.username
WHERE follows.userId = $username
I also found it easier to not have a username correspond to an Id as in jam's table example. This is because the same user can have multiple entries in "USERDATA". I instead used username as the Id.
function get_text_image($username)
{
$sql = "SELECT * FROM USERDATA where username='".$username."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
echo $row['image'];
}
}
function display_data_of_followers($userid)
{
$sql = "SELECT usertheyfollow FROM follow WHERE userid = ".$userid."";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
get_text_image($row['usertheyfollow']);
}
}
display_data_of_followers($userid);
I am developing an android Application that stimulates a poll notification feature. Therefore, I Created a service that keeps asking the server for the new data. However, I've used a table in my database called Seen. This table is used to be asked by the server for a specific user_id and if the news_id didn't exists in that table it will produce a notification.
The problem is when i launch the application for the first time. It retrieves all the data from the database because the server considering the users didn't see the news.
If Anyone Can Help me?
I Thought to solve it by this Idea: when I launch the application for the first time. Insert in seen table all of the news with that user_id in order to get 0 new messages. But i think it will be Not efficient.
This is my Database and my PHP script
Users table
User_ID | User_Name
--------------------
1 | John
2 | Carl
3 | Tomas
4 | Adam
5 | Nancy
News Table
News_ID | News_Text | news_date
---------------------------
1 | Hello World | CURRENTDATE()
2 | This is My car | CURRENTDATE()
3 | I had Ate pizza| CURRENTDATE()
4 | Leave Me Alone | CURRENTDATE()
5 | C++ Programming| CURRENTDATE()
Seen Table
ID | User_Id | News_Id
---------------------------
1 | 1 | 2
2 | 1 | 3
3 | 4 | 1
4 | 5 | 3
5 | 1 | 4
This is my PHP Code and it also showing my Query to get the news that didn't show in the Seen_news Table :
<?php
require('config.php');
$conn = mysqli_connect($servername, $username, $password, $db);
$query="SELECT * FROM news WHERE news_id NOT IN (SELECT news_id FROM news_seen WHERE user_id = '".$_GET['id']."')";
$result = mysqli_query($conn,$query);
$rows = array();
echo mysqli_error($conn);
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode($rows);
?>
Supposing that i am sending the User_Id to the PHP script and based on the result Query will show json file.
If you can add a create_date column to your Users table, you can select where Seen news_date is greater than User create_date.
Something like:
"SELECT * FROM news WHERE news_id NOT IN (SELECT news_id FROM news_seen WHERE user_id = '".$_GET['id']."') AND news_date > (SELECT create_date FROM user WHERE user_id = '".$_GET['id']."')"