Trying to search one table using the value from another table - php

I am trying to program a lookup tool in PHP with SQL database.
$sql="SELECT
ID,
switch,
vlan,
circuit_id
FROM vlan
WHERE switch
LIKE LOWER('%" . $name . "%') OR vlan='" . $name ."'
ORDER BY vlan";
then further down I have this to put the results into variables:
while($row=mysql_fetch_array($result)){
$switch =$row['switch'];
$vlan=$row['vlan'];
$circuitID=$row['circuit_id'];
$ID=$row['ID'];
What I am wanting to do is take the switch reply and use that to do another query on a different table named router and return that information.
I have been searching for a few days and all of my searches ended up here but didnt seem to quite fit. I apreciate any help you can give.
UPDATE
With some great answers I finally got this to work. Here is how I did it. Thanks for the help.
while($row=mysql_fetch_assoc($result)){
$switch =$row['switch'];
$vlan=$row['vlan'];
$circuitID=$row['circuit_id'];
$ID=$row['ID'];
$sql2 = "SELECT IPAddress FROM router
WHERE switch LIKE '%".$switch."%'
LIMIT 1";
$result2 = mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$IPAddress = $row2['IPAddress'];
Probably real ugly to the more experienced but it works. Thanks again.

It would be highly inefficient to run a secondary lookup query in a loop.
What you want is a simple JOIN between your two tables based on the switch field. What this will do is bring the linked rows in your router table alongside the rows in your vlan table where values in the switch column match up:
$sql = '
SELECT a.id, a.switch, a.vlan, a.circuit_id, b.ipaddress
FROM vlan a
JOIN router b ON a.switch = b.switch
WHERE a.switch LIKE "%' . strtolower($name) . '%" OR vlan = "' . $name . '"
ORDER BY a.vlan';
Then in your same fetch loop, you'll be able to access the linked values from your router table without having to run extra database calls:
while($row=mysql_fetch_array($result)){
$switch =$row['switch'];
$vlan=$row['vlan'];
$circuitID=$row['circuit_id'];
$ID=$row['ID'];
$ipaddress = $row['ipaddress'];
}

How many results do you expect? If there's more than one result, you might need to point which row exactly you want to take. Since it's fetch_array, your $row['switch'] or $switch value is still an array. var_dump it for keys and use the key, i.e.
SELECT `col` FROM `router` WHERE `switch` = '$switch[1]'

Related

SELECT DISTINCT with so many conditions

I am trying to create a Filter feature for my website. I was told to use SELECT DISTICT to accomplish this. Below is what I currently have, it retrieves all the distinct values in column STATE and displays them as check boxes so the user can check those states he wants displayed on a table on the page.
$sql = "SELECT DISTINCT state FROM allproperties";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<input type='checkbox' name='state' value='" . $row[0] . "'>" . $row[0] . "<br>";
}
My problem is this Filter feature will have a lot of conditions, not just selecting which States to show, there'd be selections for which county, member age, member contributions etch. When the user clicks DISPLAY button to display the filtered results, I do not know how to build an SQL query for this. If only a few condition I can simply use "SELECT * WHERE (...) AND (....)" but if I use this for a filter feature, there'd be a lot of conditions like:
WHERE (state='CA' OR state='NV' OR state='WA' ..... so on and so fort)
Is there a way to do it like WHERE state=OR('CA','NV','WA') so I don't have so many state=?
Also, does anyone have any sample queries for filter feature? The Filter feature is like when you do a search in a music website for songs based on genre or something. I apologize in advance for the confusing question, I can't find the right question to ask for this.
Yes, you can use IN() :
WHERE state IN('CA','NV','WA'...)
Its not only doing the same effect, it's a lot more efficient then severals ORs , always try to avoid unnecessary OR's .
As mentioned by #Kulvar , you can use implode() to make it work with PHP , something like:
'WHERE state IN(' . implode(',', $states) . ')'

PHP - Getting num_rows of different ID's without writing new statements?

Basically, I'm coding a site that has many different categories and I want to display the amount of rows specific to that ID.
So for example, I have as the query:
$query= "SELECT job_sec FROM jobs WHERE job_sec = ?";
mysqli_num_rows($query);
I need to know how I can count the rows of an ID then echo the rows counted.
I'd like the results to display:
Web Design: 2,001 jobs
Logo Design: 5,120 Jobs
The job_sec column just uses a numerical value, would it be easier to have a text value then count the rows relating to the text value and echo them?
I have a feeling I need to use an array however I need the most efficient method.
Any help would be much appreciated!
Assuming job_sec is the category and I think you are looking for "group by":
$sql= "SELECT job_sec, count(*) AS c FROM jobs GROUP BY job_sec";
$r = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($r)) {
echo $row['job_sec'] . ': ' . $row['c'] . ' Jobs ';
}
(didn't test and not sure if the mysqli syntax is correct)

Select SUM() as a variable in a for Loop

I'm trying to generate XML from database and need to gather a specific amount of data based on the average from a column. This can vary from anywhere between 5 to 30 queries for the $numItems variable.
I need to execute a for loop and assign the column name in the SUM($variable) but I'm not getting any data (but no errors either).
Here is my code:
for ($t = 1; $t <= $numItems; $t++){
$query = mysql_fetch_assoc(mysql_query("SELECT SUM(column'".$t."') AS value_sum FROM scoring WHERE ID='" . $userID . "' AND name ='" . $name . "'"));
$q = $query['value_sum'] / $totalUsers;
echo "<output".$t.">" . $q . "</output".$t.">\n";
}
The problem is assigning the SUM(column1) variable name for the column I'm getting data from, when I write the queries individually it works, but assigning the variable within the statement is causing a problem. Can any one give me any pointers?
Thanks in advance.
It looks like you might have extra single quotes in your query. I think it should be:
"SELECT SUM(column".$t.")..."
You should also consider doing a single select. Doing multiple database calls inside a for loop will be a huge performance problem. You could write a single select like this:
"SELECT SUM(column1), SUM(column2), SUM(column3),..."
Looks like bad escaping/concatenation around the column name...
"SELECT SUM(column{$t}) AS value_sum FROM scoring WHERE ID='{$userID}' AND name ='{$name}'"
Is that what you want?
Also use PDO!

Displaying info from MySQL - from 2 different tables... Argh! Noob in trouble

I am trying to pull some stats from a gameserver database, and return them in a table.
I have managed to do the first bit - pulling 10 results, displaying in a table in html, HOWEVER... the next bit has me stumped... I for each player I want to get some info from another table...
Here is what I have so far... excuse the messy code, I am just learning!
// adding ALL info from the first 10 tables 'profile' based on humanity, ascending, to the variable 'profile_info'
$profile_info = mysql_query("SELECT * FROM profile ORDER BY humanity desc LIMIT 10");
while($row = mysql_fetch_array($profile_info))
{
// Below I add the players unique ID into the variable $unique, to be used later for pulling their survival time from the 2nd table, which is called 'survivor'
$unique = $row['unique_id'];
echo "<tr>";
echo "<td class=\"c1\">" . $row['name'] . "</td>";
echo "<td class=\"c2\">" . $row['humanity'] . "</td>";
echo "<td class=\"c3\">" . $row['total_survivor_kills'] . "</td>";
echo "<td class=\"c4\">" . $row['total_bandit_kills'] . "</td>";
echo "<td class=\"c5\">" . $row['total_zombie_kills'] . "</td>";
echo "<td class=\"c6\">" . $unique . "</td>";
//In the line below, I try to get data from the 2nd table (called survivor), checking for the unique_id for the player (extracted from the first table, called 'profile') which is common across both tables and which have a 0 in the field 'is_dead'
$result = mysql_query("SELECT * FROM `survivor` WHERE `unique_id` ='.$unique' AND `is_dead` = 0") or die(mysql_error());
echo $unique;
if (mysql_num_rows($result)) {
$survivors_survival_time = mysql_fetch_assoc($result);
echo "<td class=\"c7\">" . $survivors_survival_time['survival_time'] . "</td>";
}
I hope that, even though the code above is probably rubbish, you can see what I am trying to do?
Most of it works fine, it is just that the part where I try to get the info for a player from the second table, based on their unique_id from their row in the first table, it doesn't work :(
Any ideas, or is the above so bad I should just give up?
I believe you have a typo in your query that pulls info for each individual player here:
mysql_query("SELECT * FROM `survivor` WHERE `unique_id` ='.$unique' AND `is_dead` = 0")
Specifically, the unique_id = '.$unique' part, where there is an extra . in the value field.
Try removing it to get the following:
$result = mysql_query("SELECT * FROM `survivor` WHERE `unique_id`='$unique' AND `is_dead` = 0") or die(mysql_error());
This, of course, is under the assumption that you don't prepend a . to each of your unique_id values in the survivor table.
Side-note (not answer specific):
If you were to update your code to use the MySQLi or PDO libraries opposed to the deprecated mysql_ functions, you would have the ability to use prepared statements. Using these would prevent minor errors like the one noted above as well as provide more-secure code too.
Nest your while loops or read about mysql LEFT JOIN and update your query.
I do not know about MySQL, because I've always used MSSQL, but here's how I would write it in PHP and mssql:
'SELECT * FROM survivor WHERE unique_id="'.$unique.'" AND is_dead = 0'
Try it and let me know ;)
You can combine those queries using a join:
SELECT
*
FROM
profile AS p
LEFT JOIN
survivor AS s ON p.unique_id = s.unique_id
WHERE
s.is_dead = 0
ORDER BY
humanity DESC
LIMIT
10
Then simply loop the results. Using LEFT JOIN gives you all the results from profile and any matches in survivor. If you change that to JOIN (i.e. drop the LEFT) it will give you only rows where a match exists in profile AND survivor.
A couple of suggestions:
Explicitly state which columns you want, i.e. "SELECT name, humanity, survival_time, etc..." instead of SELECT *.
Use a query method that allows you to use prepared statements, such as PDO.
Use single quotes instead of doubles so that you don't have to escape all the doubles in your HTML output. Anyone else who reads your code will thank you for that!

Subquery in PHP

Let's put an easy example with two tables:
USERS (Id, Name, City)
PLAYERS (Id_Player, Number, Team)
And I have to do a query with a subselect in a loop, where the subselect is always the same, so I would like to divide it into two queries and put the subselect outside the loop.
I explain. What works but it is not optimize:
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')");
}
What I would like to do but it doesn't work:
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Thanks!
Something like this should work.
<?
$sql = "SELECT Team from PLAYERS
JOIN USERS on (Id_player=Id)
WHERE Number BETWEEN $minID AND $maxID
AND City='London'
GROUP BY Team";
$results=mysql_query($sql) or die(mysql_error());
// $results contain all the teams from London
// Use like normal..
echo "<ul>\n";
while($team = mysql_fetch_array($results)){
echo "\t<li>{$team['Team']}</li>\n";
}
echo "</ul>";
Placing SQL quires in loops can be very slow and take up a lot of resources, have a look at using JOIN in you SQL. It's not that difficult and once you've got the hang of it you can write some really fast powerful SQL.
Here is a good tutorial worth having a look at about the different types of JOINs:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
SELECT PLAYERS.*, USERS.City FROM PLAYERS, USERS WHERE USERS.City='London' AND PLAYERS.Number = $i
Not the best way to do it; maybe a LEFT JOIN, but it should work. Might have the syntax wrong though.
James
EDIT
WARNING: This is not the most ideal solution. Please give me a more specific query and I can sort out a join query for you.
Taking your comment into account, let's take a look at another example. This will use PHP to make a list we can use with the MySQL IN keyword.
First, make your query:
$res1 = mysql_query("SELECT Id from USERS where City='London'");
Then, loop through your query and put each Id field one after another in a comma seperated list:
$player_ids = "";
while($row = mysql_fetch_array($res1))
{
$player_ids .= $row['Id'] . ",";
}
$player_ids = rtrim($player_ids, ",");
You should now have a list of IDs like this:
12, 14, 6, 4, 3, 15, ...
Now to put it into your second query:
for($i = 0; $i<something; $i++)
{
$res2 = mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN $player_ids");
}
The example given here can be improved for it's specific purpose, however I'm trying to keep it as open as possible.
If you want to make a list of strings, not IDs or other numbers, modify the first while loop, replacing the line inside it with
$player_ids .= "'" . $row['Id'] . "',";
If you could give me your actual query you use, I can come up with something better; as I said above, this is a more generic way of doing things, not necessarily the best.
Running query in a loop is not a great idea. Much better would be to get whole table, and then iterate through table in loop.
So query would be something like that:
"SELECT Team from PLAYERS WHERE Number BETWEEN($id, $something)
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')"
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Would work, but mysql_query() returns a RESULT HANDLE. It does not return the id value. Any select query, no matter how many, or few, rows it returns, returns a result statement, not a value. You first have to fetch the row using one of the mysql_fetch...() calls, which returns that row, from which you can then extract the id value. so...
$stmt = mysql_query("select ID ...");
if ($stmt === FALSE) {
die(msyql_error());
}
if ($stmt->num_rows > 0) {
$ids = array();
while($row = mysql_fetch_assoc($stmt)) {
$ids[] = $row['id']
}
$ids = implode(',', $ids)
$stmt = mysql_query("select TEAM from ... where Id_player IN ($ids)");
.... more fetching/processing here ...
}

Categories