I have SQL command, which will get list of all categories that I used within my table. (writting categories into "categories" column)
SQL:
SELECT category FROM `events` GROUP BY category
In PHPMYADMIN the result is correct, so I know my SQL command is good (each of them is separate category):
MEDICINE
SLEEP
SPORT
I need to get these values and wrap each of them in OPTION html tag, so I can use them on page in SELECTION element. I have a strong feeling I need to use PHP to generate something like this. Can you please inspire me with code?
Here is my attempt to at least see the list via PHP, but I have failed
<html>
<body>
<table>
<?php
include_once('config.php');
$query1 = mysqli_query($query, "SELECT category FROM `events` GROUP BY category");
//nefunkcny
echo $query1;
?>
</table>
</body>
</html>
This is what I would like to get, the ability to select the category on page
I would appreciate any advice on this, thank you in advance.
If further clarification needed, please ask.
Have a nice day.
use a while to fetch the results.
// Perform queries
$query1 = mysqli_query($query, "SELECT category FROM `events` GROUP BY category");
if (mysqli_num_rows($query1) > 0) {
// output data of each row
echo "<select>";
while($row = mysqli_fetch_assoc($query1)) {
echo '<option value="' .$row['category'] . '">' . $row['category'] . "</option>";
}
echo "</select>";
}
Related
Im coding in PHP and SQL after finishing the web site I realize that in my bloucles, that take their info from the database I have repeated values,
Here you will understand better:
I have this code:
<?php
$mysqli = new mysqli("localhost","root","","motorsportgeneral") or die("1");
$sql = "SELECT * FROM cars ";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<?php echo $row['model'] ?>
<?php
}
}
?>
If in the rows of my table I have 2 repeated values the server will show this:
Hello1
Hello2
Hello1
Hello2
How can I eliminate this repeated values in my list, with out touching the table?
Thanks, I hope you can help me!
SELECT DISTINCT model FROM cars
SELECT DISTINCT model FROM cars
That should do the trick, if I understand correctly.
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);
?>
i have a table called home which has column_id as a column ,i want to display dropdown items say(column 1 and/or column2 and/or column3) which are not there in home table.
Execute a query like below,
$query = select * from home where description ='' or description is NULL;
Process the above query and send the items to your HTML page to display in the dropdown. I hope this is what you expect.
as i understand your problem try this
<select>
<?php
$res = mysql_query("SELECT column_id FROM `your_table` WHERE description='' ") or die(mysql_error());
while($row = mysql_fetch_assoc($res))
{
echo '<option value="'.$row['column_id'].'">Column-'.$row['column_id'].'</option>';
}
?>
</select>
I hope my title says something about what I am trying to do, I'll try to describe it a bit better:
I have a database with two tables, one named "movies" and another one named "directors".
Its a small movie database where we are supposed to be able to display all the movies, their title, year and producer.
In the table "directors" I have a field "id" and in my "movies" table i have a field named "producer" with the matching id. I want the while loop to loop thru all the movies in the "movies" table (working fine) and if i choose to print the "id" from "movies" its correct.
But now i want the loop to display the "title" and "year" from the "movies" table, and go to the "directors" table and get the name for the matching "id".
I'm new to both PHP and mysql queries and my code does this correctly for the first movie, but the rest have their "producer" field empty as for now.
(Right now I'm just trying to display the surname to see that it works).
FYI this is for a school project.
Code:
<?php
$sql = "SELECT * FROM movies ORDER BY title ASC";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"title");
$year=mysql_result($result,$i,"year");
$producer=mysql_result($result,$i,"producer");
$id=mysql_result($result,$i,"id");
$sqldir = "SELECT * FROM directors WHERE id='$producer'";
$result1 = mysql_query($sqldir);
$row1 = mysql_fetch_assoc($result1);
$iddir = $row['id'];
$producertext = mysql_result($result1,$i,"surname");
?>
<b>Title:</b> <?php echo $title ?>
<br/><b>Year:</b> <?php echo $year ?>
<br/><b>Director:</b> <?php echo $producertext ?>
<br/>
</form> <HR>
<?php
$i++;
}
?>
Assuming that every movie has a single director then you can just create a joined query
SELECT movies.title as title, movies.year as `year` producer.surname as surname
FROM movies, producer where movies.producter = producer.id ORDER BY title ASC
You can then just walk the result set and the surname will be in the result arrays.
Here should be a complete solution assuming the query works as expected
<?php
$sql = "SELECT movies.title as title, movies.year as `year` producer.surname as surname FROM movies, producer where movies.producter = producer.id ORDER BY title ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)): ?>
<b>Title:</b> <?php echo $row['title'] ?>
<br/><b>Year:</b> <?php echo $row['year'] ?>
<br/><b>Director:</b> <?php echo $row['surname]; ?>
<?php
endwhile;
?>
You are using wrong function
$num=mysql_numrows($result);
you should use
$num=mysql_num_rows($result);
You're accessing the producer information as:
$producertext = mysql_result($result1,$i,"surname");
However, $i is the index from the main SQL loop; so on the second run through, you'll be looking for the surname from the second line of your producer result set, which won't necessarily be there. So only the first producer is showing up.
Some other things you might want to look at - you can use PDO or mysqli to access data - they're more secure that mysql, which is in the process of being deprecated. You're also using mysql_fetch_assoc at the moment, but you don't seem to be using the resulting array for anything. It's a lot more common to go through a result set with something like:
while ($row = myssql_fetch_assoc($result)) {
....
}
Which loads the next row into an associative array for you to use, and stops when you run out of rows.
Also, have you considered what your code should do if there's more than one producer for a film? You might want to add a loop for that query, too.
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)) . ')';
?>