2017-05-25 113 views
-1

我想取消设置$ _POST超全局,因此在用户提交表单之前它没有任何值。我使用了unset($ _ POST ['name']),并且在此之后它不会使用表单输入进行更新。 我已经测试没有取消$ _POST,它的工作恰到好处。我也尝试过使用$ _POST ='something',但表单并没有替换这个值。

<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>to-do-list</title> 
    <!-importanto css-> 
    <link href="bootstrap.css" rel="stylesheet"> 
    <link href="style.css" rel="stylesheet"> 
</head> 
<body> 

    <?php 
    error_reporting(E_ALL & ~E_NOTICE); 
    ?> 

    <!--formulario com ação post--> 
    <form action="" method="post"> 
     <h1> To Do List </h1> 
     <table class="table"> 

      <tr> 
       <?php 
        unset ($_POST['nome']); 
       ?> 

       <td><input type="text" name="nome" placeholder="nome" ></input></td> 
       <td><button>enviar</button></td> 


      </tr> 

      <?php 


       //definindo a variavel que vai capturar o input do usuário->  
       $name=($_POST['nome']); 


       //definindo a query que será passada ao mySQL 
       $query = "insert into itens (item) values ('{$name}')"; 

       //definindo qual banco de dados deve ser acessado 
       $conexao = mysqli_connect('localhost', 'root', '', 'to-do-list'); 

       //verifica se existe algo no $_POST, se tiver, mostra na tela e envia ao servidor. 



       if (isset($_POST['nome'])) { 
        mysqli_query($conexao, $query); 
       } 
       else { 

       }   


       //busca as tarefas listadas no banco e transforma em um array 
       function listaTarefas($conexao) { 

       $tarefas = array(); 
       $resultado = mysqli_query($conexao, "select * from 
         itens"); 


       //loop para colocar as tarefas antigas dentro do array $tarefas 
       while($item = mysqli_fetch_assoc($resultado)) { 
       array_push($tarefas, $item); 
       } 

       return $tarefas;  
       } 

       //para cada item do array tarefas, imprime o valor da coluna "item" na tabela 
       $tarefas = listaTarefas($conexao); 
       foreach($tarefas as $item) : 
      ?> 

      <tr> 
       <td><?= $item['item'] ?></td> 
       <td>   
      </tr> 

      <?php 
       endforeach 
      ?> 


     </table> 

    </form> 

</body> 
+0

你并不需要这样做。除非他们提交表单,否则变量中没有任何内容。 – Barmar

+0

是正确的,但如果用户没有在输入字段上写下任何内容并按下按钮,它会向我的SQL银行发送一个空字符串,而我不需要它。 –

+0

你的问题说“在用户提交表单之前”。这与用户在填写输入字段时提交表单不一样。 – Barmar

回答

0

所有的PHP代码都在页面发送给用户之前运行。当用户提交表单时,所有的PHP代码都会再次运行。

对于“回传”,其中相同的URL /页面都创建表单并处理它,您需要在页面上分割代码。

$show_form = true; 
$errors = false; 
$error_list = ""; 
if (isset($_POST['submit'])) { 
    ... code to validate and process the form ... 
    ... if success, render the results page set $show_form = false .... 
} 

if ($show_form) 
{ 
    ... render the form page, including $error_list if validation failed 
} 

而且,这条线是很危险的 - 谷歌“SQL注入”和“小鲍比表”`

$query = "insert into itens (item) values ('{$name}')";