How to join two diffrent tables in php PDO - php

I have two tables with this content:
Table users:
id 1
username demoUser
pwd 123
uid ghuyd3t2fgaggascxucxtu767fjc1g1e
Table all_product:
id 1
p_name demoNmae
price demo
product_id ghuyd3t2fgaggascxucxtu767fjc1g1e
I want to join them and fetch data, this is the code I'm using:
$uid = $_GET['pid'];
$query = "SELECT users.*, all_product.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}
But I got this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'' in /Applications/AMPPS/www/AppenceMedia/fetch_user.php:22 Stack trace: #0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22): PDOStatement->execute() #1 {main} thrown in /Applications/AMPPS/www/AppenceMedia/fetch_user.php on line 22

You're using the alias of table but in select you're using the name of table.. that gives you the error.
Also in where condition bind the parameter
Try this code:
$uid = $_GET['pid'];
$query = "SELECT tableUsers.*, tableProduct.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = :product_id";
$statement = $con->prepare($query);
$statement->bindParam(':product_id', $uid, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row){
echo $row['id'];
echo $row['username'];
echo $row['p_name'];
}

Be sure that you have really a table named users and If you are using table alias the try use these in everywhere
$query = "SELECT tableUsers.*, tableProduct.*
FROM users tableUsers
JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id
WHERE tableProduct.product_id = tableUsers.$uid";
anyway you should not use php var in sql .. you are at risk for sqlijection .. try take a look at prepared statement and binding param

I think your query is a bit wrong. You should do it like:
table_name as table_alias
So in your case:
$query = "SELECT users.*, tableProduct.* FROM tableUsers as users JOIN all_product as tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";
br

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

Fetching number of rows after PDO execute

I am trying to show the number of rows found in the database after the searching.
Here is my code:
$city = $_POST['city'];
$bloodType = $_POST['donorType'];
$q = $db->prepare("SELECT count(*) FROM `users` AS numusers WHERE `city` = :city AND `bloodType` = :bloodType");
$q->bindValue(":city",$city,PDO::PARAM_INT);
$q->bindValue(":bloodType",$bloodType);
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
echo "<p align='center'><h5> There is/are <span class='red-text'>".$row['numusers']."</span> available donor(s) found.
You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";
}
That's the last try I did. And I get this error message
`Notice: Undefined index: numusers
How do I solve that Tips ?
Just create alias of count(*)
SELECT count(*) AS numusers..
It would be
$q = $db->prepare("SELECT count(*) AS numusers FROM `users` WHERE `city` = :city AND `bloodType` = :bloodType");
There is a special method in PDO to retrieve this kind of data - a single value returned by the query, PDOStatement::fetchColumn(). So you don't have to hassle with aliases at all.
Besides, a while loop is superfluous here.
$city = $_POST['city'];
$bloodType = $_POST['donorType'];
$q = $db->prepare("SELECT count(*) FROM `users` WHERE `city` = :city AND `bloodType` = :bloodType");
$q->bindValue(":city", $city, PDO::PARAM_INT);
$q->bindValue(":bloodType", $bloodType);
$q->execute();
$numusers = $q->fetchColumn();
echo "<p align='center'><h5> There is/are <span class='red-text'>$numusers</span> available donor(s) found.
You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";

Alternate query using if statement in PHP

I'm trying to run an alternate query if the initial query fails (it does because the id I'm searching for in this instance only exists in one of the databases being joined) using an if statement and I've constructed it like so:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php/link_costreport_2013.php');
$id = $_GET['id']; //ID # For page/query
if($query = $link->prepare("SELECT locale.id, locale.provider_num, locale.provider_name, locale.state, locale.city,
finstat_ca.coh_and_banks, finstat_ca.temp_investments, finstat_ca.notes_receivable, finstat_ca.accounts_receivable, finstat_ca.other_receivables,
finstat_ca.afun_and_ar, finstat_ca.inventory, finstat_ca.prepaid_expenses, (finstat_ca.other_cur_assets + finstat_ca.due_from_other_funds) as other_cur_assets, finstat_ca.total_current_assets,
finstat_fa.total_fixed_assets,
finstat_olta.investments, (finstat_olta.dep_on_leases + finstat_olta.due_from_owners_officers + finstat_olta.other_assets) as all_olta, finstat_olta.total_other_assets, finstat_olta.end_assets,
finstat_cl.accounts_payable, finstat_cl.salaries_wages_fees_payable, finstat_cl.payroll_taxes_payable, finstat_cl.notes_loans_payable, finstat_cl.deferred_income, finstat_cl.total_current_liabilities,
(finstat_cl.total_current_liabilities - (finstat_cl.accounts_payable + finstat_cl.salaries_wages_fees_payable + finstat_cl.payroll_taxes_payable + finstat_cl.notes_loans_payable + finstat_cl.deferred_income)) as all_other_cl,
finstat_ltl.mortgage_payable, finstat_ltl.notes_payable, finstat_ltl.unsecured_loans, finstat_ltl.other_long_term_liabilities, finstat_ltl.total_long_term_liabilities,
finstat_talfb.total_fund_balance, finstat_talfb.total_lia_plus_fb
FROM `locale`
INNER JOIN `finstat_ca`
ON locale.id = finstat_ca.id
INNER JOIN `finstat_fa`
ON locale.id = finstat_fa.id
INNER JOIN `finstat_olta`
ON locale.id = finstat_olta.id
INNER JOIN `finstat_cl`
ON locale.id = finstat_cl.id
INNER JOIN `finstat_ltl`
ON locale.id = finstat_ltl.id
INNER JOIN `finstat_talfb`
ON locale.id = finstat_talfb.id
WHERE locale.id = :id
LIMIT 1")){
} else {
$query = $link->prepare("SELECT id, provider_num, provider_name, state, city
FROM `locale`
WHERE id = :id
LIMIT 1");
}
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
Basically it defaults to the single table where the ID does exist and only pulls a couple fields as opposed to the large statement above it. My only issue is that my code here is not working. My JSON only says false when I echo it. It obviously should not.
Is there an error in my code here?
Thanks in advance
:edit: I should note that when I enter an ID that exists in all the tables joined, the correct result (json) is displayed on the page.
I believe the problem is that even if ID does not exist in the first query, the $query variable still has a proper query in it and there is nothing false about it. That's not what you should be if-testing.
I think you should be testing $results.
This shows you the logic.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql_1 = "SQL CODE FOR QUERY 1";
$sql_2 = "SQL CODE FOR QUERY 2";
$query = $link->prepare($sql_1);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if (!$results)
{
$query = $link->prepare($sql_2);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
}
echo json_encode($results);
However as you can see there are a few lines of code that are repeated inside the if-statement that very similar to code that was just before the if-statement. Perhaps with a loop that loops twice but breaks out if $results is not false would be neater.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql[] = "SQL CODE FOR QUERY 1";
$sql[] = "SQL CODE FOR QUERY 2";
foreach ($sql as $sql_query)
{
$query = $link->prepare($sql_query);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if ($results)
{
break;
}
}
echo json_encode($results);
The world is your oyster.

Select all values from multiple tables

I am new to both mysql and php.
I have two tables which are 'members' and 'points'. Both of them including the column 'username'. I want to select all the values from these two tables where username= $POST[username].
So I wrote this but this is not working.
$username = $_POST['username'];
$sql = $con->prepare("SELECT *.members, *.points FROM members, points WHERE
username=?");
$sql->bind_param("s", $username);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
And I tried this :
$sql = $con->prepare("SELECT * FROM members INNER JOIN points
ON username.points = username.members WHERE username=?");
$sql->bind_param("s", $username);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
And this:
$sql = $con->prepare("SELECT *.points, *.members FROM members INNER JOIN points
ON username.points = username.members WHERE username=?");
$sql->bind_param("s", $username);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
I can't use UNION because the number of columbs are not equel in these tables.
So, Please help me what is wrong with the code? What is the proper way to select all from multiple tables.
Alias are meant to be used to specify to which table those column belong, so you need to prepend table name to your columns
SELECT * FROM members
INNER JOIN points
ON points.username = members.username
WHERE points.username = ?
You can otherwise assign an alias to your table while selecting and use them
SELECT * FROM members a
INNER JOIN points b
ON a.username = b.username
WHERE a.username = ?
You were close with this:
SELECT *.points, *.members
FROM members
INNER JOIN points ON username.points = username.members
WHERE username=?
Try this instead:
SELECT *
FROM members
INNER JOIN points ON members.username = points.username
WHERE members.username=?
check this
SELECT * FROM points,members WHERE points.username="'.$_POST['username'].'" AND members.username="'.$_POST['username'].'";
you can check this query it is very simple.

Fetch all specific results from a table, and store them into a array

Hello, I am not sure if it's been asked already, but I've been googling for 20 minutes now, could not find a relevant answer.
I am trying to fetch ALL thread_id's in my table, and then store them into a array named $ids[]
And then make a query:
SELECT * FROM posts WHERE tid = $ids[]
Basically, I want to fetch ALL of the posts, that their tid column is one of these that in the array.
How do I do this?
I am using PDO by the way.
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2 , 3 , 4 , 1' ORDER BY pid ASC LIMIT 10' at line 1' in C:\xampp\htdocs\bronified\index.php:77 Stack trace: #0 C:\xampp\htdocs\bronified\index.php(77): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\bronified\index.php on line 77
<?php
$test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$test->execute();
while ($row = $test->fetch(PDO::FETCH_ASSOC))
{
echo'<li>'. $row['subject'].'</li>';
}
$get = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC LIMIT 10");
$get->execute();
$array = $get->fetchAll(PDO::FETCH_COLUMN, 0);
?>
</ul>
<?php
$test = $pdo->prepare("SELECT * FROM mybb_threads ORDER BY replies DESC");
$test->execute();
$fetch = $test->fetch(PDO::FETCH_ASSOC);
$new = $pdo->prepare("SELECT * FROM mybb_posts WHERE replyto = 0 AND tid IN :ids ORDER BY pid ASC LIMIT 10");
$new->execute(array(":ids" => implode(" , ",$array)));
while ($row = $new->fetch(PDO::FETCH_ASSOC))
{
echo
'
<div id="st-'.$row['tid'].'-'.$row['fid'].'">
<h4>'.$row['subject'].'</h4>
<p>
'.$row['message'].'
</p>
</div>
';
}
?>
using IN and implode
$idsStr = implode(',', $tids);
$sql = "SELECT * FROM posts WHERE tid IN ($idsStr)";
Edit: Assuming you know these ids are ints, and you're not using any other prepared statement features in it, this way is easier than making it a prepared statement. If you really want to make it a prepared statement then:
$idsStr = "";
foreach($tids AS $id){
$idsStr .= "?, ";
}
$idsStr = trim($idsStr, ', ');
$sql = "SELECT * FROM posts WHERE tid IN ($idsStr)";
$sth = $dbh->prepare($sql);
foreach($tids AS $k=>$id){
$sth->bindParam($k, $id, PDO::PARAM_INT);
}
Edit2: It sounds like you just need to join. You said you want to select all the thread ids from a table:
SELECT * FROM posts INNER JOIN threads ON threads.thread_id = posts.thread_id
$query = "SELECT * FROM posts WHERE tid IN ".implode(" , ",$ids);
implodes transforms your PHP array into a string containing IDs separated by commas.
All you need is exec the query.
fetch_array -- Returns an array that corresponds to the fetched row Key->Value with MYSQLI_BOTH
$row = $result->fetch_array(MYSQLI_BOTH);
$ids = implode(',',$row['id']);
$sql = "SELECT * FROM posts WHERE tid IN ($ids)"

Categories