Sor*_*h n 8 html php mysql mysqli
我想用新数据更新数据库,这样当您将文本放在文本框中然后单击提交按钮时,数据将被发送到具有特定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>
Run Code Online (Sandbox Code Playgroud)
您需要将 URL 放入进行表单处理的操作属性中,而不是函数中:
action="<?php updater($_POST['name'],1); ?>" // not this
action="" // empty for the same page
Run Code Online (Sandbox Code Playgroud)
此外,通常编辑的值会填充输入,并且记录的 ID 会添加到表单的隐藏字段中。如果处理是在同一页面上,最好将操作留空。所以基本形式可能是这样的:
<form action="" method="post">
<input type="text" name="name" value="<?=htmlspecialchars($row['name']) ?>"/><br>
<input type="hidden" name="id" value="<?=htmlspecialchars($row['id']) ?>"/>
<input type="submit" /><br/>
</form>
Run Code Online (Sandbox Code Playgroud)
表格上方,还要添加处理
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$conn = new mysqli( 'localhost' , 'user_name' , '' , 'data_base_name' );
updater($conn, $_POST['name'], $_POST['id']);
}
Run Code Online (Sandbox Code Playgroud)
此外,您必须使用更安全的准备好的查询:
function updater($mysqli, $value, $id) {
$sql = "UPDATE table_name SET name = ? WHERE id= ?";
$update = $mysqli->prepare($sql);
$update->bind_param('si', $value, $id);
$update->execute();
return $update->affected_rows;
}
Run Code Online (Sandbox Code Playgroud)
小智 0
像这样:
<?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>
Run Code Online (Sandbox Code Playgroud)