用户注册到网站。管理员将登录并查看用户列表。
我试图为管理员提供一个选择复选框并通过下拉提交更改用户状态的选项。当我尝试下面的代码时,我可以选择“Y/N/A”,点击提交
按钮后,它显示消息“添加成功”,但它不是更新数据库中的值。
表名:tbl_users,列:userStatus [enum],值:Y、N、A
表单
<form method="post" action="ajax1.php">
<select name="userStatus">
<option value="N">N</option>
<option value="Y">Y</option>
<option value="A">A</option>
</select>
<button type="submit" name="submit" >Submit</button>
</form>
ajax1.php
if(isset($_POST["submit"]))
{
$userStatus=$_POST["userStatus"];
$conn = new Database();
$stmt = $conn->dbConnection()->prepare("INSERT INTO tbl_users (userStatus) VALUES ('$userStatus')");
echo " Added Successfully ";
}
显示用户复选框、ID、姓名、电子邮件的代码:
$stmt = $user_home->runQuery("SELECT * FROM tbl_users");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
$status = array('Y'=>'Verified','N'=>'Not verified' , 'A'=>'Approved');
echo "<table>";
echo "<tr>
<td></td>
<td>id</td>
<td>name</td>
<td>email</td>
</tr>";
while($data = $stmt->fetch())
{
echo "<tr>
<td> <input type='checkbox' > </td>
<td>" . $data['userID'] . "</td>
<td>" . $data['name'] . "</td>
<td>" . $data['email'] . "</td>
</tr>";
}
echo "</table>";
在发布问题之前我研究并尝试了很多,在一些链接中我看到我们需要使用Javascript,但在其他一些链接中,他们提到我们只能使用php来实现。 我对编码很陌生,请帮助我
编辑
按照以下答案后,我将代码更新为 $stmt = $conn->dbConnection()->prepare('UPDATE tbl_users SET userStatus = ? WHERE userID = ?');
最佳答案
<form method="post" action="ajax1.php">
<select name="userStatus" id="userStatus" onchange="UpdateStatus();">
<option value="N">N</option>
<option value="Y">Y</option>
<option value="A">A</option>
</select>
<button type="submit" name="submit" >Submit</button>
</form>
<script>
function UpdateStatus(){
var staus=$('#userStatus :selected').val();
allCheckedBoxes="";
$("input[id^='checkBoxId']:visible:checked").each(function(){ // this is to get checked checkbox vaues to update which user to update
allCheckedBoxes=allCheckedBoxes+$(this).val()+","; // comaseparated valuse
});
var dataString="allCheckedBoxes="+allCheckedBoxes+"&staus="+staus;
$.post("aupdate_status.php",'allCheckedBoxes='+allCheckedBoxes'&staus='+staus,function(result,status,xhr)
{
if( status.toLowerCase()=="error".toLowerCase() )
{ alert("An Error Occurred.."); }
else
{
alert(result);
}
})
.fail(function(){ alert("something went wrong. Please try again") });
}
</script>
update_status.php
<?php
$staus=$_POST['staus'];
$allCheckedBoxes=$_POST['allCheckedBoxes'];
$ArrallCheckedBoxes=explode(",",$allCheckedBoxes);
foreach($ArrallCheckedBoxes as $tempBoxes){
$sqlQueryToUpdate=" UPDATE tbl_users SET userStatus = '".$staus."' WHERE userID = '".$tempBoxes."' ;";
$conn = new Database();
$stmt = $conn->dbConnection()->prepare($sqlQueryToUpdate);
echo " ok success";
}
?>
Please try this . This is working in my case. This will work you too. Don't forget add jquery in your coding.
关于javascript - 使用表单提交更新数据库中选定的下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40542673/