首页 > 解决方案 > 我怎样才能只使用一个文件而不是 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 个文件缩小为一个,我只是不知道如何。非常感谢所有帮助:)

标签: phphtmlmysqlforms

解决方案


我感觉您的数据库架构可以改进,但是在不了解您的软件范围的情况下,很难提出建议。看起来您想根据提交的值更改表和列名。有几种不同的方法可以提供帮助。

我将更改您的查询代码以使用准备好的语句(使用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'];
...

推荐阅读