0

I'm trying to run a MySQL query depending on what HTML selectbox option is selected and then take the query result and output it to an HTML textbox but to no avail. I'm using the switch statement with the superglobal $_GET. I'm trying to set the value of an HTML textbox using Javascript inside of a PHP block (using echo), but it's not working. The textbox is not being populated (still blank). Could this be because the PHP is running before the textbox is getting initialized or is there something else I'm missing? I know for sure that the DB login info is correct, and the query actually works. The code is below.

<?php
---db login info here---

switch($_GET['string'])
{
    case "another string":
        $query = mysql_query("SELECT field1 FROM table1 WHERE id = '1'");
        $row = mysql_fetch_row($query);
        break;
}

echo "<script type='text/javascript'>";
echo "document.getElementById('textbox').value = '$row[0]'";
echo "</script>";   
?>
4

1 回答 1

2

Couple things:

  1. you can verify that the PHP part is working by checking the "source" of the site when you visit it in the browser (does the <script> part look like you expect?)

  2. Note that the "textbox" must occur earlier in the document than this script, as written

  3. If the element in question is a <textarea>, it does not have a value attribute, and you need to use innerHTML or similar.

  4. There may be bigger-picture issues with how this is being accomplished (is this ajax? all one request? why not simply author the text box with php?)

edit, do it with PHP

If it is your code which authors the <input>, just do it with php in the first place (then you get the added benefit of no js dependency:

switch($_GET['string'])
{
    case "another string":
        $query = mysql_query("SELECT field1 FROM table1 WHERE id = '1'");
        $row = mysql_fetch_row($query);
        $textboxValue = $row[0];
        break;
}
?>
// ...
<input type="text" name="foo" id="textbox" value="<?php echo $textboxValue;?>" />
于 2012-08-29T16:00:39.890 回答