So I have this drop down list in my form which pull "tags" from database as value for drop down options:
<select name="cartags">
<?php $result = mysql_query("SELECT * FROM Products WHERE ID > '0'");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['Tag']; echo "\""; echo ">"; echo $row['Tag']; echo "</option>";
}
?>
</select>
What is my problem? My problem is that I am adding a lot of products into my databas and my code make dropdown list with tags for all this producst even if they have same tag. So what I need is solution how to prevent that same tag appear twice in my drop down.
I am pretty new to PHP and this is my first question here so I really hope that I explained my problem well.
Thanks in advance!
What is the purpose of WHERE ID > '0'? If ID is an auto-increment then it will always be positive. If not, it should be.
Why are you using mysql_fetch_array and then only using the associative keys? You should use mysql_fetch_assoc instead.
Why are you using a new echo every time you want to output a variable? Just concatenate.
Why are you setting the same string in value as the option's text? Without a value, it defaults to the text anyway.
Why are you not using backticks around your column and table names?
Try this instead:
<select name="cartags">
<?php
$result = mysql_query("SELECT DISTINCT `Tag` FROM `Products`");
while(list($tag) = mysql_fetch_row($result)) {
echo "<option>".$tag."</option>";
}
?>
</select>
Try this
<select name="cartags">
<?php $result = mysql_query("SELECT Tag, COUNT(Tag) tg Products WHERE ID > '0' GROUP BY Tag HAVING COUNT(Tag)>0 ORDER BY tg DESC");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['tg']; echo "\""; echo ">"; echo $row['tg']; echo " </option>";
}
?>
</select>
It will also display the top tags that have the most first.
Related
I've set up a php form that registers a project to our database, it has a drop down that populates from our customer/supplier databases.
I've also set up a function to edit these projects, the problem I have is that when I go to my edit page it just displays the customer/supplier name and not in the drop down but a value box - is there a way to have the edit page display the dropdown but also be selected on the original supplier/customer?
Register project page
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo '<select name='client'>';
while($row = mysql_fetch_assoc($result))
{ `
echo '<option value = ''.$row[name].''>'.$row[name].'</option>';
}`
echo '</select>';
?>
Edit page
<input type='text' name='client' value='<?php echo $client; ?>'/>
I tried a few tutorials and code tweaks but kept getting errors. I am aware of my sql injection problem, at the moment this site is internal.
Any help would be appreciated.
thanks
instead of $row[name] you should use $row['name']
$client= "<select name='client'>"; // you had error here also.
while($row = mysql_fetch_assoc($result))
{
$client.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
$client.= '</select>';
now echo $client to get dropdown.no need of constructing separate select tag now.
for selected use like this:
$client1= "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
if($row['name'] == $clientValue){
$client.= "<option selected='selected' value = '".$row['name']."'>'".$row['name'].'</option>';
}else{
$client1.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
}
$client1.= '</select>';
on echo of $client1 you will get selected based on the value $clientValue which you have to pass.
On your edit page:
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo "<select name=\"customer\">";
while($row = mysql_fetch_assoc($result))
{
if ($row['name'] == $client)
{
echo "<option selected value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
else
{
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
}
echo "</select>";
?>
I also suggest that you change the old extension for mysql. I can't see no SQL Injection problem for now, but you should take care of it even if it is internal, because, from different reasons you will forget to sanitize it later. If you are writing it, then write it correctly.
Now for the problem, you are not using the quotes correctly, hence the errors. Do not use the same type of quotes, but change them, like so:
echo '<select name="client">';
Or if you use double quotes for concatenation, use single inside.
In case you have to use the same, escape them with \
For starters, you have a syntax error here:
echo '<select name='client'>';
(There are probably more quoting errors throughout the code, but I digress...)
As for using a drop-down, what you're looking for is the selected attribute. When you're building the page elements to display the form on the "edit" page, presumably you have the values that you're looking to display. When your loop finds an element which matches the value, select it:
while($row = mysql_fetch_assoc($result))
{
if ($knownValue == $row[name]) {
echo '<option selected value = ''.$row["name"].''>'.$row["name"].'</option>';
} else {
echo '<option value = ''.$row["name"].''>'.$row["name"].'</option>';
}
}
I have a database user with a table user(name(varchar(25)),status(int(1)). The values in status will be just 1 or 0. My query is select user.name where status=1 and I just want the result of it to be put in the option tag. I have tried the codes below but it only appears the select box and no options.
<select>
<?php
include'connect.php';
$res = mysql_query("SELECT name from user where status=1 ");
while($row=mysql_fetch_array($res))
{
?>
<option value="<?=$row['name']?>"><?=$row['name']?></option><?php } ?>
</select>
Change your code to this. Note you are doing a while returning $row but your original code was referencing $res['name']. It should all be $row with $row['name'] being set in the <option> now:
<select>
<?php
include 'connect.php';
$res = mysql_query("SELECT name FROM user WHERE status='1'");
while($row = mysql_fetch_array($res)) {
echo '<option value="' . $row['name'] . '">' . $row['name'] . '</option>';
}
?>
</select>
Also note how I am creating a whole PHP block to run through the results. This makes more sense, is easier to read & easier to debug when compared to template formatting where PHP code snippets are mixed in with HTML.
I have the following code:
<?php
$a= 11;
echo "<select name='rabboSelect' style='width:300px;'>";
$sqlQuery="SELECT * FROM writers";
$result=sql($sqlQuery);
while($row = mysql_fetch_array($result))
{
$a .= "<option value='" .$row["ID"]."'>" . $row["name"] . "<option>";
}
echo str_replace("<option></option>", "", $a);;
echo "</select>";
?>
and in the html it's adding <option></option> after each one, even if I try to delete it:
<select name="rabboSelect" style="width:300px;">11<option value="2">הרב מילר</option><option></option><option value="3">משה דוויד</option><option></option><option value="4">קלמי גריינמן</option><option></option><option value="5">בנימין יעבץ</option><option></option><option value="8">אליהו פרץ</option><option></option></select>
How can I stop this from happening?
Firstly, I wonder why you are setting $a=11; - did you maybe mean $a='';?
Next, you are missing a / in the closing option tag. If you tried View Source rather than viewing the DOM, you'd see that rather than the extra options.
$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
$row_num = mysql_num_rows($result);
$rows = mysql_fetch_array($result);
echo "<select name='Branch'>";
for($i=0;$i<=$row_num-1;$i++){
echo "<option value='".$rows[$i]."'>".$rows[$i]."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
I am trying to create a dropdown using the above code for my form. But its not working. There are 3 distinct values in the Branch column but in the dropdown, it shows only one value(the first one) and the next two as blank values.
However when in echo $row_num, its shows 3.
Thats means its fetching the three rows, but then why its not showing in the dropdown list.
If I run the same query in phpmyadmin it shows the correct answer i.r it returns 3 distinct Branch values.
You should do something like this:
$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
echo "<select name='Branch'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
you need to mysql_fetch_array() for each row. That function returns an associative array for one row only. just include it inside your for loop just above your echo statement.
edit: mysql_fetch_array() actually returns an array (by default) that has associative indices and numbered indices. You can continue using it the same way, though.
You need to loop through your query using the following:
$sql = "SELECT DISTINCT Branch FROM student_main";
$result = mysql_query($sql);
echo "<select name='Branch'>";
while($rows = mysql_fetch_array($result)){ // should probably use mysql_fetch_assoc()
echo "<option value='".$rows['Branch']."'>".$rows['Branch']."</option>";
}
echo "</select>";
echo "<input type='submit' Value='submit' />";
echo "</form>";
mysql_fetch_array only returns the current dataset as an array, and moves the internal pointer ahead. You need to repeatedly call mysql_fetch_array to get all results.
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row['Branch']."'>".$row['Branch']."</option>";
}
There is a problem in the loop using a while loop:
while($rows=mysql_fetch_array($result)){
echo "<option value='".$rows[$i]."'>".$rows[$i]."</option>";
}
Try this
What you really need is to learn how to use templates.
But it seems Stackoverflow is definitely not the place where one can learn professional ways of website developing.
get your data first
$select = $array();
$sql = "SELECT DISTINCT Branch FROM student_main";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
while($row = mysql_fetch_array($res)) $select = $row[];
And then use it in the template
<form>
<select name='Branch'>
<? foreach($select as $row): ?>
<option value="<?=htmlspecialchars($row['Branch'])?>">
<?=htmlspecialchars($row['Branch'])?>
</option>
<? endforeach ?>
</select>
<input type='submit' Value='submit' />
</form>
mysql_fetch_array will only return the first row...
see here for full details :)
I'm using this to populate a dropdown:
$result = mysql_query("SELECT user from `users` order by user asc") or die(mysql_error());
echo '<select name="user" class="user">';
while ($row = mysql_fetch_array($result)) {
echo "<option value=".$row['user'].">".$row['user']."</option>";
}
echo '</select>';
But the source is this:
<select name="user" class="user"><option value=joe bloggs>joe bloggs</option>
So when i do this:
var user = $('.user').val();
It only sees "joe" not "joe bloggs"?? Any ideas
$result = mysql_query("SELECT user from `users` order by user asc") or die(mysql_error());
echo '<select name="user" class="user">';
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.htmlspecialchars($row['user']).'">'.htmlspecialchars($row['user']).'</option>';
}
echo '</select>';
Corrected for you :)
Wrap the value in quotes:
echo "<option value=\"".$row['user']."\">".$row['user']."</option>";
Also, make sure to htmlspecialchars() in order to escape possible quotes in the name. E.g.,
$user = htmlspecialchars($row['user']);
printf('<option value="%s">%s</option>', $user, $user);
inside the while loop try:
echo "<option value=\"".$row['user']."\">".$row['user']."</option>";
basically adding a quote to the value inside the option
Use quotes " around attribute values..
your html should look like
<option value="joe bloggs">joe bloggs</option>