我想用新数据更新数据库,这样当您将文本放在文本框中然后单击提交按钮时,数据将被发送到具有特定ID的数据库。我要发送的只是亮度,代码如下。当我写这样的东西,然后运行它时,我收到403错误:禁止访问。我该如何解决这个问题?
<?php
function updater($value,$id){
// Create connection
$conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_name SET name=$value WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
//$conn->close();
}
?>
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<form action="<?php updater($_POST['name'],1); ?>" method="post" style="height:50px;width:50px;">
<input type="text" name="name" /><br><br>
<input type="submit" /><br/>
</form>
</body>
</html>
答案 0 :(得分:4)
您需要将URL放在执行表单处理的action属性中,而不是函数:
action="<?php updater($_POST['name'],1); ?>" // not this
action="<?php echo $_SERVER['PHP_SELF']; ?>" // path to this page
如果这是在同一页面上,您可以省略它或使用$_SERVER['PHP_SELF']
,然后抓住表单提交。在该过程中,然后调用您的自定义函数。
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$value = $_POST['name'];
$id = 1;
updater($value, $id);
}
一个简单的解决方法就是引用其中的字符串:
$sql = "UPDATE table_name SET name='$value' WHERE id=$id";
但这对SQL注入是开放的,另一种做更安全的查询的方法是准备它们:
function updater($value,$id) {
// Create connection
$conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_name SET name = ? WHERE id= ?";
$update = $conn->prepare($sql);
$update->bind_param('si', $value, $id);
$update->execute();
if ($update->affected_rows > 0) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
答案 1 :(得分:2)
<?php
function updater($value,$id){
// Create connection
$conn = new mysqli( 'localhost' , 'user_name' , 'pass' ,'data_base_name' );
$value =mysqli_real_escape_string($conn,$value);
$id =mysqli_real_escape_string($conn,$id);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table_name SET name='{$value}' WHERE id='{$id}'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
if(isset($_POST['name'])){
updater($_POST['name'],$_POST['id'])
}
?>
<!DOCTYPE html>
<html>
<header>
</header>
<body>
<form action="" method="post" style="height:50px;width:50px;">
<input type="hidden" name="id" value="1" />
<input type="text" name="name" /><br><br>
<input type="submit" /><br/>
</form>
</body>
</html>