PHP explode data to be used in WHERE clause - php

I am working on a project where I need to maintain user specific content.
One user can view one content only one time in 24 hours.
After 24 hours it will be made available to the same user again.
So when a user successfully views a content I store the username of the user in the database in a comma separated value.
For example: when the user user1 successfully views a content his username will stored in user_statusas user1 along with other users likes user1,user2,user3,.......,etc.
Now what I want is to check the content if the username user1 exists in the database or not.
If it exists then content will not be made available to him for next 24 hours.
But for some reasons I cannot check a particular user from the group of comma separated usernames using if...else.
I can do it with if...else and explode but that does not satisfies my need. I want to know that can I check for one username in the WHERE clause of SELECT statement?
For ex. something like SELECT * FROM user_data WHERE user_status != '".$something."'.
Is it possible by using explode first then checking it in WHERE clause or just by some other method? If yes, then how? Please help me php experts.
Is it possible something like this?
$uname = $_SESSION['username'];//username of the logged in user
$ths = "SELECT * FROM user_data";
$its = mysql_query($ths) or die(mysql_error());
$uhs = mysql_fetch_array($its);
$user_status = explode(',', $uhs['user_status']);// first explode the comma separated usernames
$ths = "SELECT * FROM user_data WHERE user_status != '".$uname."'";// then check if the logged in username does not exists in the database
$its = mysql_query($ths) or die(mysql_error());
Can the exploded list of usernames be checked in the WHERE clause? Is it possible? Or is there any method to do this? If yes then how?

I think you are looking at it all wrong. That is a lot of maintenance for a very simple task.
You could just have another table, where you keep user id & data id pairs along side with a timestamp.
For example, for user data 1 and user 1 you will save:
uid | did | ts
--------------------
1 | 1 | TIMESTAMP
To check if a user watched an item, just select from that table using the user id and data id.
If no row is found, or the the current timestamp minus the row timestamp is more than 24 hours, allow the user to view the data, otherwise - don't allow it.

You may use LIKE to search some string for existence of another string:
SELECT * FROM `user_data` WHERE `user_status` LIKE '%user1%';
See: https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html

Related

PHP - get rows from a database where a word is not in a specific text

I have a database where I'm getting a random row from a table depending on a few variables. I'm trying to make it so it adds their username in this format (Admin, Jerry, Ben) once they view the advertisement (My project - clients view ads for Bitcoin). I want to make it so that once they view it , it adds their name in to a row called users_viewed_add (example is above). I need it to only get random rows based on if their username does not exist in the row users_viewed_add atoll so they can't view the ad more than once.
At the moment, I'm trying to do:
$query_second = mysqli_query($con, "SELECT * FROM business_advertisments WHERE ($users_credits >= amount_per_click) AND (users_viewed_add) NOT LIKE '$username' AND users_name != '$username' ORDER BY RAND() LIMIT 1");
As you can see, the AND (users_viewed_add) NOT LIKE '$username' is not working for me as it's reading the text as a whole word. The problem is that I'm using comma's to seperate the usernames of the clients who have viewed the ad. Is there any work around for this ? I know the method to check a block of text but it wouldn't work in a SQL statement I'm pretty sure.
You can do:
AND CONCAT(',', users_viewed_add, ',') NOT LIKE '%,$username,%'
But you probably want to make a separated many to many table, and use user id instead of user name.
If you want to use multiple values in your LIKE comparison, you can use:
AND users_viewed_add NOT LIKE ALL ('$username')
This will check that none of the $username values exists in the users_viewed_add field. You may need to format your variable properly so the SQL works.
I found the answer from this post: How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3 in python code?
The correct SQL syntax to check a word doesn't exist in a row is:
AND users_viewed_add NOT REGEXP '[$username]'

PHP MySQL query - select all users but only display the earliest logon times for each user

I want to be able to bring back the earliest logon time per user, so only 1 record (the earliest record) displays for each user
I've tried various ways of GROUP BY but can't seem to get it quite right (if that is actually the correct way of doing). username is the unique value which can be used to GROUP BY
Here's the code I'm currently working with..
SELECT username, name, logon, added FROM data WHERE (date(added) LIKE '$date') AND (logon = (SELECT MIN(logon) FROM data))
I've also tried (below) but only get one result back, only displaying one user
WHERE (date(added) LIKE '$date') AND logon = (SELECT MIN(logon) FROM data)
The first image is what I'm currently getting, the second image is how I want my results to display, please see below
Let me know if you require anymore information, I've tried to put as much as possible
Thanks,
Tom
You are close. Your query needs a correlation clause:
SELECT d.*
FROM data d
WHERE date(d.added) = '$date' AND
d.logon = (SELECT MIN(d2.logon) FROM data d2 WHERE d2.name = d.name);
Note: The logic for added is confusing. First, you should not use like with dates. And, for that matter, you should not be inserting parameter values into the string, you should be using query parameters. And, actually, I don't see the need for that column; your question doesn't mention added.
use this query , problem will be solved
SELECT username, min(logontime) FROM data where date(logontime) = '2016-08-10' group by username
do this:
<?php
$users = array();
$sql = "select * from users";
$result= mysqli_query($conn,$sql);//$conn is your connection object
while($user = mysqli_fetch_assoc($result)){
if(!in_array($user['name'],$users)){
$users[$user['name']]=$user['logOnTime'];//replace key names with your table row names
}
}
//$users is an array that has your user names as key and their last logon time as value
?>

Retrieve Values for User from Database

I'm currently trying to retrieve values from a database.
New Users are given a UNIQUE ID once they register on my website:
Keys are stored into my database with a link such as:
website.com/file.php?id=4&key=123abcd123
What I was planning on having was the website pulling the keys ONLY related to the ID of the user.
Lets say User 4 inputs a key into the database, I want to have a universal .php file that will retrieve HIS codes (codes with the ID of 4) ONLY.
I'm sorry if this doesn't really make sense, English isn't my first language.
For finding particular record in mysql query pass the id value in the place of 4 below.
SELECT * FROM tablename WHERE UserID = '4'
if you want to get particular value then use like this
$query = "SELECT * FROM tablename WHERE UserID = '".$_SESSION['ID']."'";
Refference
If you use SQL, it is easy to search for all keys for a user:
select cdkey
from YourTable
where UserID = 1
Note that anyone can edit a URL. So unless you take additional measures, any user could ask for the cdkeys of any other user, just by modifying the id parameter in the URL.

table-design for addbuddy module

I'm rebuilding an add-buddy module and I have a question about the database table design.
In the current version i have a design like this:
id | user1_id | user2_id | status
Each time an user invites another, two rows are created, in one row the current users id is placed in the field user1_id, in the next row the users id is placed in user2_id, which enables me to use a rather simple MySQL query in the list mode of the module:
WHERE a.id=b.user2_id AND b.status = 1 AND b.user1_id = '".$get_user."'
Now, i try to find another way to build this, as i would prefer to have only one row for each friendship, instead of the currently used two.
I have come up with several approaches for table-design and building the logged in users buddylist and i would like to see your opinion about this.
using only one field "ids" for both users ids, comma-seperated. in the select-query i check if the field ids contains the logged in users id, probably using LIKE for that. Than in the while loop i would remove the current users id from the field with str_replace($current_user_id, '', $row['id']);
one row, with fields id1 and id2, using a simple OR in the select-query, in the while loop for building the list i would place an if-statement:
if ($row['id1'] == $current_user_id) use $row['id2'] else use $row['id1']
using two select-queries with UNION like this:
(select * from users where id1 = user_id)
UNION
(select * from users where id2 = user_id)
What do you think of this approaches would be the best for this kind of thing, or do you have another idea?
Edit: thought i would have found an easy solution for table and a matching query, but didnt work, so i deleted it.
Like #Nonym suggested, you could use the status column. Set -1 when the friendship is awaiting confirmation, 0 when the friendship has been denied, and 1 if the friendship is accepted.
Getting a list of all friends for a certain user ID is as simple as calling:
SELECT user2_id FROM users WHERE status = 1 AND user1_id = <your user id> .
Since your database is going to be filled with denied invitations, you could have a cronjob running every 24 hours or so, which will delete all denied invitations, reducing space. A query like
DELETE FROM users WHERE status = 0
would be of use. Actually, you can move even further and add another field called date, which will indicate the date when the request was sent and in the same cronjob include deleting records with status = -1, which have been in the table for too long.
EDIT
Just like #jayden said, the user_id's may be mixed, so the best way is to keep these two consistent. Like user1_id being always the current user and user2_id being the receiver. And to know, who invited who, add another field like addressee or any other (probably) more suitable name, which will hold the id of the user who initiated the request.
For starters, and while waiting for a response to the comment, I'll have to say this as soon as possible:
Approach # 1: Try to avoid doing this as much as possible. Data should be what it is; data, so refrain (when you can) from putting logic into the data. Put your logic perhaps in a view, function or stored procedure :)
[edit]
Now I'm confused. Let's take a step back, shall we?
First, you have a table that appears this way (and I will just make a rough 'sketch' of it) :
TABLE USERS
id (auto increment?)
user1_id (the one initiating the friendship invite)
user2_id (the one user1_id is inviting to form a friendship)
status (the status of the friendship; like
A record is added to the table USERS when:
A user, whose id goes into user1_id invites someone whose id then goes into user2_id , and a status is set to mean something like 2 if an invite had just been sent, and 1 if it was accepted or perhaps 0 if it was rejected, etc
What part/s in the above statements is/are incorrect?
[edit] part ii:
Everything aside, if it comes down to:
Get all records where the viewing user is either an initiator (user1_id) or is a recipient of a buddy request (user2_id)
Then you don't really need a union:
SELECT
CASE
WHEN user1_id = <Id_Of_Viewing_User> THEN user2_id
WHEN user2_id = <Id_Of_Viewing_User> THEN user1_id
END AS user_id
FROM users
WHERE
user1_id = <Id_Of_Viewing_User>
OR
user2_id = <Id_Of_Viewing_User>
Can you try the SQL above? That way, you won't need to worry about the programming part. Whatever comes out in user_id is the id of someone who has either requested to be the viewing user's friend of someone the viewing user requested to be a buddy with.
Is this... anywhere.. anywhere at all.. near what you want?

user insert into course as shown I want the course_limit to increment by 1 for that user

Let's say I have two tables as shown:
user
id plan course_limit username
10 0 ahmad
note: plan is enum field containing '','a','b','c'.
course
id user_id username
1 10 ahmad
Now I want when a user insert into course as shown I want the course_limit to increment by 1 for that user so that I can apply a limit.
now i don,t want to use triggers as my hosting does not support so i want to use php and do this. plz help me.
You could run an UPDATE statement after you run the INSERT.
(If you are using MySQL) Ex:
UPDATE user SET course_limit=course_limit+1 WHERE username = '$username'

Categories