1 JSON object, 2 queries, 2 tables - php

Here is my simple query:
$sql = "SELECT * FROM donations Order By userid";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
I use it to display all data from the 'donations' in a table. Fields are: userid,date,amount.
In that same table, I'd like to add firstname and lastname of corresponding userid which are stored in mymembers table. The condition should be WHERE donations.userid = mymembers.id.
I need help adding that condition for every row resulting from the $sql query.

Use join and change query to
SELECT * FROM donations
INNER JOIN mymembers on (donations.userid = mymembers.id)
Order By donations.userid

Related

Get applicants from Table 1 and compare id and get user details from Table 2 Using PHP

Ok so I have two Tables
Applicant list - this shows all applicants
User Table
Now I'm Providing news_id by Post method and I want to list details of all users(email,mobile,username) where the value for user_authToken and user_authtoken is same. Can Someone help me out with this logic using PHP.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile,
FROM appliers_list,user
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();
First of all, your naming is very inconsistent, it's hard to read and understand.
Second, please use prepare statement, otherwise you open your system to SQL injection.
$news_id = $_POST['job_id'];
$stmt = $con->prepare("SELECT email, mobile, user_name
FROM users
WHERE user_authtoken in (select user_authToken from appliers_list where news_id = ?)");
$stmt->bind_param("i", $news_id);
$stmt->execute();
$resultSet = $stmt->get_result();
while($row = $resultSet->fetch_assoc()) {
// data manipulation here
}
you can use left join to get record from both table :
$job_id = !empty($_POST['job_id']) ? intval($_POST['job_id']) : 0;
$resultSet = $con->query("SELECT appliers_list.*,users.email
FROM appliers_list
left join users on appliers_list.user_authToken = users.user_authToken
WHERE news.news_id = '$job_id'
ORDER BY news.id DESC
");
$rows = $resultSet->fetch_assoc();
You didn't specify a relationship between the user and appliers_list tables, so you're getting all rows in user. You also have an extra comma at the end of the SELECT list.
$job_id = $_POST['job_id'];
$resultSet = $con->query("SELECT appliers_list.news_id AS jobid ,
appliers_list.user_authToken AS user,
user.user_name AS username,
user.mobile AS mobile
FROM appliers_list
JOIN user ON appliers_list.user_authToken = user.user_authToken
WHERE appliers_list.news_id = '$job_id'
ORDER BY appliers_list.id DESC
");
$rows = $resultSet->fetch_assoc();

Converting SQL Table ID into another field in PHP

So I'm trying to get the following to work;
//SEARCH USERPETS TABLE FOR ANYTHING USER OWNS
$query = "SELECT * FROM userpets WHERE owner = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userspets = $row['petid'];
//SEARCH PETS TABLE FOR LIST OF PET NAMES AND DETAILS
$query = "SELECT * FROM pets";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$petid = $row['id']
$petname = $row['petname'];
$petimg = $row['petimg']
//TURN PET ID INTO PET NAME AND IMAGE
echo "Pets: ".$userspets;
Essentially what I'm trying to do is this;
The 'userpets' table contains all 'owned' pets and the players username is displayed.
I want to grab all pets owned by that user and compare the petid with the 'pets' table.
I then want to take the pet's name and image from that table and 'echo' it onto the page.
Getting all the ids is fine, I just don't know how to make it convert the id's into the names.
Table Structure
You can use JOIN of MYSQL or Foreach of PHP
This is example by using PHP Foreach
$query = "SELECT * FROM userpets WHERE owner = '".$username."'";
$result = mysqli_query($conn, $query);
$petid = array(); // store all petid of this user
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
foreach($rows as $row) {
$petid[] = $row['petid'];
}
$query = "SELECT * FROM pets WHERE id IN (".implode(",",$petid).")";
// implode will convert an array to string with delimete
// example array(0=>35, 1=>36, 2=>48) will be convert to "35,36,48"
// and above query should be : SELECT * FROM pets WHERE id IN (35,36,48)
$result = mysqli_query($conn, $query);
$pets = mysqli_fetch_assoc($result);
// dump it
echo "<pre>";
var_dump($pets);
echo "</pre>";
die;
Using MySQL Join
<?php
$query = "SELECT pet.id, pet.petname, pet.petimg, up.owner FROM pets as pet LEFT JOIN userpets as up ON pet.id = up.pet_id WHERE up.owner = '".$username."'";
I don't know how your tables look, but the best thing I can think of is, you have 3 tables one with Users, second with pets, and third "many to many" table lets call it ownedpets with users that own pets, because many users can own many pets. So ownedpets should have id_users that is connected to user.id and id_pets which is connected to pets_id. With that in mind I would do the fallowing query
SELECT *
FROM ownedpets
LEFT JOIN users
ON users.id = ownedpets.id_users
LEFT JOIN pets
ON pets.id = ownedpets.id_pets
WHERE users.id = $user_id
hope this helps

How can I show rows from one table that aren't in another table?

I have two tables in a database, one of them is a list of 'buildings' you could create. The other is a list of buildings that have been built by users.
On one page, (cityproduction.php), it displays a list of 'buildings' you can build.
I want it to display the buildings that you can build, that you haven't already built.
Here is my code:
$sql = "SELECT * FROM [The list of built buildings] WHERE building_owner = '$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$variable = $row["building_name"];
}
(...)
$sql = "SELECT * FROM [The list of ALL buildings] WHERE name != '$variable' ORDER BY id asc";
$result = mysqli_query($database,$sql) or die(mysqli_error($database));
while($rws = mysqli_fetch_array($result)){
echo $rws["name"]; (etc.)
What this is doing is only not-showing one of the buildings that the user has built, not all of them.
Without seeing the real table names or the schema it is tricky to answer accurately but you could try something along these lines:
SELECT * FROM `all_buildings`
WHERE `id` not in (
select `building_id` from `built_buildings` where `building_owner` = '$user'
)
ORDER BY `id` asc;
Another translation of your question into SQL (besides NOT IN) results in a Correlated Subquery:
SELECT * FROM `all_buildings` AS a
WHERE NOT EXISTS
(
select * from `built_buildings` AS b
where a.`id` = b.`building_id` -- Outer Select correlated to Inner
and b.`building_owner` = '$user'
)
ORDER BY `id` asc;
The main advantage over NOT IN: it's using only two-valued-logic (NULL is ignored = false) while NOT IN uses three-valued-logic (comparison to NULL returns unknown which might no return what you expect)
Why are you using while after the first query, it suppose to be a list or just a single value? because if you use $variable in your second query it will only have the value of the last value of the list you are getting
if ($result->num_rows > 0) {
$variable = array();
while($row = $result->fetch_assoc()) {
$variable[] = $row["building_name"];
}
Second query example:
foreach($variable as $building) {
$sql = "SELECT * FROM [The list of ALL buildings] WHERE name != '$building' ORDER BY id asc";
$result = mysqli_query($database,$sql) or die(mysqli_error($database));
$result = mysqli_fetch_assoc($result);
echo $result["name"];
}
Assuming both of your tables have some sort of id column to relate them, with this query:
SELECT building_name, building_owner FROM
test.all_buildings a
LEFT JOIN test.built_buildings b ON a.id = b.building_id AND b.building_owner = ?
ORDER BY building_owner DESC, building_name;
(where ? is the user), you can select all the buildings, first the ones that have been built, followed by the ones that haven't, in one query. If your tables don't have id's like that, you can join them on name instead; it should work as long as the names are distinct.
Then as you fetch the rows, you can sort them into "built" or "not built" by checking if the row has a building_owner.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['building_owner']) {
$built[] = $row['building_name'];
} else {
$not_built = $row['building_name'];
}
}
}

How to retrieve data from multiple tables using a PHP form?

I want to retrieve data from multiple tables using dot operator/join where arguments are passed from an HTML/PHP form.
HTML CODE
<input name="rollno" type="text" placeholder="Roll Number" required>
<input name="submit_view_details" type="submit" value="Proceed">
PHP CODE
if(isset($_POST['submit_view_details']))
{
$rollno = (int) $_POST['rollno'];
$query = "select * from table1, table2 where table1.{$rollno}=table2.{$rollno}";
$result=mysqli_query($connection,$query);
}
In the browser if enter the input 1 and echo this query then it looks like follows:
select * from table1, table2 where table1.1=table2.1
and no row is fetched despite of having data in the table(s).
it only works if the query looks like follows:
select * from table1,table2 where table1.rollno=table2.rollno
However, in that case it fetches all the rows but I need only the row of the rollno that user entered in the above mentioned form.
I am just not able to work this out. Help would be much appreciated. Thanks!
Use the AND keyword to specify the rollno.
SELECT * FROM table1, table2 WHERE table1.rollno = table2.rollno
AND table1.rollno = {$rollno};
You could probably use the keyword JOIN instead like this :
SELECT * FROM table1 NATURAL JOIN table2
WHERE rollno = {$rollno};
You need joins
take a reference of joins from here,
i am sure it will help
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
You should use join like this
$query = "SELECT tbl1.*, tbl2.*
FROM tbl1
INNER JOIN tbl2 ON tbl1.id = tbl2.id
WHERE tbl1.column = value ";
foreach ($pieces_2 AS $value) {
$pieces_3[] ="(CONCAT_WS('|',$presql2) like '%$value%')"; //concat all columns from one table
}
$serch_jyouken = implode(" and ",$pieces_3); // for multiple keywords
$result1 = mysqli_query($connection, "select p.p_no from pfr_data p where (" .$serch_jyouken .")");
$res1 = array();
while($r1 = mysqli_fetch_array($result1){
$res1[] = $r1['p_no'] ; //fetch primary key from table and store it into array
}
foreach ($pieces_2 AS $value) {
$pieces_4[] ="(CONCAT_WS('|',$presql3) like '%$value%')"; // same as above
}
$serch_jyouken1 = implode(" and ",$pieces_4);
$result2 = mysqli_query($connection, "select p2.p_no from pfr_mod_inform p2 where (" .$serch_jyouken1 .")" );
$res2 = array();
while($r2 = mysqli_fetch_array($result2)){
$res2[] = $r2['p_no'];
}
$res_mrg = array_merge($res1 , $res2); //merge array
$result = implode("','",$res_mrg ); // array to sring
$sql5 = $presql ." from pfr_data p where p.p_no in ('$result') order by p.section_p,p.status,p.no";

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

Categories