Get value from foreign key. MySQL. PHP - php

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

Related

How to use update query in many to many relationship

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));
}
}

Check First on Table A, if not found Check on other table

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.

Fetching all Data from Multiple tables based on Single id

I have to select data from multiple tables based on single key value. I have one table called maintable where I will get all the ids from, and i have another 10 tables in the same database which have maintable.id as a foreign key. Now I have to retrieve data from the 10 tables where maintable.id matches in one single table.
The code I have tried is:
$sql = select id from maintable;
$runsql = mysql_query($sql);
while($sqlRow = mysql_fetch_array($runsql ,MYSQL_ASSOC)) {
for($i=1;$i<=10(This is another table count);$i++) {
$servSql = "select * from table.$i where ref_id = ".$sqlRow['id'];
$runServerSql = mysql_query($servSql);
while($serverRow = mysql_fetch_array($runServSql,MYSQL_ASSOC)) {
}
}
}
Try something like this in a join:
SELECT * FROM maintable m
INNER JOIN othertable o
ON m.id = o.id
That will select from both tables using an inner join ON the id column. You may want to look up a basic SQL tutorial to learn the basic types of joins you can use. Good luck!

MySQL two conditions for two tables

I have a mysql query:
$query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') ");
And second:
$query5 = mysql_query("SELECT * FROM `pages_admin` WHERE (`pId`='$switch' AND `rand`='$randID' AND `admin`!='".$_SESSION['user']."') ");
I use a while loop to present data.
while($row = mysql_fetch_array($query5)) {}
I need one mysql query instead two.
If these tables are related you can JOIN them using the foreign key.
If I'm not mistaken this pId in the table pages_admin is a foreign key to the id on the table pages, is that correct?
If so, you could do something like this to you query:
"SELECT * FROM pages p
LEFT JOIN admin_pages ap on p.id = ap.pId
WHERE (`pId`=$switch AND `rand`=$randID AND `admin`!='{$_SESSION['user']}')"
Note that I've changed the syntax, instead of merging string you can use only one containing all variables you need.

Retrieving specific ID once

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.

Categories