My Question is I need to get two conditions first one if a user is admin I need to display all transactions but if a users is not admin I need to display his own transaction only.
hers is the code that I tried but does not work.
Tables I have
Users(Id, username, password, category ...etc)
Transaction (Id, name, description, username, …etc)
SELECT IF ( (select category from users where username = ‘ali’ )==’A’) THEN
Select * from transaction
ELSE
Select * from transaction where username = ‘ali’
I also tried with this one but still no solution
SELECT IF(
SELECT category FROM users where username= 'ali' AND category ='A',
SELECT * FROM Transaction ,
SELECT * FROM Transaction where username= 'ali'
)
Thanks
try this
$where_text = ""; // initially blank
// here $user variable contains the current username
if($user!='admin') // check $user is admin or not if not
{
$where_text = " WHERE username='$user' "; // update $where_text
}
$query = "SELECT * FROM `transaction` ".$where_text; // apply in the query
Now you can user your query by $query variable
I would prefer to do this logic in the code but you can check using an OR in the where clause:
SELECT * FROM Transaction t
WHERE t.username = 'ali'
OR EXISTS (SELECT category FROM users where username= 'ali' AND category ='A')
This should work:
SELECT * FROM Transactions WHERE username = 'username' OR (SELECT 1 FROM users WHERE username = 'username' AND category = 'A')
Related
I'm trying to select commenter from a table called comments then select username from a table called users using a where clauses from the details from the first table.
After that update comments set username to the usernames obtained from table 2.
This is my code:
<?php
include("connection.php") ;
$sql=mysqli_query($link, "SELECT * FROM comment ORDER BY id ASC" ) ;
while($row=mysqli_fetch_assoc($sql)){
$commenter=$row['commenter'] ;
$sqli=mysqli_query($link, "SELECT * FROM users WHERE fullname='$commenter' ORDER BY id ASC" ) ;
while($rows=mysqli_fetch_assoc($sqli)){
$username=$rows['username'] ;
$sql_u=mysqli_query($link, "UPDATE comment SET username='$username' WHERE commenter='$commenter' " ) ;
}
}
?>
The code above only updates one row
Here is a small correction of Barmar answer
UPDATE comment c
JOIN users u ON u.fullname = c.commenter
SET c.username = u.username
u.fullname = c.commenter instead of comment
I have two tables which I'm trying to combine and get data from one of them, depending on the query.
My sql query: (Which does not work)
SELECT *
FROM contacts
INNER JOIN users
(ON contacts.user_id_sender = users.id
WHERE contacts.user_id_sender = '$user_id' AND contacts.status = 1)
OR
(ON contacts.user_id_receiver = users.id
WHERE contacts.user_id_receiver = '$user_id' AND contacts.status = 1)
Basically, I have a class that needs to return the 'users' of which 'contacts' that is a part of the users id, and has a status of 1.
The idea behind this is a Contact/Friend system table. I basically have a Users and Contacts table, and I need to return the Users data depending on which of the contacts has relation to OUR user id.
The () brackets in the ON where placed incorrect + there was a WHERE statement in the ON clause, which is not allowed.
This looks like what you wrote, but then syntactically works:
SELECT *
FROM contacts
INNER JOIN users
ON (contacts.user_id_sender = users.id
AND contacts.user_id_sender = '$user_id'
AND contacts.status = 1)
OR
(contacts.user_id_receiver = users.id
AND contacts.user_id_receiver = '$user_id' AND contacts.status = 1)
I'm trying show some records from table and if doesn't exist to show button create new. If exist to show record.
There are two tables - users
user_id
username
...
And restaurants
rest_id
name
menu
So after user is created and he log into his account must have condition if user_id has restaurant user_id = menu (menu from restaurants). If doesn't exist in restaurant show button create. This is the query with which I trying
$q = $pdo->prepare("SELECT * FROM restaurants m
LEFT JOIN users ON users.user_id = m.menu WHERE rest_id = :user_id");
$q->bindParam(':user_id', $_SESSION['user_id']);
$q->execute();
// fetch the results
$results = $q->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0) {
foreach($results as $res) {
echo ' '.$res['name'].' ';
}
} else {
echo 'Create New';
}
In this way when user login he see button Create New because he doesn't have one. The problem is when he log again after he is created record already ... button Create New is visible again.
I thing the problem is in the query or no?
UPDATE:
menu row hold user_id from session when he create new one. This is in restAdd.php
$sql = "INSERT INTO restaurants ( name, menu, image) VALUE ( :name, :menu, :image)";
$q = $pdo->prepare($sql);
$q->execute(array(
':name' => $name,
':menu' => $_SESSION['user_id'],
':image' => $forDB
));
Try with this query:
SELECT m.rest_id, m.name FROM restaurants m
INNER JOIN users ON users.user_id = m.menu
WHERE menu = :user_id
1) INNER JOIN instead of LEFT, you want to check if there are restaurants related with the user.
2)I think you did a little mistake, the menu field is wich contains the user id
In this case you need in your where clause menu = :user_id not rest_id = :user_id
Try with this:
SELECT * FROM restaurants m
LEFT JOIN users ON users.user_id = m.menu WHERE menu = :user_id"
I'm trying to display a list of users who live locally to the user who is logged in. so if the logged in session user has a postcode of 'm3 4' and 5 other users have a postcode beginning with 'm3 4' then these users will be shown to the user.
My table is laid out like this:
id | user_id | user_postcode
1 2 M3 4
2 3 SM2 7
3 4 M3 4
so in this scenario user 2 will be shown to user 4 who is logged in because their post codes match.
I'm trying to do this in mysql and it works when i put the postcode in manually like so:
AND ptb_stats.user_postcode='M3 4'
but I'm trying to make it user session specific, so if the logged in user / $_SESSION[user_id'] has the same post code as other users.
i'm trying to do it this way, but it's showing all the users without postcodes where as it should be showing the users that have matching postcodes, shouldn't it?
function get_local_users() {
global $connection;
global $_SESSION;
$query = "
SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode='".$_SESSION['user_postcode']."'";
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}
With this answer, I assume that the $_SESSION['user_postcode'] is filled from some type of input box and the value is a valid zipCode (like "M3 4").
You can use preg_match to split the zipcode from the number and try to select zipcodes form the db. Take a look at this example:
$matches = array();
$zipCode = preg_match('/^([a-z0-9]+)/i', $_SESSION['user_postcode'], $matches);
The zipcode is now in the $matches variable at the second place ($matches[1]).
Now use this value to create a query and check if it is the same as others..
$query = "SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode REGEX '^" . $matches[1] . "'";
According to what you describe, I will go onto something like that.
I used prepared statement from PDO to handle the query.
function get_local_users() {
// given that it was created like this: $connection = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
global $connection;
$stmt = $connection->prepare(
"SELECT ptb_stats.*
FROM ptb_stats, ptb_users
WHERE ptb_stats.user_id = ptb_users.id
AND ptb_stats.user_id != ?
AND ptb_stats.user_postcode = (
SELECT user_postcode
FROM ptb_stats
WHERE user_id = ?
)");
$stmt->execute(array($_SESSION['user_id'], $_SESSION['user_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
If the user id is stored in $_SESSION['user_id'], you can get the local users with
select u.id, u.name
from ptb_users u
join ptb_stats s1 on s1.user_id = $_SESSION['user_id']
join ptb_stats s2 on s2.user_id = u.id and s2.user_postcode = s1.user_postcode
where u.id <> $_SESSION['user_id']
SQLFiddle
If you have the postcode in $_SESSION['user_postcode'], it is even easier
select u.id, u.name
from ptb_users u
join ptb_stats s on s.user_id = u.id
and s.user_postcode = $_SESSION['user_postcode']
where u.id <> $_SESSION['user_id']
SQLFiddle
Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1