blank spaces and repetition in dropdown box - php

My drop down boxes are working fine using multiples of this code which, I admit, is very rudimentary:
$sql = "SELECT Country FROM engravers order by Country";
$result = mysql_query($sql);
echo "<select name\\='Country'>";
echo "<option value='$_POST'>Country</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Country'] . "'>" . $row['Country'] . "</option>";
}
echo "</select>";
The only problem is that if I have more than one item in the field I get a response for each item, for instance, in my testing database there are two rows with Australia as the country. My dropdown then puts Australia in twice. Later, when there will be about a hundred Australian entries this will be a problem.
Also if there is a blank field I get a blank line in the drop down box. I don't seem to be able to find a solution to this. Is there a better way to write the drop down code that doesn't do this. Unfortunately, as a novice, I am using the simplest code I can understand but the results look just like that. Any help would be gratefully accepted.

Try this query:
SELECT DISTINCT Country
FROM engravers
WHERE Country <> ''
ORDER BY Country
SELECT DISTINCT will take care of multiples - if there are 100 rows with Country = Australia, it will only select one.
WHERE Country <> '' will exclude any rows that have a blank value for Country. You could also include AND Country IS NOT NULL to exclude NULL values as well.
References:
<> (Not equal operator), SELECT DISTINCT ...

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) . ')'

How do I organize all the rows that contain the same FK ID into one row that shows all the items inside those rows

I am trying to make all the data I have in my database organized by SaleID, this is how I have my DB right now. SalesID and ProductID are foreign keys.
TID.......SaleID .........ProductID
....1...............1.......................1
....2...............1.......................4
....3...............1.......................6
....4...............2.......................3
....5...............3.......................1
....6...............3.......................5
....7...............4.......................3
....8...............5.......................3
....9...............5.......................6
I want to make a table that shows all the data organized like this. Not stored into a database just to output this information.
SaleID........Products
.........1.......1,4,6
.........2.......3
.........3.......1,5
.........4.......3
.........5.......3,6
I was trying to do this with multidimensional arrays but every iteration it added a new row and showed exactly the same thing as the first table not being able to modify or add to a past row.
this is the code that I have right now
<?php
mysql_connect('localhost','root','');
mysql_select_db('mydb');
$query="SELECT * FROM prodsales ORDER by salesID ASC";
$result = mysql_query($query);
echo "<table border='1'>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['salesID'] . "</td><td>" . $row['productID'] . "</td></tr>";
}
echo "</table>";
mysql_close();
?>
SELECT SaleID , GROUP_CONCAT( DISTINCT ProductID SEPARATOR ',' ) AS PID FROM prodsales GROUP BY SaleID
Please try this hope it help you to get what you wnat
MySQL has a lovely group_concat function as Abhik posted in a comment. You can use it like this to get the distinct rows you want and to make the other matching rows a comma (or just about anything else) separated list:
select
saleID,
group_concat(productID)
from
prodsales
group by
saleID
order by
saleID
This will return the rows in the format you want and you can simply then output into the table as you are doing.

MYSQL union PHP select into one result column

Ok, there comes a point where staring at SQL is the only option when Googling has you cross eyed. I can't quite get my head around this. What I'm trying to do, is simply use 1 query to search multiple tables at once and return what it finds. I think I need to just do separate queries for this, but wanted to see if there is a better way.
So, for example, there is a categories table, and a users table. If the user searches for "jo", it might find "jobs" in the categories table, but it should also find "joe" in the users table. These are displayed in a <ul><li> html style with fixed lengths. Is there a way with one query? Ideally if "jobs" is found in the category table, that would end the record and the next record would contain "joe" from the users table (provided that the "jo" didn't have multiple categories from the category table.
I've played around with UNION SELECT, but am not sure if it can perform in this fashion or not. I might be able to get a result back from the query, but since the tables have more than 1 field name that is being searched on, I need to be able to return the result based on where it's from.
For example, something like:
SELECT cat_name as result FROM categories WHERE cat_name LIKE '%$name%'
UNION (SELECT firstname as result, lastname as result, username as result WHERE
firstname LIKE '%$name%' OR lastname LIKE '%$name%' OR username LIKE '%$name%' LIMIT 10
<?php echo $row['result']; ?>
Do you think it needs multiple queries?
I don't see that there is any harm in using multiple queries and using echo to display the results separately as to not confuse (so you know where to results are coming from).
Something like this wont burden your script in anyway and makes it easier to read.
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT cat_name FROM categories WHERE cat_name LIKE '%$name%';";
$result = mysqli_query($con,$sql);
echo "<h1>Category Matches</h1>"
echo "<ul>";
while($row = mysqli_fetch_array($result)) {
echo "<li>" . $row['cat_name'] . "</li>";
}
echo "</ul>";
$sql2 = "SELECT * FROM users WHERE first_name LIKE '%$name%';";
$result2 = mysqli_query($con,$sql);
echo "<h1>User Matches</h1>"
echo "<ul>";
while($row = mysqli_fetch_array($result2)) {
echo "<li>" . $row['first_name'] . "</li>";
}
echo "</ul>";
mysqli_close($con);
?>

php mysql while - loop while condition is the same

I have a db that have this kind of structure:
name|color
paul|blue
mary|red
paul|green
joe |yellow
paul|purple
mary|orange
paul|white
etc |etc
What am I trying to achieve here is to list the colors associated with a name, something like this:
paul=blue,green,purple,white
mary=red,orange
joe=yellow
I was checking some examples and found this:
$query="SELECT * FROM mytable order by name";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['color'];
echo "<br />";
}
To be honest I just don't know how to go from this to what an I trying to achieve. How can I create a condition that will list all the color associated with one name and then jump to the next and so on?
You need to use GROUP_CONCAT. Try something like this:
SELECT
name,
GROUP_CONCAT(color) AS color
FROM mytable
GROUP BY name
See this fiddle - updated
If you need to account for duplicates, use GROUP_CONCAT(DISTINCT color). You can also include a custom SEPARATOR, but if you leave it out the default is ,. So in your case you don't need to specify. Also, as can be seen in the documentation linked above, you can, if desired, order the colors in whichever way you see fit - although, note that the default order is ASC, so you don't need to specify that, either, unless you want to change it.
You can do all with the SQL query:
SELECT name, GROUP_CONCAT(DISTINCT color ORDER BY color DESC SEPARATOR ',')
FROM mytable
GROUP BY name;
thank you for pointing me into the right direction. I manage to gather more info and make it work with this:
$query="SELECT name, GROUP_CONCAT(color) FROM mytable GROUP BY name";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['GROUP_CONCAT(color)'] . "</td>";
echo "</tr>";
}
Thank you again :)

PHP - two multiple select dropdowns, passing user selections into a MySQL query

EDIT:
The drop down menus have the following listed in them:
Typing Course
Daily Marketing Course
When using the code below to add selected text form the dropdown into the MySQL statement, only the first word appears ie. 'Typing' and 'Daily', the code looks like this:
SELECT * FROM `acme` WHERE `course` IN('Typing', 'Daily')AND `date` IN('2010-08-27', '2010-08-31')
it should be this:
SELECT * FROM `acme` WHERE `course` IN('Typing Course', 'Daily Marketing Course')AND `date` IN('2010-08-27', '2010-08-31')
Original question below:
Hi all,
Ok, I'll do my best to explain what I would like to do.
I have two dropdown menus set to multiple, the first is Course and the second is Date, here is the code that populates each dropdown:
Course
echo "<select name='course' value='' multiple='multiple'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value=$ntc[course]>$ntc[course]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
Date
echo "<select name='date' value='' multiple='multiple'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($nt=mysqli_fetch_array($queryr)){//Array or records stored in $nt
echo "<option value=$nt[dates]>$nt[dates]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
The main problem I have is passing the results of each dropdown to a MySQL query. For example, if a user select from the Course dropdown 'Typing' AND 'Marketing' - I need the MySQL query to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing'
In addition, I also need to add the second dropdown into the equation, so working on the assumption the user has selected 'Typing' AND 'Marketing', they then select 21-06-2010 from the Date dropdown, so the query then needs to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing' AND date = '21-06-2010' OR date = '18-05-2010'
Clearly, I also need to build in if they select more than one date form the dropdown.
I hope I have explained clearly enough what I'm looking to achieve..any and all help gratefully received. Really struggling to get my head around this one.
Thanks in advance,
Homer.
Use WHERE value IN ('a', 'b'):
SELECT * FROM acme WHERE course IN ('Typing','Marketing') AND date IN ('21-06-2010', '17-09-2010');
In HTML (or the PHP that outputs HTML), add [] to fieldnames:
<select name='course[]' value='' multiple='multiple'>
in PHP:
$courses=$_POST['course'];
$courses=array_map('mysql_real_escape_string', $courses);
$dates=$_POST['date'];
$dates=array_map('mysql_real_escape_string', $dates);
$query = 'SELECT * FROM `acme` WHERE ';
$query.='`course` IN(\''. join("', '", $courses). '\')';
$query.='AND `date` IN(\''. join("', '", $dates). '\')';
OK, first of all, your SQL is a bit off. Rather than WHERE course = 'Typing' OR 'Marketing', you want WHERE course = 'Typing' OR course = 'Marketing'. Alternatively, you could use WHERE course IN ('Typing', 'Marketing'). You can then create this using the array_map function to add the quotes and the join function to link them together:
<?php
...
function escape_and_add_quotes($string) {
return '\'' . mysql_real_escape_string($string) . '\'';
}
...
$sql = 'SELECT * FROM acme WHERE course IN (' . join(',', array_map('escape_and_add_quotes', $courses)) . ')';
?>

Categories