首先让我说,我是新手,我的代码对于那些知道你在做什么的人来说可能是可笑的......
我正在尝试从我的mysql数据库中检索数据,并在匹配的下拉列表中显示信息。我有一部分使用了一些丑陋的基本代码。
$url = $_SERVER["REQUEST_URI"];
$url_path = parse_url($url, PHP_URL_PATH);
$devid = pathinfo($url_path, PATHINFO_BASENAME);
$con = mysqli_connect("localhost","xxxxxx","xxxxxx","xxxxxxxx");
//Run a query
$result = mysqli_query($con,"SELECT type FROM `xxxxx`.`xxxxxx` WHERE device_id='$devid'");
$pulldown1 = '<select name="extension_type">';
while($row = mysqli_fetch_array($result))
{
if($row['type'] == "Unlimited")
{
$pulldown1 .= "<option selected value=\"Unlimited\">Unlimited Extension</option>
<option value=\"Metered\">Metered Extension</option>
<option value=\"Virtual\">Virtual Extension</option>
\n";
}
if($row['type'] == "Metered"){
$pulldown1 .= "<option selected value=\"Metered\">Metered Extension</option>
<option value=\"Unlimited\">Unlimited Extension</option>
<option value=\"Virtual\">Virtual Extension</option>
\n";
}
if($row['type'] == "Virtual"){
$pulldown1 .= "<option selected value=\"Virtual\">Virtual Extension</option>
<option value=\"Unlimited\">Unlimited Extension</option>
<option value=\"Metered\">Metered Extension</option>
\n";
}
}
$pulldown1 .= '</select>';
echo $pulldown1;
mysqli_close($con);
现在我希望能够更改该值并保存相应的值并更新数据库中的该列。这是我被困的地方。有人可以指导我朝正确的方向发展吗?
答案 0 :(得分:3)
当选择框的值发生变化时,您可以使用jQuery发送AJAX帖子请求。反过来,这可以更新您的mysql数据库条目。如果这是你想要的东西让我知道,我将通过代码示例进一步扩展我的答案。
JS代码示例
$("select").change(function () {
// Send ajax request
$.ajax
({
type: "POST",
url: "/change-value.php",
dataType: 'json',
data: { location: $(this).val() },
cache: false,
success: function(data)
{
}
});
});
// PHP change-value.php示例
<?php
// Get the changed value
$value = $_POST['value'];
// Code to update you mysql database entry would go here...
答案 1 :(得分:0)
从php.net上的PHP文档修改:
<?php
if ( !empty($_POST['extension_type']) )
{
// Your MySQL connection code should be at the top of the script.
$query = "UPDATE `xxxxx` SET `extension_type` = ? WHERE `[your_id_field_here]` = ?";
/* Prepared statement, stage 1: prepare */
if ( !($stmt = $mysqli->prepare($query) ) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if ( !$stmt->bind_param("s", $_POST['extension_type']) || !$stmt->bind_param("i", intval($id)) ) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if ( !$stmt->execute() ) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
?>
如@Simon Carlson所述,您还需要考虑SQL注入。如果您有一组扩展类型的集合,则可以通过针对已知有效值检查$ _POST值来改进上述代码。