Concatenated list of values in PHP

I am trying to create a concatenated list of client names using only one entry in php, but ultimately the result was not what I expected.

External Part (Interface):

At the beginning, with each name entered in input, the user decides whether to add another name or already display the list with the names already entered by two buttons called with the names add (+) and show (Exibir) respectively. In this way, every button add (+) clicked, the system will print one more new empty entry below the filled one to put one more name, and another name, and another and so on until the user registers all the necessary names and resolves to print a list of all the clients that have been registered in the system by pressing the Enviar button.

Inner part (processing code):

1º) in this system will have a counter called $i that will control the amount of names that will be registered in the list, which will also set the number of rows the column will have;
2º) I created an array called $nome to store all the names that the user register;
3º) I created a new variable called $conteudo that will store all the names that the user is entering concatenately;
4º) a function called get_post_action has as parameter the variable $nome, which will return the names of all existing buttons in the form;
5º) I created a switch-case to define the distinct actions of the buttons add and show;

How would it be possible to create a concatenated list of names with the lines inserted through inputs working in PHP?

<?php
	$i = 0;
	$nome = array("", "", "", "", "", "");
	$conteudo = "";
	function get_post_action($name){
		$params = func_get_args();
		foreach ($params as $name) {
			if (isset($_POST[$name])) {
				return $name;
			}
		}
	}
	switch (get_post_action('add', 'show')) {
		case 'add':
			$i++;
			$nome[$i] = $_POST['nome'];
			$conteudo += "$nome[$i]<br>";
			echo "<input type='text' name='nome'><input type='submit' value='+' name='add'><hr>";
		break;
		case 'show':
			echo "$nome";
		break;
		default:
			$conteudo = "";
		break;
	}	

?>
<form action="teste.php" method="POST">
	<input type="text" name="nome">
	<input type="submit" value="+" name="add"><hr>
	<input type="submit" value="Enviar" name="show">
</form>
Author: pe.Math, 2019-05-14

1 answers

You need to adjust in your code 2 things:

  • arrange a way to persist the form data after submit so you can retrieve it later. I suggest doing this with session.
  • inform PHP that Your "Name" field is an array of names and you can do this by changing the input attribute name from name="nome" to name="nome[]" (in the example below I put in the plural just to get more semantic).

The final code of the file teste.php was left from following Form:

<?php
// inicia a sessao para guardar os nomes
session_start();

/**
 * Quando a pagina carregar
 * Iniciaremos um array vazio na sessão
 * somente caso ele não exista na sessão
 * por exemplo na primeira vez que a página carrega
 */
$_SESSION['nomes'] = $_SESSION['nomes']?: array();

/**
 * Aqui salvaremos os nomes enviados do
 * formulário somente se a ação for para add (+)
 */
if (isset($_POST['acao']) && $_POST['acao'] == '+') {
    $_SESSION['nomes'] = $_POST['nomes'];
}

/**
 * Esta função percorre todos os nomes
 * salvos na sessão e imprime um campo de texto
 * com o nome já preenchido
 */
function print_campos () {
    foreach ($_SESSION['nomes'] as $nome) {
        echo '<input type="text" name="nomes[]" value="'.$nome.'" /><br />';
    }
}

/**
 * Gera a lista concatenada de nomes
 * somente se a ação for "Enviar" (show)
 */
if (isset($_POST['acao']) && $_POST['acao'] == 'Enviar') {
    $lista_concatenada = sprintf('%s', implode('<br />', $_SESSION['nomes']));
    echo $lista_concatenada;
}
?>

<form action="teste.php" method="POST">
    <?php print_campos() ?>
    <input type="text" name="nomes[]" />
    <input type="submit" value="+" name="acao"><hr>
    <input type="submit" value="Enviar" name="acao">
</form>

Reading suggestions

 2
Author: Vinicius.Silva, 2019-05-15 01:35:25