Add Friends Function - friend already added - php

I have an application to add friends. I need to have my script to check, if the users' already friends. I thought I could do this by a COUNT. I did like this:
$username = $_GET[user];
$ven_til_id = $_SESSION['userID'];
$num = 1;
if(isset($_GET['add_friend'])){
$check=("SELECT username,ven_til_id, COUNT(*) AS num FROM friends WHERE username=$username AND ven_til_id=$ven_til_id GROUP BY username,ven_til_id")or die(mysql_error());
$result=mysql_query($check);
if(!$result){
echo "Cant run query.";
} else {
$num = mysql_num_rows($result);
}
if($num>0){
header("Location: /profil/$username?add_error");
} else {
$sql=mysql_query("INSERT INTO friends (username,ven_til_id)VALUES('$username', '$ven_til_id')")or die(mysql_error());
header("Location: /profil/$username");
}
}
?>
But when I'm adding one friend it's fine. It adds it and everything is fine. But then when I try to add another, it says we're already friends. I guess it's because it's counting how many times my ID (ven_til_id) is listed in the tables.

You're missing a comma:
SELECT
username,ven_til_id COUNT(*) AS num FROM ...
should be
SELECT
username,ven_til_id, COUNT(*) AS num FROM ...
Also, your reference to the count field is incorrect - it should be the third column or $row[2]
You may want to make your code more robust by referring to fields by name eg $row['num']
One final thing to confirm is that the value being retrieved with a count is being treated as an integer not a string. I don't think it's the problem here but you may want to explicitly cast it to avoid possible issues later eg...
$num = (int) $row[2];
Option 1
Just select the appropriate rows and see how many records you get back...
SELECT username,
ven_til_id
FROM friends
WHERE username=$username
AND ven_til_id=$ven_til_id
Then just count the number of records returned using PHP - eg mysql_num_rows() (I think that's the correct function name)
Clarification:
Change
$row = mysql_fetch_row($result);
$num = $row[2];
to
$num = mysql_num_rows($result);
Option 2
Get MySQL to do the counting for you - in qhich case you need to tell it to group multiple record together...
SELECT username,
ven_til_id,
COUNT(*) as Num
FROM friends
WHERE username=$username
AND ven_til_id=$ven_til_id
GROUP BY username,
ven_til_id
Then just read the 3rd value of the first row (num) and you'll have a count
NB: The second method may be overkill if you're only ever expecting a 1 or a 0

Related

Row Count outputting - in front of the number of rows in table

Good day,
i have the following code in php
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid=$staffid";
$result4 = $pdo->prepare($sellast2);
$result4->execute();
$rowcount = $result4->rowCount();
echo $rowcount;
I am expecting that the row count would be one since this table only has one record in it.
The variable is outputting -1 and not 1 as expected.
What does the minus mean and why does it output a minus?
I am using Microsoft sql server management studio as the database.
$sellast2 = "SELECT id, staffid, password FROM staff WHERE staffid='$staffid'";
use your $staffid in single quotes like i did, then pass a valid staff id and get your result

Need to return the name of person with maximum value from a column (fetched from database)

$sql = "SELECT firstname FROM candidate_info1 WHERE votes=(select MAX(votes) from candidate_info1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// how do i echo the firstname of candidate with highest votes??
}
I'm new to PHP so please be gentle.
Here in the code I have to return the name of the person with maximum number of votes(stored in database candidate_info1), how do I do that?
What am I doing wrong?
Your query seems to be correct, since it:
returns the firstname
of the correct table
for the record(s) which match in vote number to the maximum vote number
However, if you need a single value, then you can use an order by desc, as suggested in other answers. If you want to return the firstname of all the records having the same vote number as the maximum, then order by desc is inadequate here.
Also, if your problem is that votes is not stored in this table, but rather in a different table, then you might need to find the groups having the maximum count from there, selecting the foreign key and then return the values in your main query using the in operator. Anyway, if you have a specific problem which was not mentioned here, then you will need to add the details.
You have to fetch record By
$person_name = $result->fetch_assoc($result);
$person_name = $person_name['firstname ']
while($row = $result->fetch_assoc()) {
$firstname=$row['firstname'];
}
echo $firstname;
In your query, you already return the name with the max votes so you just have to fetch the results in order to show that name.

Display the amount of Paid items in my database using php

I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.

MYSQL>PHP - Trouble with a query relating to function that checks if a table contains a row of user details

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.

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories