By the way, before it is mentioned, I am well aware I should be using mysqli. Thanks in advance.
This is my code:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a 'lookup' table and has two columns:
userid and listingid
It has a many to many relationship. In other words, there could be one userid attached (associated) to multiple listingids and thus having multiple rows in that table.
e.g.
userid|listingid
1|1
1|2
1|3
2|1
etc
To keep things simple: What I want to do is check the following:
$a5['listingid'] == $_GET['id']
And if it is True I will display information and if it is False the information will not be displayed.
So on the page mywebsite.com there will be an id as so, mywebsite.com?id=[id here]. I am trying to see if the user $_SESSION[UserID] has an entry in userlisting table that matches the id of the page (well, it is a property website and the id is that of the property listing).
At the moment the code I have above just searches/checks for the first row for that userid only. In the example I gave above that would be listingid ='1' It is not seeing that row 2 and 3 also have entries in them too, listingid = '2' and '3' respectively. So on mywebsite.com?id=1 it is true, but on ?id=2 and id=3 it is coming up false, but userid = 1 has three rows with entries 1, 2 and 3.
I have been trying to find a solution for a while and I am starting to feel frustrated now. I would much appreciate it if someone could come up with a quick solution for me.
You can check both on SQL with some clause like
WHERE userid=XX AND listingid=XX
And remember to escape the get parameter ;)
PS: You can use too a while for iterate the mysql_fetch_row and search if anyone is correct. Something like:
$correct_check = false;
while($a5 = mysql_fetch_array($r5)) {
if($a5['listingid'] == $_GET['id']) $correct_check = true;
}
if($correct_check) ....
else ....
Try something like this
$page_id = $_GET['id'];
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]' and listingid = '$page_id' ";
$res = mysql_qury($result);
$num_rows = $mysql_num_rows($res);
if($num_rows > 0)
//your ok code
else
//fail message
Related
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
I have this simple query:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a many to many relationship. It is used as a lookup table. Each userid can be associated with multiple listingids and vice versa.
Also in my file (a html template file) I have this code
if(!empty($_SESSION[UserID]) and $a5['listingid'] == $_GET['id']) :
So I am wanting to check if the listingid column in userlisting table = the id of the page (well, it is a property website and it is the id of the property). As each user can be associated with many listingids I need to be able to check multiple rows. But for some reason it only checks the very first row.
In the userlisting table there is the following test entries:
userid | listingid
1 1
1 2
So one user associated to two listingids. However, it is acting like this userid is only associated with listingid 1, the very first row.
You are only grabbing the first entry.
$a5 = mysql_fetch_array($r5);
This does not fetch the whole query result, but only the first row. If there is none, it will return false.
You have to create a loop to get more results.
I am having trouble with a function that checks if a set of user entered info (username and password) exists within either of the two possible tables where this information is stored.
The first table is the users table. It contains the first set of specific user information.
The last table is the listings table. It contains the second set of specific user information.
I have basically modified my original code to include the new listings table, and hence the trouble coming from within that task. The old code basically counted the number of results in the users table, if the result was greater than 0, then the function returned true, else false.
Now I have been stuck on the best way to go about adding another table to the query, and function. So I have been playing around with a union.
This was the original query:
SELECT COUNT(*) FROM users
WHERE id='$accNum' AND password='$password'
This returned a count of either 0 or 1 based on the info stored in the users table.
This is how I have reworked the query to include a count of the additional listings table:
SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
This returned a result set of two rows, the first relating to the users table, and the second relating to the listings table. Then a column called COUNT (*) that contained the result count. This is the result set that I see within php myadmin.
Now this is the function:
function databaseContainsUser($accNum, $password)
{
include $_SERVER['DOCUMENT_ROOT'] . '/../../includes/db.inc.php';
$accNum = mysqli_real_escape_string($link, $accNum);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT count . *
FROM (
SELECT COUNT( * )
FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (
SELECT COUNT( * )
FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password'
)
)count
";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for user.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The problem that I have, is trying to work out how exactly to check the results to ascertain if the given log in credentials are valid.
I tried this: if (($row[0] > 0) || ($row[0] > 0)) But a var dump on $row showed that only the first row (count of users table) was being added to the array.
So I decided that this was complicated, and a long way to the final result.
So I tried selecting only the id column of the result as in:
...
`COUNT( * )` to `id`
...
$data = mysql_query($sql);
$num_sql = mysql_num_rows($data);
if ($num_sql > 0)
...
But this did not work out for me either.
But in either instance, my hours of trial and error have provided me with no success... So I've decided to seek help from the knowledgeable members of Stack Overflow!
So my question is this, what would be a logical way of going about this task? I am looking for any suggestions, or positive input what so ever here.
As I am fairly new to dabbling with PHP and mysql, if you would like to provide some code to explain your suggestions or input on the matter, it would more than likely help me to better understand the answer.
If you are checking existence only try doing this that way:
select case when
exists (SELECT 1 FROM users WHERE id = '$accNum' AND PASSWORD = '$password') or
exists (SELECT 1 FROM listings WHERE id = '$accNum' AND PASSWORD = '$password')
then 1 else 0
end as itDoesExist
It returns always one row with one column with 1 when record exists in at last one table (else 0).
Do not use count to check whether some specific record/-s exist/-s in table, it's usually slower than simple exists.
Looks like you're going to get two rows in the result no matter what. Try this:
$sql = "SELECT id,password
FROM users
WHERE id = '$accNum' AND password = '$password'
UNION
SELECT id,password
FROM listings
WHERE id = '$accNum' AND password = '$password'
";
Now you can just check mysql_num_rows() to see if there's a match in either of the tables.
There are a couple of ways to go about this; if we are to stick with the approach you started with; you can simplify the query to:
$sql = "SELECT COUNT(1) FROM users
WHERE id = '$accNum'
AND PASSWORD = '$password'
UNION (SELECT COUNT(1) FROM listings
WHERE id = '$accNum'
AND PASSWORD = '$password')";
The reason you are only seeing one result, is because thats the way mysql_fetch_array() works, try doing this to get all results:
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
var_dump($data);
Now you should have both values in there to validate with your conditional statements.
If I perform the following MySQL query through PHP:
UPDATE pictures
SET category = '0'
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
It works fine and any category that was equal to $categoryID gets changed to 0. However, if I perform the following:
UPDATE pictures
SET category = '0',
pictureorder = (SELECT COUNT(category) + 1 WHERE category='0' AND username='$username')
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
Not only does pictureorder not equal to the count of the category row plus one, but the category no longer gets changed if equal to $categoryID. I'm not too good at figuring this out as I know only basic MySQL through PHP and am not familiar with it through its own console.
Thanks in advance for any suggestions.
This form of query is not valid. First, your subquery is missing a FROM clause. Second, you cannot select from the same table you are updating in the same query.
http://dev.mysql.com/doc/refman/5.1/en/update.html
I have a table:
id, affiliate
Each time somebody clicks a link, a new row is inserted,
ID being the ID of the page, and affiliate being the ID of the affiliate.
For example:
Page ID: 9 Affiliate ID: 1
Page ID: 9 Affiliate ID: 2
Page ID: 9 Affiliate ID: 3
I only have 3 affiliates.
I want to select this information, and group them by affiliate, for the ID.
I have tried this query:
SELECT COUNT(*) FROM table
WHERE id = '9' GROUP BY
affiliate
It works fine when I do it in php my admin, how do I get the info in PHP?
I have tried:
$q = mysql_query("SELECT COUNT(*) FROM
table WHERE id = '" . $id . "'
GROUP BY affiliate");
$r = mysql_fetch_array($q);
When trying to print the data onto the page, I am only getting one result.
Do I need to use a foreach/while loop to get all 3? How would I go about doing this?
Thank you!
You should do mysql_fetch_array() (or mysql_fetch_assoc()) in a loop:
while ($row = mysql_fetch_assoc($q)) {
echo $row["id"];
echo $row["affiliate"];
}
UPDATE (in accordance with comment):
If you ALWAYS have 3 rows in your result, probably mysql_result() function would be helpful:
$firstAffiliate = mysql_result($q, 0, "affiliate");
$secondAffiliate = mysql_result($q, 1, "affiliate");
$thirdAffiliate = mysql_result($q, 2, "affiliate");
BTW, be careful and check, whether query actually returns 3 results.
Loop like this:
while($row = mysql_fetch_array($q)) {
print_r($row);
}
If you just want to get list of Affiliate ID, you can consider this query
select group_concat(affiliate)
from table
where id=9;
The above will return a comma separate value like 1,2,3 in single row
So, you can then in PHP explode using ,, and the size of the exploded array is the same as count(*)
you can use a variable to hold state inside the actual mysql statement itself. Try the following:
affiliates:
page_id
afil_id
set #page_id=0;
select page_id, if(#page_id <> page_id, count(*), 0), #page_id:=page_id from clicks group by page_id;
Hope that helps