mysql union and order not working - php

I am trying to combine all the results as i go through the loop
$result = ....;
$finalresult = 0;
while($row = mysql_fetch_assoc($result))
{
$clubID = $row['clubID'];
$finalresult = mysql_query('"'.$finalresult.'" UNION ALL SELECT * FROM events WHERE clubID = "'.$clubID.'"');
}
However, this isn't working. Is there another way to do this?

This should do the trick:
$clubIDs = array();
while($row = mysql_fetch_assoc($result)) {
$clubIDs[] = $row['clubID'];
}
$finalresult = mysql_query("SELECT * FROM events WHERE clubID IN (" . implode(',', $clubIDs) . ")");
It's generating a list of clubIDs from your previous query, and putting them in an array. Then, it's using that array to generate an IN clause, and retrieving all the data in one go.
A couple of caveats - this will fail if there are no valid club IDs, so you'll want to add some error checking.
Secondly, mysql_* is deprecated in PHP 5.5, so you should look at using mysqli_* or PDO instead - they're both much more secure.

Related

PHP mysql query issue when filtering from array and variables

On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.
Effective code that WORKS for filtering (very static, not practical to use obviously) is this:
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\' OR
Joint_1=\'region2\' OR
Joint_1=\'region3\' OR
Joint_1=\'region4\') AND
(Position=\'position1\' OR
Position=\'position2\' OR
Position=\'position3\')";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
} else {
echo "0 results";
}
Below code is attempts at above code, but using arrays, which does NOT work.
$regions =
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\' OR
Joint_1=\'. $regions[1] .\' OR
Joint_1=\'. $regions[2] .\' OR
Joint_1=\'. $regions[3] .\') AND
(Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\')";
Above code provides results of '0 results.'
I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).
$sqlregion = array();
foreach ($_POST['region'] as $reg) {
$sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";
}
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",",
$sqlreg) . ");";
$result=$conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
}
Any help is appreciated! Thanks.
You can construct this query from arrays, you can use the IN clause in mysql to specify multiple OR values
$regions = array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$regions = implode(",", $regions); // Converts array to string with comma as a separator
$position = implode(",", $position);
$sql = "SELECT * FROM `Table_Name` WHERE Joint_1 IN ($regions) AND Position IN ($position)";
echo $sql;
This gives you a query like this
SELECT * FROM Table_Name WHERE Joint_1 IN (region1,region2,region3,region4) AND Position IN (position1,position2,position3)
add in your own LIMIT GROUP BY or ORDER BY parameters to suit your needs

How to use two different records from database?

I'm running a query to get results from the database. The results are then saved in an array. I want to know how can I use those results from array to get further results from the database in a single query. Or I'll have to use multiple queries?
$query2="SELECT officeName FROM office
WHERE parentOfficeID='$parent'";
$result2=mysqli_query($connect,$query2);
if(mysqli_num_rows($result2) != 0)
{
$results= array();
while ($row2 = mysqli_fetch_assoc($result2))
{
$results[]=$row2['officeName'];
}
}
The $results array saves the results. I want to use the officeName values individually. Is there any way I use single query? Or I'll have to process each value?
Hi If I understand your question then first you want to fetch some officeName and store them in array and then want to fetch some other info based on that officeName . You can use this one
<?php
$db = new mysqli('localhost','root','','databasename');
$result = mysqli_query($db,"SELECT officeName FROM office WHERE parentOfficeID='$parent'") or die(mysqli_error($db));
$officeName = array();
while($row = mysqli_fetch_assoc($result)){
$officeName[] = $row['officeName'];//store your office name in an array
}
$officeName= join("', '", $officeName);//The join() function returns a string from the elements of an array. It is an alias of the implode() function.
$sql = "SELECT * FROM office WHERE officeName IN ('$officeName')";// query with IN condition
$result1 = mysqli_query($db,$sql) or die(mysqli_error($db));
while($row1 = mysqli_fetch_assoc($result1)){
echo "<pre>";print_r($row1);
}
for more info more about join(). Please read http://www.w3schools.com/php/func_string_join.asp
for mysqli IN condition please read http://www.mysqltutorial.org/sql-in.aspx
To add to #Nyranith, you could also swap out your while statement and use
mysqli_fetch_all($result2, MYSQLI_ASSOC);
Which will return your values as an associative array without the need for you to loop through and build the array yourself.
It's been a really long time since I used mysqli, could need tweaking but here goes.
Here's a better way to go about the process itself:
Assume you have tables: Office and Staff and for some reason, you are binding the office to staff by the office name (bad juju)
$parent = 1;
$query2="SELECT o.officeName, s.name
FROM office AS o
INNER JOIN staff AS s ON o.officeName = s.officeName
WHERE o.parentOfficeID=?";
$stmt = $connect->prepare($query2);
$query = $stmt->bindParam($parent);
$exec = $stmt->execute();
$results2 = mysqli_fetch_all($exec, MYSQLI_ASSOC);
Now, do something with your result array
foreach($results2 as $key => $value) {
//loop through your results an do another query with them. Just like you queried the database to get these results.
}

Mysql return joined table as sub-array

I'm using my mysqli query as JSON output.
This is my query:
$sql = "SELECT p.*,comments.*,COUNT(comments.id) AS numComments FROM people AS p
LEFT JOIN comments ON comments.people_id = p.id
WHERE p.name LIKE '%".$data."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
} else {
echo 0;
}
What I want to do, is to group all the person comments and place it under the person data. for example:
The desired output is that I will be able to access the comments not directly from the query, but from the person itself.
for example:
echo $person['comment'][0]['content']
Currently, I access it like any of the query data..
echo $person['content']
JSON OUTPUT:
As you can see, the person data and the comment data is mixed in the same array. I want the comments to have an array of their own.
Any ideas?
Edit: Seem like I have problem with the query. it returns only the first comment!
You need so-called eager loading for this task. It will involve two queries, but it will be way better than one.
You have to select your people first, then get people ids and query comments table for the comments. And finally you will have to combine the two arrays together.
I will use PDO as it will take 5 times less code to write, thanks to some neat PDO features.
$stmt = $conn->prepare("SELECT * FROM people WHERE name LIKE ?");
$stmt->execute(["%$data%"]);
$people = $stmt->fetchAll(PDO::FETCH_UNIQUE);
$ids = array_keys($people);
$in = str_repeat('?,', count($ids) - 1) . '?';
$stmt = $db->prepare("SELECT people_id, * FROM comments WHERE people_id IN ($in)");
$stmt->execute($ids);
$comments = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach($people as $id=>$row)
{
$row['comments'] = $comments[$id];
$people[$id] = $row;
}

Is there a more efficient way to express this query

I have a query for my mysql database but I just want to know if there is more of a simpler way of achieving something, here is my code:
$sql="SELECT value
FROM drivers
WHERE drivers_id = '$driver1' OR drivers_id = '$driver2' OR drivers_id = '$driver3'";
$result = mysql_query($sql);
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
${'value'.$i} = $row['value'];
$i++;
}
This is how I want my code as it is shorter, but the problem I am having is that I need to know that where the $driver1 variable is found in the database the data retrieved for that is placed inside the value1 variable, and the retrieved information for $driver2 is placed inside $value2. However it grabs the data from the database in the order that it comes across the matches. I don't want to have to write 3 different queries for this because I am sure it can be done in one.
$sql="SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3')";
$result=mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
${'value_for_'.$row['drivers_id']}=$row['value'];
}
Boom.
Though personally, instead of on-the-fly variables, I'd use an array w/ the id's as keys:
...
$resultArray = array();
while($row = mysql_fetch_assoc($result)) {
$resultArray[$row['drivers_id']]=$row['value'];
}
If you want to change the order of the results, you can add an order by clause to the query:
$sql = "SELECT drivers_id, value FROM drivers WHERE drivers_id IN ('$driver1','$driver2','$driver3') ORDER BY drivers_id";
...

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories