php - 我怎样才能只使用一个文件而不是 4 个基本相同的 php 文件?
问题描述
我基本上有一个简单的 porgram 来计算单击特定按钮的次数,然后将其发送到 mysql,但是对于每个按钮,我都有不同的表和分隔文件。我想知道是否有任何方法可以将 4 个文件合并为一个,因为它在不同的文件中重复了 4 次相同的事情。这是我的代码:
索引.php
<!DOCTYPE html>
<html>
<head>
<title>Fct</title>
</head>
<body>
<form action="inserir.php" method="post">
<button name="A" type="submit" value="A">Senha A</button>
</form>
<form action="inserir2.php" method="post">
<button name="B" type="submit" value="B">Senha B</button>
</form>
<form action="inserir3.php" method="post">
<button name="C" type="submit" value="C">Senha C</button>
</form>
<form action="inserir4.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
</form>
</body>
</html>
然后插入 mysql 女巫的文件是 inserir.php;
<?php
include 'bdados.php';
$A = $_POST['A'];
$query = "INSERT into `tipo1`(`senhaa`) VALUES ( '$A' )";
mysqli_query($dbconn, $query);
header("location: index.php");
?>
基本上我有 4 个“inserir.php”,我想我可以将这 4 个文件缩小为一个,我只是不知道如何。非常感谢所有帮助:)
解决方案
我感觉您的数据库架构可以改进,但是在不了解您的软件范围的情况下,很难提出建议。看起来您想根据提交的值更改表和列名。有几种不同的方法可以提供帮助。
我将更改您的查询代码以使用准备好的语句(使用PDO,因为这就是我所知道的)
PHP 开关
您将拥有一个文件来处理所有这四个提交。
include 'bdados.php';
$key = array_keys($_POST)[0];
$value = $_POST[$key];
switch ($key){
case 'A':
$column = 'senhaa';
$table = 'tipo1';
break;
case 'B':
$column = 'senhab';
$table = 'tipo2';
break;
case ...
}
//The table name is hard-coded, so that part is not vulnerable to SQL injection
$query = "INSERT into `{$tableName}`(`senhaa`) VALUES ( :newValue )";
$bind = [':newValue'=>$value];
$pdo = new PDO(...);
$statement = $pdo->prepare($query);
$statement->execute($bind);//pass the ':newValue' to be bound
//Without binding, somebody could submit: `'');DELETE FROM senhaa WHERE (TRUE`
// This would close your INSERT statement with an empty value & delete everything from your table
// print_r($statement->errorInfo()); //for debugging if it doesn't work
header("location: index.php");
PHP 数组
这将与上面非常相似,但我们将switch
用一个数组替换该步骤,例如:
$info = [
"A"=>['table'=>'tipo1','column'=>'tipo2']
"B"=> ['table'=>'tipo2'...]
...
];
$table = $info[$key]['table'];
$column = $info[$key]['column'];
隐藏的 HTML 输入
另一种方法可能是通过隐藏的输入字段发送识别信息。虽然您不应该以这种方式发送表名,但您可以发送某种标识符,然后使用上面的数组方法将标识符映射到表信息。
<form action="inserir-todo.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
<input type="hidden" name="identifier" value="the-fourth-table" />
</form>
然后你会这样做:
$key = $_POST['identifier'];
$table = $info[$key]['table'];
...
推荐阅读
- python - 编码错误读取stata文件,read_stata()不接受编码参数python
- c++ - 未显式传递参数时使用 lambda 默认为用户输入
- amazon-s3 - 使用 ansibles s3_sync 或相关模块设置 s3 对象的 Content-Type 和 Content-Encoding 标头
- python - 导入数据时从openpyxl获取楼梯输出
- sed - sed 命令替换文件中的值而不使用查找和替换
- containers - systemd podman 这通常表示先前运行的不干净终止,或服务实现缺陷
- javascript - CSS 样式不适用于 Angular 2+ 指令中由 innerHtml 添加的 Html
- html - Flexbox: How to write a simple responsive side-by-side article layout?
- ios - PDF文件不显示ios
- javascript - 提交时不调用函数