I am trying to pull data from my database which ahs the following:
x3 tables:
docs
doc_id - index
cat
cat_id - index
doc_cat_join
doc_id - foreign key to docs/doc_id
cat_id - foreign key to cats/cat_id
I have inserted some data so that I have a row in cats and a rows in docs and in the join table bound a cat_id with a doc_id which all works fine. I am tying to pull that from the tables and show it, here is my approach so far but not getting anything out and am wondering where my failings are as I am getting no errors?
when I visit the cateroy page in my scripts I GET the id from the url:
$id = $_GET['cat_id'];
$q = sprintf("
SELECT
docs.doc_id,doc_name
FROM docs
INNER JOIN doc_cat_join
ON cats.cat_id = doc_cat_join.cat_id
WHERE doc_cat_join.doc_id = '%s'
",
mysqli_real_escape_string($dbc, $id) );
$r = mysqli_query($dbc,$q)
or die ("Couldn't execute query: ".mysqli_error($dbc));
// FETCH AND PRINT ALL THE RECORDS
echo '<div class="view_body">';
while ($row = mysqli_fetch_array($r)) {
echo ' '.$row["doc_name"]. '<br>';
}
echo '</div>';
}
for some bizarre reason I get nothing, if I do a var_dump on $r I get the following:
string(168) " SELECT docs.doc_id,doc_name FROM docs INNER JOIN doc_cat_join ON cats.cat_id = doc_cat_join.cat_id WHERE doc_cat_join.doc_id = '24' "
So it gets the correct category ID I am in.
I am now getting th following output:
Couldn't execute query: Unknown column 'cats.cat_id' in 'on clause'
as per your input and query design, your query should be as per below-
SELECT d.doc_id, d.doc_name
FROM docs AS d
INNER JOIN doc_cat_join AS dc ON dc.doc_id = d.doc_id WHERE dc.cat_id = '24';
Note: If it is not then show what output you require.
$id = $_GET['cat_id'];
$q = sprintf("
SELECT
*
FROM docs
INNER JOIN doc_cat_join
ON docs.doc_id = doc_cat_join.doc_id
INNER JOIN cat
ON doc_cat_join.cat_id = cat.cat_id
WHERE doc_cat_join.cat_id = '$id'
",
mysqli_real_escape_string($dbc, $id) );
print_r ($q);
// FETCH AND PRINT ALL THE RECORDS
echo '<div class="view_body">';
while ($row = mysqli_fetch_array($r)) {
echo ' '.$row["doc_name"]. '<br>';
}
echo '</div>';
}
your query is wrong I think.
Related
I have a database with several tables. I'm able to query IDs from a single table. What I'd like to do is Use those IDs to query another tables IDs, then use these new IDs to query fields from the final table. Here is what I am currently doing:
Here is how I acquire the first set of IDs:
$returnedPost = mysqli_query($con, "SELECT Region_ID FROM Region WHERE RegionName='" . $queryVar . "'");
function resultToArray($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
$rows = resultToArray($returnedPost);
//$rows[x]['Region_ID'];//returns Region_ID 1...n
I'd like to use the IDs in $rows to be able to query a new set of IDs from other tables as follows:
$newTbl = mysqli_query($con, "SELECT Location_ID FROM Location WHERE Region_ID=" . $rows[$x]['Region_ID']);
$rows2 = resultToArray($newTbl);
$finalTbl = mysqli_query($con, "SELECT Field1, Field2 FROM Posts WHERE Location_ID=" . $rows2[$x]['Location_ID']);
Can someone please tell me how I can accomplish this? Thanks.
you can use INNER JOIN in one query to get at this data, maybe something like this
SELECT P.Field1,P.Field2
FROM Region R
INNER JOIN Location L ON R.Region_ID = L.Region_ID
INNER JOIN Posts P ON L.Location_ID = P.Location_ID
WHERE R.RegionName = Your_Region_QueryVar
I have this code, that fetches data from two tables in MySQLi.
It first has to get the title, description, status and project_id from table 1, and then get the name from table 2 using the id from table 1.
Is there a better/faster way to do this? I have about 600 rows in the tables, and it takes about 5 sec to run this query. I will also add that this example is a bit simplified, so please don't comment on the db-structure.
<?php
$results = $connect()->db_connection->query(
'SELECT title, description, status, project_id
FROM table
WHERE created_by ='.$user_id
);
if ($results) {
while ($result = $results->fetch_object()) {
$res = $connect()->db_connection->query(
"SELECT name FROM projects WHERE id = ".$result->project_id
);
if ($res) {
while ($r = $res->fetch_object()) {
echo $r->name;
}
}
echo $result->title;
echo $result->status;
}
}
?>
Use Query:
SELECT title,description,status,project_id
FROM table tb
inner join projects pr on pr.id = tb.project_id
WHERE created_by = $user_id
Try to use JOIN in your query.
You can find examples and description of this command here: http://www.w3schools.com/sql/sql_join.asp
Check out also this infographics:
http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg
You can use JOIN on project_id:
$results = $connect()->db_connection->query('SELECT t.title title,t.description,t.status status,t.project_id, p.name name FROM `table` t JOIN projects p ON p.id= t.project_id WHERE t.created_by ='.$user_id);
if($results){
while($result = $results->fetch_object()){
echo $result->name;
echo $result->title;
echo $result->status;
}
}
tables have aliases here - t for table and p for projects.
Also to make it faster, add index to project_id in table table, if you haven't done it yet:
$connect()->db_connection->query('ALTER TABLE `table` ADD INDEX `product_id`');
I have my table that one of my column shows empty. It has the column of Id, Date, Cust name, Product + Qty, and amount. But only in Product + Qty shows empty even it has data in database.
PHP code
<?php
include('connect.php');
$start = isset($_GET['d1']) ? $_GET['d1'] : '';
$end = isset($_GET['d2']) ? $_GET['d2'] : '';
if(isset($_GET['submit']) && $_GET['submit']=='Search')
{
$result = mysql_query(
"SELECT
t1.qty,
t2.lastname,
t2.firstname,
t2.date,
t3.name,
t2.reservation_id,
t2.payable FROM prodinventory AS t1
INNER JOIN reservation AS t2
ON t1.confirmation=t2.confirmation
INNER JOIN products AS t3
ON t1.room=t3.id
WHERE str_to_date(t2.date, '%d/%m/%Y') BETWEEN
str_to_date('$start', '%d/%m/%Y') AND
str_to_date('$end', '%d/%m/%Y')
GROUP BY t2.confirmation") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo'<tr class="record">';
echo '<td>'.$row['reservation_id'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="left">';
$rrr=$row['confirmation'];
$results = mysql_query("SELECT * FROM prodinventory where confirmation='$rrr'");
while($row1 = mysql_fetch_array($results))
{
$roomid=$row1['room'];
$resulta = mysql_query("SELECT * FROM products where id='$roomid'");
while($rowa = mysql_fetch_array($resulta))
{
echo $rowa['name'].' x';
}
echo ' '.$row1['qty'].'<br>';
}
echo '<td>'.'PHP ' . number_format(floatval($row['payable']));
}
?>
Hmmmm I have deleted my answer but noone tried so...
I think this echo ' '.$row1['qty'].'<br>'; is the row you asked about. And all this looks like a typo. If this is the case:
You have no confirmation in the SELECT clause (it's used only in JOIN and GROUP BY) and it possible your $rrr to be blank. Echo it to be sure there is a value.
Check does your query works and return results. Echo the query string (or take it from the mysql log file) and test it.
You have SELECT *. Is the field name 'qty' correct in a case-sensivity environment? 'Qty' may be different and the query may work but you don't get the result.
i think that's because you have inner join and maybe the intersection tables have no data
try to do left join first if it works
insure that all of tables have data in it
I have two tables which both have a unique PID. I need to know how I should setup the primary/foreign keys so I can access fields from both tables in one SQL statement.
For example: With the following data structure i'd like to echo out the players name and photo but also echo out all their stats via PHP as well. I have successfully done this with just the player Stats, but I do not know how to get access to fields in another table.
Here is my database structure so far:
Players
-PID (Set as Primary Key)
-Name
-Height
-College
-Photo
Stats
-PID
-Touchdowns
-Receptions
Current PHP Code:
$query="
SELECT * FROM Stats
ORDER BY Stats.FantasyPoints DESC";
$res=mysql_query($query);
$num=mysql_numrows($res);
$i=0;
while($i< $num){
$Name = mysql_result($res, $i, "Name");
$FantasyPoints = mysql_result($res, $i, "FantasyPoints");
echo $Name . ': '. $FantasyPoints . "<br />";
$i++;
}
$sql = "
SELECT p.*, s.*
FROM Players AS p
LEFT JOIN Stats AS s ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
You could also use a JOIN rather than a LEFT JOIN which would limit the result to only players who have stats
Edited sql to produce result similar to your own sql.
======================================================
This is how I would go about it...
$query =
"
SELECT s.*, p.*
FROM Stats AS s
LEFT JOIN Players AS p ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
echo "{$row['name']}: {$row['FantasyPoints']}<br />";
}
Is it possible to strip away columns from the response I get in a query where I join 3 tables and need more or less all columns for the query itself so that some columns aren't visible in the response?
This is the query I have:
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_subApp.*,
tbl_tag.*
ISNULL(tbl_userDeviceNOTTag.userDevice_id) AS selected
FROM tbl_subApp2Tag
LEFT JOIN tbl_subApp
ON tbl_subApp.id = tbl_subApp2Tag.subApp_id
AND tbl_subApp.subApp_id = '".$sub."'
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDeviceNOTTag
ON tbl_userDeviceNOTTag.tag_id = tbl_tag.id
AND tbl_userDeviceNOTTag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = tbl_subApp.id
ORDER BY tbl_tag.name ASC ");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
You do not need to include columns in the result table, just because they are referenced elsewhere in the query. Just select the columns that you need.