Concatenated list of values in PHP

Asked

Viewed 129 times

1

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

External Part (Interface):

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

Internal part (processing code):

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

How it would be possible to create a concatenated list of names with the lines inserted through inputs running 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>

1 answer

2


You need to adjust in your code 2 things:

  • Fix a way to persist the form data after Submit to be able to retrieve it later. I suggest doing this with session.
  • Let PHP know that your "name" field is an array of names and you can do this by changing the attribution name of the input of name="nome" for name="nome[]" (in the example below I put in plural only to get more semantic).

The final code of the file teste.php was as follows:

<?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

  • It worked right @Vinicius.Silva. Thanks for the guidance! ;-) Now I’ll just make some adjustments to add one more button to remove row by row, for when every time I go to update the script in PHP there are those lines exaggerations. Gratitude! -D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.