如何将数组值或<option>值传递给SQL查询?</option>

时间:2013-04-12 21:41:45

标签: javascript jquery mysql

我在HTML中有一个函数调用,它创建一个包含表列表的新mysql表,并将它们填充到options的元素中。然后我需要填充其中一个选项的另一个select语句“onselect”或“onchange”,但我无法弄清楚如何将所选选项的值传递给sql查询中的变量。我只能通过手动为变量赋值来使其工作。

它可能更容易使用:

var option_user_selection = element.options[ whatever they select ].text

但后来我无法弄清楚如何正确查询循环。

网址:http://people.cs.clemson.edu/~pjnodin/assg/index.php

<body>
<div id="container">
<div id="header">
    <h1>
        SQL Query Builder
    </h1>
</div>
<div id="content-container">
    <div id="data-sets"  title="Click on a Data Set">
        <h3>
            Data Sets
        </h3>
        <form name="myForm">
            <select size="34" style="width: 200px" id="selectBox1" name="dataSets" onChange="optionBlockRecipe2(this.selectedIndex)">

            <?php
                prepareTableList();
                optionBlockRecipe();
            ?>

            </select>
            <input type='hidden' id='myhidden' value=''>
    </div>
    <div id="attributes" title="Click on an Attribute">
        <h3>
            Attributes
        </h3>
            <select size="34" style="width: 200px" id="selectBox2" name="attributes" onClick="alert(this.options[this.options.selectedIndex].value)">
                <?php
                                        optionBlockRecipe2();
                ?>
            </select>
        </form>
    </div>

<?php
function prepareTableList()
{
mysql_query("drop table Table_List");
mysql_query("drop table TheJoins");

$rs = mysql_query("SHOW tables");

mysql_query("create table Table_List(
    TableName char(20) not null,
    TableEnglish char(20),
    PRIMARY KEY(TableName))");

mysql_query("create table TheJoins
    (Table1 char(20) not null
    ,Table2 char(20) not null
    ,TheJoin char(50)
    ,primary key(Table1,Table2))");


for($i = 0; $i < mysql_num_rows( $rs); $i++)
{
    $tmp = mysql_fetch_row( $rs );
    mysql_query("INSERT into Table_List(TableName) VALUES('$tmp[0]')");
    //print("<OPTION value=\"$tmp[0]:$tmp[0]\">$tmp[0]</OPTION>\n");
}
}

function optionBlockRecipe()
{
$rs = mysql_query("SELECT TableName FROM Table_List");
for($i = 0; $i < mysql_num_rows( $rs); $i++)
{
    $tmp = mysql_fetch_row( $rs );
    print("<OPTION value=\"$tmp[0]\" selected=\"selected\">$tmp[0]</OPTION>\n");
}
}
function optionBlockRecipe2()
{
    $temp = Orders;
$rs = mysql_query("DESCRIBE '$temp'");
for($i = 0; $i < mysql_num_rows( $rs); $i++)
{
    $tmp = mysql_fetch_row( $rs );
    print("<OPTION value=\"$tmp[0]:$tmp[1]\" selected=\"selected\">$tmp[0]</OPTION>\n");
}
}
?>

1 个答案:

答案 0 :(得分:0)

您的问题是<option>实际上不是一个元素,而是<select>元素的一个属性。这是一种常见的误解,并使<select>成为最可能(也许是唯一)令人困惑的元素。

他们之所以这样做,是为了让开发人员能够以有组织的方式在列表中添加任意数量的可选选项,包括文本和值。

因此,问题的解决方案很简单:选择新的option时,请使用value元素的<select>,而不是<option>

此外,如果没有AJAX,您将遇到麻烦,因为PHP是服务器端语言而不是客户端语言,因此它不是响应用户事件,而是响应服务器事件,如接收提交形式。