我在每次点击下拉列表时创建了一个下拉列表,另一个下拉列表显示在[u] drop1 [/ u]数据库中。以下是相同的代码:
dropdown1.php
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","drop2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a plan:</option>
<option value="1">Dedicated</option>
<option value="2">VPS</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
**drop2.php:**
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM drop WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
/*echo "<table border='1'>
<tr>
<th>plan1</th>
<th>plan2</th>
</tr>";*/
echo "Plan";
echo "<select>";
while($row = mysqli_fetch_array($result))
{
echo "<option>" . $row['plan1'] . "</option>";
echo "<option>" . $row['plan2'] . "</option>";
}
//echo "</table>";
echo "</select>";
mysqli_close($con);
?>
上面的代码非常适合显示正确的下拉列表。 现在我想在另一个数据库中插入第二个下拉列表值。 我完全陷入了困境。 :(
答案 0 :(得分:0)
与插入相同的数据库没有什么不同,除了您将连接如下:
$con2 = mysqli_connect('localhostOrServerName','root','','otherDatabaseName');
然后通过$ con2:
引用第二个数据库$result2 = mysqli_query($con2,$insert_sql);
答案 1 :(得分:0)
你可以这样做:
$needInsert = false;
$query = 'INSERT INTO table(plan1, plan2) VALUES ';
while($row = mysqli_fetch_array($result))
{
$needInsert = true;
$query .= "('{$row['plan1']}','{$row['plan2']}'),";
echo "<option>" . $row['plan1'] . "</option>";
echo "<option>" . $row['plan2'] . "</option>";
}
if ($needInsert)
{
$query = substr($query, 0, -1);
mysqli_select_db($con,"another_db");
mysqli_query($con,$query);
}
我建议您使用PDO扩展而不是mysqli,因为它会在插入数据库之前自动清理数据。否则,您必须像这样清除$row['plan1']
和$row['plan2']
:
mysql_real_escape_string($row['plan1']);
mysql_real_escape_string($row['plan2']);