PHP MYSQL query - Strip away columns from response - php

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.

Related

How to get results from mysqli_fetch_assoc with table aliases

I am pretty new to PHP and don't know how to get results from the mysqli_fetch_assoc() function if my select statement has table joins and those joins are handled with table aliases.
The code looks like following:
$sql = 'SELECT T1.update_text, T1.created_at, T2.username, T3.group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
And the PHP Code afterwards:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n",$row["username"],$row["T1.created_at"]);
}
For the "username" row I am not getting an error, but nothing is displayed. For the second one I am getting an Index undefined error. (This is only a snippet of the code)
Change the SQL Query as following,
$sql = 'SELECT T1.update_text as update_text, T1.created_at as created_at, T2.username as username, T3.group_name as group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
then change the PHP code as following,
$result = $mysqli->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = $results->fetch_object())
{
echo $row->username.$row->created_at."<br/>";
}
}

PHP Query MySQL Tables from IDs from other tables

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

Adding the sum of another table column to a query

I am using following query to get all bank accounts from a database table (tb_bank_accounts).
There is another table called tb_movements, and I need to add as new column in the query the SUM of the column 'income' from all records from the table tb_movements where the column 'bank' is equal to the column id_bank_account in the query.
$query="SELECT * from tb_bank_accounts LEFT JOIN tb_currencies ON tb_bank_accounts.currency = tb_currencies.id_currency";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
I guess I should use another LEFT JOIN to do it...
It might be easiest to do using a correlated subquery. Something like this:
SELECT a.*, c.*,
(SELECT SUM(m.income)
FROM movements m
WHERE m.bank_id = a.bank_id
) as income
from tb_bank_accounts a LEFT JOIN
tb_currencies c
ON a.currency = c.id_currency;

Generate html table based on 2x mysql db queries

I'm trying to show stuff queried from two tables, but on one html table. Data is shown for the last 30 days, based on which, an html table is being generated.
Currently I'm stuck using two queries and generating two html tables:
$query1 = mysqli_query( $con, "SELECT date, stuff* " );
while( $record = mysqli_fetch_array( $query1 ) ){
echo '<html table generated based on query>';
}
$query2 = mysqli_query( $con, "SELECT date, other stuff*" );
while( $record = mysqli_fetch_array( $query2 ) ){
echo '<another html table generated based on query2>';
}
Is there a possibility to show both queries on one html table instead?
Note that it gets tricky since we have dates on one table which are not necessarily found in the second table or vice-versa.
Thanks for the support guys. So far I'm stuck at this:
SELECT * FROM user_visit_logs
LEFT JOIN surfer_stats ON user_visit_logs.date = surfer_stats.date
UNION
SELECT * FROM user_visit_logs
RIGHT JOIN surfer_stats ON user_visit_logs.date = surfer_stats.date
The query completes, but the 2nd table fields are all null:
Furthermore, it breaks when I add additional clause like:
WHERE user_id = '{$_SESSION['user_id']}' ORDER BY date DESC LIMIT 30
I think you are after FULL OUTER JOIN concept:
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2)
In which you may use common dates as a shared row.
So the query will get to simple one:
$query = "
SELECT table1.date, stuff
FROM table1
LEFT OUTER JOIN table2 ON table1.date = table2.date
UNION
SELECT table2.date, other_stuff
FROM table1
RIGHT OUTER JOIN table2
ON table1.date = table2.date
";
$result = mysqli_query( $con, $query );
while( $record = mysqli_fetch_array( $result ) ){
echo '<html table generated based on query>';
}
Example
This is an schematic diagram of FULL OUTER JOIN concept:
After running into quite a few bumps with this one, I finally managed to merge 2 columns from each table and also to use where and sort clauses on them with the following query:
( SELECT user_visit_logs.user_id,user_visit_logs.date,unique_hits,non_unique_hits,earned,sites_surfed,earnings FROM user_visit_logs
LEFT OUTER JOIN surfer_stats ON user_visit_logs.user_id = surfer_stats.user_id AND user_visit_logs.date = surfer_stats.date where user_visit_logs.user_id = 23 ORDER BY date DESC LIMIT 30 )
UNION
( SELECT surfer_stats.user_id,surfer_stats.date,unique_hits,non_unique_hits,earned,sites_surfed,earnings FROM user_visit_logs
RIGHT OUTER JOIN surfer_stats ON user_visit_logs.user_id = surfer_stats.user_id AND user_visit_logs.date = surfer_stats.date where user_visit_logs.user_id = 23 LIMIT 30 )
Simplified, "user_visit_logs" and "surfer_stats" were the 2 tables needed to be joined.
Absolutely. Just pop them both into a variable:
$data = '';
$query = mysqli_query($con,"SELECT date, stuff* ");
while($record = mysqli_fetch_array($query)) {
$data.= '<tr><td>--Your Row Data Here--</td></tr>';
}
$query2 = mysqli_query($con,"SELECT date, other stuff*");
while($record = mysqli_fetch_array($query2)) {
$data .= '<tr><td>--Your Row Data Here--</td></tr>';
}
echo "<table>$data</table>";
Instead of using echo in your loop, you're just storing the results in $data. Then, you're echoing it out after all data has been added to it.
As for your second point, it's not a big deal if fields don't exist. If they're null, you'll just have a column that doesn't have data in it.
Here's an example with fake column names:
$data = '';
$query = mysqli_query($con,"SELECT date, stuff* ");
while($record = mysqli_fetch_array($query)) {
$data.= "<tr><td>{$record[id]}</td><td>{$record[first_name]}</td><td>{$record[last_name]}</td></tr>";
}
$query2 = mysqli_query($con,"SELECT date, other stuff*");
while($record = mysqli_fetch_array($query2)) {
$data .= "<tr><td>{$record[id]}</td><td>{$record[first_name]}</td><td>{$record[last_name]}</td></tr>";
}
echo "<table><tr><th>ID</th><th>First Name</th><th>Last Name</th></tr>$data</table>";
I have a feeling I may have misunderstood the need. If so, I apologize. If you can elaborate just a bit more I can change my answer :)

add value to result from mysql query that will be JSON encoded in PHP?

I would like to add a value to each row that I get from my query depending on if a row exist in another table. Is there a smart way to achieve this?
This is the code I have:
$sth = mysql_query("SELECT tbl_subApp2Tag.*, tbl_tag.* FROM tbl_subApp2Tag LEFT JOIN tbl_tag ON tbl_subApp2Tag.tag_id = tbl_tag.id WHERE tbl_subApp2Tag.subApp_id = '".$sub."' ORDER BY tbl_tag.name ASC");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$query = "SELECT * FROM tbl_userDevice2Tag WHERE tag_id='".$r['id']."' AND userDevice_id='".$user."'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
$r['relation'] = true;
$rows[] = $r; //Add 'relation' => true to this row
} else {
$r['relation'] = false;
$rows[] = $r; //Add 'relation' => false to this row
}
}
print json_encode($rows);
Where the //Add ... is, is where I would like to insert the extra value. Any suggestions of how I can do this?
I'm still a beginner in PHP so if there are anything else that I have missed please tell me.
EDIT: Second query was from the wrong table. This is the correct one.
Edited Edited below query to reflect new information because I don't like leaving things half-done.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_subApp2Tag
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = '".$sub."'
ORDER BY tbl_tag.name ASC
");
Though the above feels like the LEFT JOIN on tbl_tag is the wrong way around, but it's hard to tell as you are vague on your eventual aim. For example, if I was to assume the following
Tags will always exist
subApp2Tag will always exist
You want to know if a record in tbl_userDevice2Tag matches the above
Then I would do the following instead. The INNER JOIN means that it won't worry about records in tbl_tag that are not on the requested subApp_id which in turn will limit the other joins.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_tag
INNER JOIN tbl_subApp2Tag
ON tbl_subApp2Tag.tag_id = tbl_tag.id
AND tbl_subApp2Tag.subApp_id = '".$sub."'
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
ORDER BY tbl_tag.name ASC
");
you have to do all the job in a single query.
Why can't you just $r['append'] = "value"; before adding $r to the array?

Categories