如何编写php填充下拉列表并使用ajax插入到mysql数据库中

时间:2013-09-09 17:44:15

标签: mysql ajax

我正在创建购物网站,在管理部分我刚刚完成类别以及mysql数据库表名称类别中的类别列表。

我编写了一个ajax代码,允许我填充使用哪个类别的下拉列表,这里有很好的代码

<script type="text/javascript">
function changeContent(str)
{
if (str=="")
  {
    // if blank, we'll set our innerHTML to be blank.
    document.getElementById("content").innerHTML="";
    return;
  } 
if (window.XMLHttpRequest)
    {   // code for IE7+, Firefox, Chrome, Opera, Safari
        // create a new XML http Request that will go to our generator webpage.
        xmlhttp=new XMLHttpRequest();
    }
else
    {   // code for IE6, IE5
        // create an activeX object
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    // on state change
    xmlhttp.onreadystatechange=function()
    {
    // if we get a good response from the webpage, display the output
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("content").innerHTML=xmlhttp.responseText;
    }
  }
 // use our XML HTTP Request object to send a get to our content php. 


}
</script>

这是我从mysql填充的选择下拉列表菜单的php代码..

        <?php

$link = mysql_connect('localhost', 'root', '3250');
mysql_select_db('shopping', $link);

$sql = "select * FROM category";

$result = mysql_query($sql);

echo "<select name=\"muppetname\" onchange=\"changeContent(this.value)\">";

while ($ary = mysql_fetch_array($result)){

    echo "<option value=\"" . $ary['category']  . "\">" . $ary ['category']  . "</option>";
}

echo "</select>";


?>

<?php


mysql_close($link);

?>

我的下一步是创建插入到mysql中的一个类别,该类别从名为category的下拉列表中选择,然后插入另一个表名称“add_product”和列名“category”

<?php
$categories_list = "";
$sql = mysql_query("SELECT * FROM category ORDER BY category ASC");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
    while($row = mysql_fetch_array($sql)){ 
             $id = $row["id"];
             $category_name = $row["category"];
             $categories_list .= "Category ID #:  &nbsp; $id - <strong>$category_name</strong> &nbsp; &nbsp; &nbsp; &nbsp;  <br /><br />";
    }
} else {
    $categories_list = "You have no categories listed in your database yet";
}
?> 

有没有人可以帮我修改插入mysql语句的代码?

0 个答案:

没有答案