I have 3 tables:
Users(id, username, sum_score, level)
user_badge(user_id, badge_id)
badges(badge-id, badge_name)
user_id and badge_id from user_badge are foreign keys for the ids in other two table.
I would like to update the user_badge table when the following condition is satisfied.
$selectscore= "SELECT sum_score from users WHERE id= '$id'";
$selectscorequery=mysqli_query($db,$selectscore);
while($set=mysqli_fetch_array($selectscorequery)){
if ($set['sum_score']>=0) {
$newbie="UPDATE user_badge a JOIN users u ON a.user_id = u.id JOIN badges b ON a.badge_id = b.badge_id SET a.badge_id = b.badge_id WHERE user_id='".$set["id"]."'" AND b.badge_id='7';
mysqli_query($db,$newbie)or die(mysqli_error($db));
}
I tried insert ignore query at first but it was not working, it was just adding a new row every time. So i used the update query. I know there is something wrong with the query. Could someone help me out with this problem. I never used update on many to many relationship before.
If I understand it right you will give a user the badge_id=7 when his sum_score is greater then 0 ?
In this case I don't want to work with joins, because in my opinion you only have to update the table user_badge to set the relationship
$selectscore= "SELECT sum_score from users";
$selectscorequery=mysqli_query($db,$selectscore);
while($set=mysqli_fetch_array($selectscorequery)){
if ($set['sum_score']>=0) {
// Query if badge already exists
$selectbadge= "SELECT user_id from user_badge WHERE badge_id='7' AND user_id='".$set["id"]."'";
$selectbadgequery=mysqli_query($db,$selectbadge);
if (mysqli_num_rows($selectbadgequery)<1) {
// INSERT THE BADGE
echo "insert Batch Newbie for User User: ".$set['id']."\n";
$newbie="INSERT user_badge (user_id,badge_id) VALUES ('".$set["id"]."','7')";
} else {
// UPDATE THE BADGE
echo "update Batch Newbie for User User: ".$set['id']."\n";
$newbie="UPDATE user_badge SET badge_id = '7' WHERE user_id='".$set["id"]."' AND badge_id='7'";
}
mysqli_query($db,$newbie)or die(mysqli_error($db));
}
}
Related
I am trying to write a simply query that will delete an event based off its event_id. That event_id could be in 1 of 3 tables in a database however.
Leagues
Tournaments
Trainings
Each event_id is generated by a randomizer function so each id is unique.
I have tried a few different syntaxs for SQL but none of them will actually delete the event from the DB table. Any suggestions?
Here is what I have:
if(isset($_POST['delete'])){
$query = "delete from leagues where event_id= '$event_id', delete from tournaments where event_id= '$event_id', delete from trainings where event_id= '$event_id'";
$result = mysqli_query($conn, $query);
header('location: index_admin.php');
} else {
}
I have also tried using the union command, using multiple delete queries, putting a semicolon after each delete command. What else can I try?
No reason to execute 3 separate DELETEs.
DELETE leagues, tournaments, trainings
FROM (SELECT $event_id AS event_id) src -- use parameter instead of immediate insert
LEFT JOIN leagues USING (event_id)
LEFT JOIN tournaments USING (event_id)
LEFT JOIN trainings USING (event_id)
Of course you'd not insert the value into the query like above - you'd use prepared statement.
if(isset($_POST['delete'])){
$stmt = $pdo->prepare('delete from leagues where event_id = :event_id');
$stmt->execute([ ':event_id' => $event_id]);
$res = $stmt->fetch();
header('location: index_admin.php');
}else{
}
My review_shared table looks like this. The column names are review_shared_id, cat_id, review_id, user_id, contact_id.
I'm trying to figure out a way of seeing if $cat_id is shared by users other than the current user, $user_id, who in this case is 10219.
For example $cat_id is 188. Is this shared with users other than 10219? Yes - it's shared with user_id number 3729.
I'm not sure how to proceed, would be grateful for some help.
What I have so far is:
//check if $cat_id is being used by users other than $user_id
//we do this in the review_shared table
$query3 = "SELECT * FROM review_shared WHERE cat_id = ?";
$stmt3 = $con->prepare($query3) or die(mysqli_error($con));
$stmt3->bind_param('i', $cat_id) or die ("MySQLi-stmt binding failed ".$stmt3->error);
$stmt3->execute() or die ("MySQLi-stmt execute failed ".$stmt3->error);
$result3 = $stmt3->get_result();
while ($row = $result3->fetch_assoc()) {
//get the corresponding user_id for that cat_id
$matching_user_id = $row["user_id"];
If ($cat_id is shared by users other than the current user, $user_id) {
}
else {
}
Just add it to the where clause using a not equal operator (<> or != will both work in MySQL).
The query below will return all distinct userids. I added distinct, because it seems that there are multiple rows for cat 188 and the same userid, so without distinct, you would get that same user id multiple times. This query will return 0 rows if there are no other users that this cat is shared with.
SELECT DISTINCT
user_id
FROM review_shared
WHERE cat_id = ?
AND user_id <> ?
If you just want to know how many, you can count it. The query below will return one row with one value. That value is the number of users it is shared with apart from the given user id. The query will return the value 0 if there are no such users. distinct is added within the count, to count each distinct user_id only once. Otherwise your example data would result in 4, because cat 188 is shared 4 times with the same user.
SELECT
COUNT(DISTINCT user_id) AS user_count
FROM review_shared
WHERE cat_id = ?
AND user_id <> ?
I am trying to get value of foreign key in my view. But i don't know how to do that. My table structure is like:
requisition:
users:
requisition_approval
I got all values from the requisition table with:
$qry = "SELECT * FROM requisition where created_by = '$uid'";
$result = $this->fetch($qry);
return $result;
But it will return id in foreign key values. I want to get name of user from users table and approval status from the requisition_approval table. How can i do that?
You are looking to learn about JOINS:
SELECT R.*, U.*
FROM requisition R
LEFT JOIN users U ON R.created_by=U.id
WHERE R.created_by = '$uid'";
From your example, requisition_approval table is not clearly linked. You need a common field
I am creating a Log in and I have separate tables for Users A and Users B.
What I want to do is check first in first table if the Users that trying to Login is in the Table A,
if YES, it will not go to the Table B to check the Login credentials, if NOT, go to Table B and check the Login credentials.
Table A
SELECT * FROM tableA WHERE userId='$userId' AND password='$password'
Table B
SELECT * FROM tableB WHERE accountNumber='$accountNumber' AND password='$password'
Note: The 2 Tables has different Field Name userId and accountNumber.
I presume you are fetching the values of username and password from client side so I will tell you only what you asked for.
$getUserBasic1=$db->prepare('SELECT * FROM tableA WHERE userId="$userId" AND password="$password"');
$getUserBasic1->execute();
$user= $getUserBasic1->fetchAll();
if(count($user)>0)
{
//if yes do what you want here
}
else
{
$getUserBasic2=$db2->prepare('SELECT * FROM tableB WHERE accountNumber="$accountNumber" AND password="$password"');
$getUserBasic2->execute();
$user2= $getUserBasic2->fetchAll();
//write your code here
}
You could use an INNER JOIN and select both table results taking Table A's result first if it exists, else take Table B's result.
Assuming both tables have some sort of reference like the User ID you can use something like this:
SELECT tbla.*, tblb.* FROM tableA tbla
INNER JOIN tableB tblb ON tbla.userId = tblb.userId
WHERE userId='$userId' OR accountNumber='$accountNumber' AND password='$password'
ORDER BY userId ASC
LIMIT 1
The query above uses the cross-reference (userId in this case) and joins both tables together before querying the results. It orders the results by Table A before Table B but limits the result to 1 bringing either Table A or Table B out depending which is null.
Try combining the tables, some thing like:
SELECT * FROM tableA, tableB WHERE tableA.userId='$userId' AND tableA.password='$password' OR tableB.accountNumber='$accountNumber' AND tableB.password='$password'
I have not checked, so may not work, but see if this gets what you are looking for!
Something like this:
$sql = "SQL QUERY FOR TABLEA";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// checking if result in TABLE A
}
else{
//search in TABLE B by updating your sql value.
}
I hope that you want to check for the registered user, the best way to do that is to keep one table and just search there itself keeping the userID as the primary key.
I have a table named users and has a user_id, and a table named groups and has a group_id and also have user_id that is a foreign key reference from users's user_id.The situation is here: if the user joined a group, his/her user_id is inserted into table groups. So if the user joined two different groups, the column 'user_id' in table 'groups' will insert two or more same user_id's. Well, I just want to bring the user_id once, either he/she joined two or more groups..
I have no idea how to loop it properly without getting user_id that is the same.... I just want it to loop once...
$query_groups = mysql_query("SELECT * FROM groups");
while ($rows_g = mysql_fetch_assoc($query_groups)) {
$g_user_id = $rows_g['user_id'];
$query_users = mysql_query("SELECT * FROM users WHERE user_id='$g_user_id'");
while ($rows_u = mysql_fetch_assoc($query_users)) {
echo $rows_u['user_id'];
}
}
change your code as follows:
$query_groups = mysql_query("SELECT user_id FROM groups LEFT JOIN users ON users.user_id = groups.user_id GROUP BY groups.user_id");
while($rows = mysql_fetch_assoc($query_groups))
{
echo $rows['user_id'];
}
You are using $rows_g but the variable is namend $rows in the first while loop.
Wrong:
$g_user_id = $rows_g['user_id'];
Correct:
$g_user_id = $rows['user_id'];
But try to use joining tables, because this is an inefficient way to get the wanted data.
In your case you should use LEFT JOIN.