adding up tables in mysql - php

Hello I have a table with 11 in and about 7 tables with 1 in
Each has 2 column username and clicks. The problem is that i have to add up all the clicks were username = username Is there anyway i can do that ?
I'm using
$result1233 = mysql_query("SELECT * FROM urls_non_loggedin WHERE username='$_SESSION[username]'");
$num_row3s = mysql_num_rows($result1233);
But I want to add up all the clicks "the column name " where username = $_SESSION[username]
If you get what I mean ?
So there is a table with 2 columns clicks and username I want to grab all the numbers in clicks and add them up were username = usersname

You can use the SQL SUM operator. Like this:
SELECT username, SUM(clicks) As number_of_clicks FROM urls_non_loggedin WHERE username='$_SESSION[username]' GROUP BY username
Although you should be careful from passing variables into your queries that you have not sanitized.
EDIT: I replaced * with username in accordance to the comment from the moderator

Related

Seeing how many posts have been made from male users (Using data from two tables to calculate number)

I have two tables:
users - Where gender information is stored:
id
username
gender
user_thoughts- Where all posts are stored:
id
added_by
What I am trying to do is determine how many posts have been made by male and female users separately. But I am just completely stumped on how to achieve this. So far, I have the following:
<?php
include ("connect.php");
// updating table posts_by_gender whenever admin logs in.
// 1.Get gender of user to compare against the author or the thought
$get_all_users_gen = mysqli_query ($connect, "SELECT gender FROM users WHERE account_type = 'user'");
while ($getting_gen = mysqli_fetch_assoc ($get_all_users_gen)){
$gender = $getting_gen['gender'];
// 2. Get all posts
$getting_thoughts = mysqli_query ($connect, "SELECT username FROM user_thoughts");
$getting_th = mysqli_fetch_assoc ($getting_thoughts);
$added_by = $getting_th['added_by'];
} // while closed
?>
I am just completely confused on what to write after this.
Summary:
Trying to check each row in user_thoughts table, get the added_by data (which is the same as username from users table) and see if that user is male or female.
At the end of the check, I need a variable which holds a number of how many posts belong to male users, and how many to female.
You can do this with a Join... An example given below
SELECT * FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
This will get all user thoughts by male... Then you can do a mysqli_num_rows($query) to get the count.
You can do the same for females...
However, if you only need the count, it may be adviseable to run
SELECT COUNT(*) AS number FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
and this would return the number of rows directly.

two pdo selects in one if there is a result in both tables

So i have a problem i have a user table and a website table i need to select a random user from the users table just there username were there is a row in the website table with there username.Is this possible ?
So i am getting a random user table
$stmt9 = $db->prepare('SELECT * FROM users WHERE coins >= ? ORDER BY RAND() LIMIT 1');
$stmt9->execute( array('1') ) ;
$row = $stmt9->fetch();
Now some how i need to grab a random website were the owner = there username like so
$stmt21 = $db->prepare('SELECT * FROM websites WHERE owner = ? ORDER BY RAND() LIMIT 1');
$stmt21->execute( array($row['username']) ) ;
$row21 = $stmt21->fetch();
The problem i have is it will grab the username fine but then if the user has not submitted a website the second select will fail so some how i need to put both these select together. And grab a row of the website table were there is a row and were the coins in the user table is over 1.
You could check if the first query returns an empty set, anyway if you want one query and you are not interested in the username you could use this:
SELECT
*
FROM
websites w
WHERE w.owner
IN (SELECT u.username FROM users u WHERE u.coins >= ?)
ORDER BY
RAND()
LIMIT
1
If you want you can limit the username selected in the subquery adding the random order by and the limit clause.

Selecting user specific records for logged in user using multiple tables PHP MYSQL

I have 2 tables one called users and one called tv shows. Im storing the name of the user in a variable called username by doing. The users table holds the user_id PK, username, password and the tv shws table stores the tv_id PK, user_id FK, TV Show Name
$username=$_SESSION['username'];
i want to be able to display all the tv shows for the specific user that has logged in and im guessing i would need to show all the results for the user id assigned to the user that has logged in because the user_id in the tv shows table is a foreign key of the primary key user id in the users table.
Code:
$user = "SELECT user_id FROM users where username='$username'";
if(!$rs = mysql_query("SELECT * FROM tv shows WHERE user_id='$user'")) {
When i run this code i get "cannot select table"
Try this
$query = 'SELECT * FROM tv_shows where user_id=(SELECT user_id FROM users where username="'.$username.'")';
okay ,try this:
<?php
$user = musql_query("SELECT * FROM users where username='$username'");
$result = mysql_fetch_array($user);
$userid = $result['user_id'];
$sql = "SELECT * FROM tv shows WHERE user_id=".$userid;
$get_tv = mysql_query($sql);
$make_array = mysql_fetch_assoc($get_tv);
print_r($make_array);
?>
Happy coding!!
First of all, as a better design, you can have user_id in your $_SESSION.. so that you can avoid unnecessary query...
Here the problem could be due to Single quote ... So please escape your Single quote ..
Thanks
SELECT username,user_id
FROM users as a
JOIN tv shows as b ON b.user_id_id=a.user_id
WHERE a.username='{$username}'
managed to figure it out myself with help from Tornado
if(!$rs = mysql_query("$query2")) {
$query2 = 'SELECT * FROM tv_shows where user_id=(SELECT user_id FROM users where username="'.$username.'")';

prevent duplicate usernames adding a sequence number after username

I'm trying to Implement the facebook registration. It works and i'm getting back all the data I need. Now I want to assign a username to the user like this:
$username = ''.$first_name.'.'.$lastname.'';
The problem is that I don't know if a user with the same name and last name will register to the website and i would like to check if the username is taken and add a sequence number to the basic $username (facebook does the same), like this:
name.lastname
name.lastname.1
name.lastname.2
etc
I tried with:
$temp_username = ''.$first_name.''.$last_name.'';
$check_username = mysql_query("SELECT username FROM users WHERE username = '$temp_username'");
$num_rows = mysql_num_rows($check_username);
if ($num_rows == 0){
$username = strtolower($temp_username);
} else {
$username = strtolower(''.$temp_username.'.'.$num_rows.'');
}
but of course it doesn't work because there is always just one user with that username.
EDIT*** this is how I fix it (thanks to zander):
$temp_username = ''.$first_name.''.$last_name.'';
$num_rows = mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username%' "));
$username = strtolower(''.$temp_username.'.'.$num_rows.'');
$num_rows = mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username.%' ")); will return the number of rows you actually expect. Then, use $username = strtolower(''.$temp_username.'.'.$num_rows.''); to get it done. No need of loops.
The following SELECT determines the user with the highest number if there are any
select max(reverse(SUBSTRING(reverse(username), 1, LOCATE('.', reverse(username))-1))) trail
from users
where username like 'John.Smith.%';
SQL Fiddle Demo
Add it to PHP like this
...
if ($num_rows == 0){
    $username = strtolower($temp_username);
} else {
... query for the max number here
... concatenate the username with the max number
}
Ah and last but not least. Make sure your code is not vulnerable to SQL injection. Use bind parameters. Good start is this answer: Best way to defend against mysql injection and cross site scripting
There are many existing answers that correctly suggest using the LIKE operator in your WHERE clause. But there is one critical issue that none of the existing answers have addressed.
Two people could attempt to add the same username at the same (or nearly the same) time. Each would SELECT the count of existing usernames that are LIKE that name, and they each would generate the same number suffix, and you still get duplicates.
I am neither a mysql developer nor php developer, so I won't provide much in the way of specific syntax.
You will want to make sure your users table uses the InnoDB storage engine. Your code will need to:
START TRANSACTION
SELECT FOR UPDATE to make sure only one person can get the count of
a particular username at a given time
INSERT your new user
COMMIT your transaction.
See Select for update for more information.
Use this code instead:
$check_username = mysql_query("SELECT username FROM users WHERE username = '$temp_username' OR username LIKE '$temp_username.%' ");
example this will match:
johnsmith or joshnsmith.X where x will be 1 , 2 , 3 .......etc
DB Dump
CREATE TABLE Users (
`username` varchar(255) PRIMARY KEY,
`firstname` varchar(255),
`lastname` varchar(255)
);
INSERT INTO Users (`username`, `firstname`, `lastname`) VALUES (
'praveen.kumar', 'Praveen', 'Kumar'
),(
'praveen.kumar.1', 'Praveen', 'Kumar'
),(
'praveen.kumar.2', 'Praveen', 'Kumar'
);
Now to the SQL, we can do this way:
SELECT *
FROM `Users`
WHERE `username` LIKE "praveen.kumar%"
ORDER BY `username` DESC
Gives an output:
+-----------------+-----------+----------+
| USERNAME | FIRSTNAME | LASTNAME |
+-----------------+-----------+----------+
| praveen.kumar.2 | Praveen | Kumar |
| praveen.kumar.1 | Praveen | Kumar |
| praveen.kumar | Praveen | Kumar |
+-----------------+-----------+----------+
And you can get the latest one this way:
SELECT *
FROM `Users`
WHERE `username` LIKE "praveen.kumar%"
ORDER BY `username` DESC
LIMIT 1
The PHP Code:
<?php
# Outputs the largest number with that username.
$nextUser = substr($userNameFromDB, strrpos($userNameFromDB, "."));
$nextUser++;
?>
SQL Fiddle: http://sqlfiddle.com/#!2/ad149/1
Use the count() function and the like operator:
$check_username = mysql_query("
SELECT count(username)
FROM users
WHERE username like '$temp_username%'
");
It will return the number of existent names. No need to call mysql_num_rows.
You should use the count() function
$query = mysql_query("
SELECT count(user_name) cnt
FROM users
WHERE username = '$just_registered_username'
");
and then fetch the result using
$row = sql_fetchrow($query);
And then get the count of users as
$next_index = $row->cnt;
Then append it to the new username
$new_username = "{$just_registered_username}.{$next_index}";
Don't forget to add comments to your final code.
Also try and use PDO for database access.
If you want to find a user name that does not exist, you have to try combinations, until you find a non existing username.
Therefore, loop until you find a non existing name:
$temp_username = $first_name . $last_name;
$i=1;
$found = false;
while(!$found) {
$check_username = mysql_query(
"SELECT username FROM users WHERE username = '$temp_username'");
$found = mysql_num_rows($check_username);
if ($found){
$username = strtolower($temp_username);
}
else{
$temp_username = $first_name . $last_name . '.' . $i;
$i++
}
}

Joining tables in MySql with one common field but different values for the common field

how to join 3 tables with one common field like
table1:c_id,username,password,c_role
table2:p_id,username,password,c_role
table3:s_id,username,password,c_role
in this c_role field is common
here i assigned
enum '1' for c_role in table1
enum '2' for c_role in table2
enum '3' for c_role in table3
for giving rights to 3 different users like corres, principal and for a staff when they login..
Now when they login it should identify the user and take them to their page..
You should have one table that contains the following columns:
id (unique, primary), username, password, role (INT, would be assigned 1-3 for principal, staff or corre depending on the user)
Additionally
You could have another table called roles if you want set up like this:
id (unique, primary), title (options for title would be principal, staff, or corres)
When the user logs in just do something like
if($role == 1){
// redirect to principal page
}
elseif($role == 2){
// redirect to staff page
}
elseif($role == 3){
// redirect to corres page
}
I'm not certain but I believe this would work as well. Try this query.
(SELECT '1' AS role FROM table1 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '2' AS role FROM table2 WHERE username = $username AND password = $password)
UNION ALL
(SELECT '3' AS role FROM table3 WHERE username = $username AND password = $password)
Assuming the user is only located in ONE of those three tables then it should match the username and password and find out which table the user is coming from. Then you can pull out the role by using
$role = $row['role'];
If the username/password combination is incorrect then $role would be empty or you could fetch the number of rows [using $iscorrectuser = mysql_num_rows($query)] where there is a match and the number of rows would be 0. You could then redirect the user trying to log in with a "Unsuccessful login" error message.
The only joins would be on username (and password ?) unless c_id, p_id and s_id are all the same id?
You can't join on role seeing as they are different in each table, aside from an utterly daft role = 1 in Table1 is the equivalent of role = 2 in table2.
Do you mean a union? As in you want
User Password Role
Fred Fr3d 1
Fred ??? 2
Fred ??? 3
Not sure what you are trying to achieve with this schema, but it breaks near every rule in the book, and doesn't seem to meet your needs....
Based on your comment, one way you might look at is.
Is
Users (UserID, UserName, Password etc) Key UserID
Roles (RoleID, RoleName etc) Key RoleID
UserRoles(UserID,RoleID) Key UserID,RoleID
You need to learn a bit about databases particularly normalisation, first three forms should do for most things.
Then
Select UserName, Password,RoleName From Users
inner join UserRoles on Users.UserID = UserRoles.UserID
inner join Roles on UserRoles.RoleID = Roles.RoleId
and such like become possible and efficient.
session and include functions are given:
session_start();
include("config.php");
if(isset($_POST['T_UserName']) && isset($_POST['T_Password']) && !empty($_POST['T_UserName']) && !empty($_POST['T_Password']))
{
username and password sent from form:
$T_UserName=$_POST['T_UserName'];
$T_Password=$_POST['T_Password'];
To protect MySQL injection:
$T_UserName = stripslashes($T_UserName);
$T_Password = stripslashes($T_Password);
$T_UserName= mysql_real_escape_string($T_UserName);
$T_Password = mysql_real_escape_string($T_Password);
$sql="SELECT * FROM login WHERE username='$T_UserName' and password='$T_Password'"; $result=mysql_query($sql);
Mysql_num_row is counting table row:
$count=mysql_num_rows($result);
If result matched $T_UserName and $T_Password, table row must be 1 row :
if($count==1)
{
Register $T_UserName, $T_Password and redirect to file "correspindex.php" :
session_register("T_UserName");
session_register("T_Password");
redirect to error page or display error message then :
if(isset($_POST['emp_role'])
{
$userinfo = mysql_fetch_assoc($sql);
$emp_role = $userinfo['emp_role'];
if($emp_role == 1)
{
header("location:corrrespondindex.php");
}
elseif($emp_role == 2 )
{
header("location:principalindex.php");
}
elseif($emp_role == 3)
{
header("location:staffindex.php");
}
closes out if the user DOES exist:
header("location:loginhome.php");
}
else
{
echo "Wrong Username or Password";
}
}
}
php is closed
this is the php code im getting so many error
i create 1table with id,username,password and role(ENUM,values as'1','2','3' –
any else shud i do in the code???

Categories