php - get how many available ads from table - php

I have this table advertisements, where I store all my advertisements. Everytime a user clicks on an advertisement, I record that click into a table called advertisement_clicks.
What I store in both tables is: userid and a unique token.
So, I want to count how many available advertisements there is for the user to see. Currently, I am doing it like this:
$ex = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='0'");
$ex->execute();
foreach ($ex as $normal) {
$search2=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE token=:token AND username=:username");
$search2->bindParam(":token",$normal['token']);
$search2->bindParam(":username",$userdata['id']);
$search2->execute();
}
$allnormal = $ex->rowCount();
$clickednormal = $search2->rowCount();
$normalads = $allnormal-$clickednormal;
$allnormal = how many advertisements is available.
$clickednormal = how many of these advertisements has the user clicked.
So the above approach is a bit messy and it doesn't give the correct result.
Can someone help me do this a smarter way?

You can use COUNT to get it through SQL instead.
SELECT count(*) as addCount FROM advertisement_clicks WHERE
token=:token AND username=:username"

I havn't messed with php in a while so I'm not going to even attempt to write some code lol, but the way I did it was I executed this query:
SELECT COUNT(*) FROM advertisement_clicks WHERE token=:token AND username=:username
Then get the query result which will return the advertisement count.

Related

Like system In Php

Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id

How to insert a particular value from one database table into another using '$row'?

I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)

Only one query instead of two

I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC

SQL : Select all Posts from Followers

Im trying to find an efficient way to display all posts from people who are being followed by the logged in account holder.
There are two key tables:
1- Posts
table name : posts
id, account_name, published, body
2- Follows
Table name : follows
id, account_name, followed_name
I'm trying to find a way that i can display all the posts from all the accounts that are being followed. The connection between Posts and Follows is the Account_name.
I understand that it will probably be a join, but it's how I construct the WHERE clause. So far I have the following (The account name is set via $_SESSION['account_name']):
$sql = "SELECT * FROM posts LEFT JOIN follows ON posts.account_name = follows.account_name WHERE --- How would I only get the posts from the accounts being followed ?---"
I'm sure this is something simple my brain just feels drained and I cant seem to work it out.
UPDATE Attempting in PDO
Returning NULL at the moment,
$sql = "SELECT * FROM share_posts WHERE account_name IN (SELECT followed_name FROM $this->account_follows WHERE account_name = :account_name)";
return $this->AC->Database->select($sql, array('account_name' => $account_name));
The goes to my Database Class:
public function select($sql, $array = array(), $fetch_mode = PDO::FETCH_ASSOC)
{
$stmt = $this->AC->PDO->prepare($sql);
foreach ($array as $key => $value)
{
$stmt->bindValue("$key", $value);
}
$stmt->execute();
return $stmt->fetchALL($fetch_mode);
}
The returned data is NULL at the moment even though the logged in account has followed other accounts.
$account = $_SESSION['account_name'];
//do some sql injection checking on $account here
$sql = "SELECT * FROM posts WHERE account_name IN (SELECT followed_name FROM follows WHERE account_name='".$account."')";
This will get all the posts where the account name matches somebody you follow. I wasnt sure who was following who, but in this case the followed_name are the people account_name is following. If thats the other way around, switch the values
$sql = "SELECT * FROM posts WHERE account_name IN (SELECT account_name FROM follows WHERE followed_name='".$account."')";
I will write this the way I interpret your question.
What you need to do is select only the posts from the users that are followed by your logged in user.
To break this down, first you want to select the users followed by the logged in user. To do this, we use the Follows table.
We then want to select the posts by these users. As such my query would be this.
SELECT posts.* FROM follows
LEFT JOIN posts ON posts.account_name = follows.follows_name
WHERE follows.account_name = $logged_in_user

PHP/MySQL Query

What I'm basically trying to do is get the the staff table, fetch the id of the names per job title and then hit another table (based on the id fetched) and get the data I'm interested in off.
My approach so far is make a query, go with a while loop to get all the ids of the job title im interested and for every id go with another loop ( connection-query) to subtract more data.
I think my approach is wrong cause im suspicious i could merge those two queries into one not sure how though.
//new db connection here... (1)
$query="SELECT * FROM staff WHERE jobtitle='$forEachJob'";
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$idFetched = $row['id'];
//new db connection here... (2)
$nextQuery = "SELECT * FROM schedule WHERE name='$idFetched' ORDER BY Day asc";
$nextResult = mysql_query($nextQuery)
}
You want to do a JOIN in mysql:
SELECT * FROM staff
JOIN schedule ON schedule.name = staff.id
WHERE jobtitle = '$forEachJob'
ORDER BY Day ASC
By the way, avoid using SELECT * and look into a DB wrapper such as PDO to sanitize/prepare your queries.

Categories