Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this code:

<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
    $nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
</script>

<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>

it works exactly how i need it to but i am wondering if it is possible to display the column name "name" from the database in the select options as well as the code?

for example rather than just

123

to have it like this

123 - name

share|improve this question
Please consider using PDO instead of mysql_* type functions, as they have been deprecated as of version 5.5 – Julian H. Lam Mar 21 at 0:17
i will do - this is just what i have at the moment - any ideas on it? – charliejsford Mar 21 at 0:19
1  
I don't know what the Js function addOptions does but it seems like if you augment this line $nominalcodes[] = $result['code'] . ' - ' . $result['name']; you will be closer to your desired result. – Mark Fox Mar 21 at 0:25
This could also work. addOptions could do a .split() on the string ` - ` to retrieve both values. – Julian H. Lam Mar 21 at 0:29

1 Answer

You'll want to rigidly separate your php and your js. The way the code is written will work as is, but is very brittle, and can break catastrophically, leading to action-at-a-distance style bugs.

For example, if your database schema were refactored to remove the code column, then your javascript would be rendered broken, with a cause that nobody would suspect.


That said, if you'd like to also display the data in the name column in the select options, you'll have to pass that data into $nominalcodes as well. Right now, it contains an indexed array of data (perhaps an int or a string), but you'll want to change that so it contains an indexed array of arrays.

So, before:

$nominalcodes = array(1,3,5,78,3,2,234);

and after:

$nominalcodes = array(
    array(1, 'foobar'),
    array(3, 'larry'),
    array(5, 'bob'),
    ...
);

At this point, you'll have to refactor your javascript addOptions function so that it can properly parse an array of arrays, instead of an array of single values.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.