2017-05-25 112 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}')";