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']."')"
Related
I am currently working on a system. This is how my tables look like:-
sales table:-
ID | avatar | ident
-------------------------------------
1 | img/photo11 | CCS7771
2 | img/photo32 | INL0987
3 | img/photo32 | INL0987
4 | img/photo6 | URS8827
5 | img/photo32 | INL0987
6 | img/photo9 | NSU8837
7 | img/photo3 | PPP9998
kudos table:-
ID | sale_id | ident_id
-------------------------------------
1 | 1 | INL0987
2 | 4 | INL0987
3 | 7 | INL0987
4 | 1 | KKU8837
5 | 1 | URS8827
6 | 4 | SHD8837
So I have this like system, and when A user press the like button to the table row, it stores the sales.id and sales.ident into another tables named kudos, like you can see above.
I am trying to query to see how many people have given kudos for each post. You can see in the above tables, example: the sales.id 1 has gotten 3 kudos from INL0987, KKU8837 and URS8827. I have tried a few different ways, but I cant seems to find a solution for this. This is what I have tried:
/* $resultSet = $mysqli->query("SELECT kudos.sale_id as makesName, sales.ident AS modelsName from kudos,sales where kudos.sale_id = '42' AND kudos.ident_id = sales.ident"); */
$resultSet = $mysqli->query("SELECT kudos.sale_id as TheID, sales.ident AS TheIdent from kudos,sales where kudos.sale_id = '42' AND sales.id = kudos.sale_id");
echo $resultSet->num_rows;
while ($rows = $resultSet->fetch_assoc()) {
$iid = $rows['TheID'];
$iident = $rows['TheIdent'];
echo "<br><br>TheID: $iid";
echo "<br>TheIdent: $iident";
}
Can someone help me out here? I can figure out what I am doing wrong.
I am trying to query to see how many people have given kudos for each post
I think you just want aggregation:
select sale_id, count(*) no_kudos
from kudos
group by sale_id
If you also want to include sale_ids that have no match in kudos, then you can use a correlated subquery:
select id, (select count(*) from kudos k where k.sale_id = s.id) no_kudos
from sales s
I have a web form.I want to display the web form if the user hasn't submitted it once. If he had submitted it before the form will not appear. I have a table in sql like this below:
| userID | topicId | Date |
| 2 | 1 | 2018 |
| 2 | 5 | 2018 |
| 2 | 4 | 2018 |
| 2 | 8 | 2018 |
| 2 | 9 | 2018 |
My form is in PHP and I am struggling to write the script which can give me the count of topicId submitted by the userID. So :
if the count is less then 1 show him the topic web form;
if the count is bigger than 1 : don't show him the same topic web form.
So far I have this:
$query = $dbh->prepare("SELECT count(userID) from topicCountTable GROUP BY topicId");
$query->execute();
$row1 = $query->fetchAll();
if (count($row1) >1){
echo "Sorry you already submitted this topic";
}
else{
<form>
......
</form>
}
But for some reason, my script is not working
Did you check the query in SQL?
If you're using GROUP BY topic_id and you're looking for a specific topic_id value count, then the topic_id should be in the SELECT part:
SELECT topicId, count(userID) from topicCountTable GROUP BY topicId
You probably also want to specify the user_id you're looking for in the query in a WHERE, eg.
SELECT topicId, count(userID) from topicCountTable WHERE userID = 2 GROUP BY topicId
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.
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 one field in the backend, where I input IDs separated by comma - ID1, ID2, ID3....These are videos in fact. All ids are stored in the field product_videos in the database (as they are typed).
How can I echo these id's on the frontend so they all show for the product?
Storing comma separated data in one data field is a bad idea. It is a real pain to manipulate, so you should really consider revising your db structure.
You haven't shown your data structure, so I'll give a basic example and then explain how it can be improved. My example assumes product_videos is linked to particular users:
table: `users`
| user_id | user_name | product_videos |
|---------|-----------|----------------|
| 1 | User1 | 1,2,3,4,6,7 |
| 2 | User2 | 5 |
You would maybe run a query
SELECT `product_videos` FROM `users` WHERE `user_name` = 'User1'
This would give you one row, with a comma separate value - you would then need to use something like PHP's explode() to convert it into an array and then loop through that array. That is a very bad method (and it will only become harder as you try to do more advanced things).
Instead, it would be easier to use a link table. Imagine:
table: `users`
| user_id | user_name |
|---------|-----------|
| 1 | User1 |
| 2 | User2 |
table: `videos`
| video_id | user_id |
|-----------|---------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 1 |
| 7 | 1 |
In this example, each video is a separate row in a db table (and each video is linked to an existing user). Each row is readily able to be handled independently. This makes it really easy to handle extra data for each video, such as a title, runtime length, date of uploading, etc.
You would then need to run a JOIN query. e.g.
SELECT `videos`.`video_id` FROM `videos`
INNER JOIN `users` ON `users`.`user_id` = `videos`.`user_id`
WHERE `users`.`user_name` = 'User1'
In PHP, you would do something like:
$q = mysql_query("SELECT `videos`.`video_id` FROM `videos` INNER JOIN `users` ON `users`.`user_id` = `videos`.`user_id` WHERE `users`.`user_name` = 'User1'");
while ($row = mysql_fetch_assoc($q)) {
echo "VIDEO ID = " . $row["video_id"] . "<br/>";
}