Reputation: 53
I run a query that returns the first word only from a particular field, this field has multiple words separated by spaces. The result of the query will be value of the select box I create dynamically. I have 3 select boxes that are created dynamically depending on the selection of the other.
Problem is query returns entire sentence and that is displayed in select box as well. I tried running the query solely in database and it seems to give me the correct result.
Here is the code snippet. How can i resolve it??
<?php
//**************************************
// First selection results //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_1") {
drop_1($_GET['drop_var']);
}
function drop_1($drop_var)
{
$result = mysql_query("SELECT DISTINCT SUBSTRING_INDEX(`h_name` ,' ', 1 ) AS name FROM hypermarket_em") or die(mysql_error());
echo '<select name="drop_2" id="drop_2"><option value=" " disabled="disabled" selected="selected">Select City</option>
<option value="ALL" >ALL</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['name'].'">'.$drop_2['name'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_2').hide();
$('#drop_2').change(function(){
$(this).parent().parent().find('.drop2').val($(this).val());
$('#wait_2').show();
$('#result_2').hide();
$.get(\"func.php\", {
func: \"drop_2\",
drop_var: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout(\"finishAjax_tier_three('result_2', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
?>
Any ideas much appreciated. Thanks.
Upvotes: 0
Views: 1028
Reputation: 12433
You are setting the substring
SUBSTRING_INDEX(`h_name` ,' ', 1 ) AS name
but still referencing the full original string $drop_2['h_name']
. Try changing to -
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['name'].'">'.$drop_2['name'].'</option>';
}
EDIT--
If you are correctly using the alias name
in $drop_2['name']
, I am not sure why it is still echoing the full string. You could use the explode()
that I first answered with, as a fail safe
while($drop_2 = mysql_fetch_array( $result ))
{
$firstWord = explode(' ',trim($drop_2['name']));
echo '<option value="'.$firstWord[0].'">'.$firstWord[0].'</option>';
}
Upvotes: 1