perform Insert with logged user code,in a table in the database

Asked

Viewed 397 times

-1

Hello I am developing a form, so the user submit the form I would like the database in the table form, be inserted the logged in user code, along with the other information filled in the form, in this table, so that the user code that enters that information is stored in the database, follow my codes below.

index page.html

<!DOCTYPE html>
<html lang="pt" >

<head>
  <meta charset="UTF-8">
  <title>.::COMMEQ UDIA::.</title>
  
  
  <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:600'>

      <link rel="stylesheet" href="src/css/style.css">

  
</head>

<body>

<form action="validacao.php" method="post">
  <div class="login-wrap">
	<div class="login-html">
		<input id="tab-1" type="radio" name="tab" class="sign-in" checked><label for="tab-1" class="tab">Login</label>
		<input id="tab-2" type="radio" name="tab" class="sign-up"><label for="tab-2" class="tab"></label>
		<div class="login-form">
			<div class="sign-in-htm">
				<div class="group">
					<label for="login" class="label">login</label>
					<input id="login" name="login" type="text" class="input">
				</div>
				<div class="group">
					<label for="senha" class="label">Senha</label>
					<input id="senha" name="senha" type="password" class="input" data-type="password">
				</div>
				
				<div class="group">
					<input type="submit" class="button" value="Acessar">
				</div>
				<div class="hr"></div>
				
			</div>

		</div>
	</div>
</div>
 </form> 
  

</body>

</html>

Page validation.php

<?php
    
  // Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
  if (!empty($_POST) AND (empty($_POST['login']) OR empty($_POST['senha']))) {
      header("Location: index.html"); exit;
  }
  
   // Tenta se conectar ao servidor MySQL
 $con = mysqli_connect('localhost', 'root', '') or trigger_error(mysql_error());
  // Tenta se conectar a um banco de dados MySQL
  mysqli_select_db($con,'db_uberlandia') or trigger_error(mysql_error());
    
  $login = mysqli_real_escape_string($con,$_POST['login']);
  $senha = mysqli_real_escape_string($con,$_POST['senha']);
    
	  // Validação do usuário/senha digitados
  $query = mysqli_query($con,"SELECT `CodUsuario`, `NomeUsuario`, `nivel` FROM `usuarios` WHERE (`NomeUsuario` = '".$login."') AND (`senha` = '".$senha."') AND (`ativo` = 1) LIMIT 1");
  
  if (mysqli_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
  } else {
      // Salva os dados encontados na variável $resultado
      $resultado = mysqli_fetch_assoc($query);
  }
  
   // Se a sessão não existir, inicia uma
      if (!isset($_SESSION)) session_start();
    
      // Salva os dados encontrados na sessão
      $_SESSION['UsuarioID'] = $resultado['CodUsuario'];
      $_SESSION['UsuarioNome'] = $resultado['NomeUsuario'];
      $_SESSION['UsuarioNivel'] = $resultado['nivel'];
    
      // Redireciona o visitante
      header("Location: restrito.php"); exit;
    
 ?>
  
  

Page of the form I want to save in the bank

fichaCadastralMusica.html

<?php
	
  // A sessão precisa ser iniciada em cada página diferente
  if (!isset($_SESSION)) session_start();
    
  // Verifica se não há a variável da sessão que identifica o usuário
  if (!isset($_SESSION['UsuarioID'])) {
      // Destrói a sessão por segurança
      session_destroy();
      // Redireciona o visitante de volta pro login
      header("Location: index.php"); exit;
  }
    
  ?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Ficha Cadastral Música - Formoid php contact form</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	
	<link rel="stylesheet" href="fichacadastralmusica_files/formoid1/formoid-solid-blue.css" type="text/css" />
<script type="text/javascript" src="fichacadastralmusica_files/formoid1/jquery.min.js"></script>



	<link rel="stylesheet" href="css/modificadonovo.css">
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
 
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  
  <script>

 function mascara(t, mask){
 var i = t.value.length;
 var saida = mask.substring(1,0);
 var texto = mask.substring(i)
 if (texto.substring(0,1) != saida){
 t.value += texto.substring(0,1);
 }
 }
 </script>

	
	
</head>
<body class="blurBg-false" style="background-color:#fff">



<!-- Start Formoid form-->

<div id="menu"></br>
		<a href="menuMusica.php"><button type='button' class='btn btn-md btn-info'>Voltar</button></a>
			
		
	</div>
<form class="formoid-solid-blue" action="salvarFichaCadastralMusica.php" style="background-color:#e2e2e2;font-size:16px;font-family:'Roboto',Arial,Helvetica,sans-serif;color:#080c10;max-width:480px;min-width:150px" method="POST"><div class="title"><h2>Ficha Cadastral Música</h2></div>
	<div class="element-input"><label class="title"><span class="required">*</span></label><div class="item-cont"><input class="large" type="text" style="text-transform: uppercase;" name="ieqbairro" required="required" placeholder="I.E.Q Bairro:"/><span class="icon-place"></span></div></div>
	<div class="element-input"><label class="title"><span class="required">*</span></label><div class="item-cont"><input class="large" type="text" style="text-transform: uppercase;" name="pastor"  required="required" placeholder="Pastor:"/><span class="icon-place"></span></div></div>
	<div class="element-input"><label class="title"><span class="required">*</span></label><div class="item-cont"><input class="large" type="text" style="text-transform: uppercase;" name="lider" id="lider" required="required" placeholder="Líder:"/><span class="icon-place"></span></div></div>
	<div class="element-radio"><label class="title">Células Ativas:</label>		<div class="column column2"><label><input type="radio" name="celulasativas" value="Sim" /><span>Sim</span></label></div><span class="clearfix"></span>
		<div class="column column2"><label><input type="radio" name="celulasativas" value="Não" /><span>Não</span></label></div><span class="clearfix"></span>
</div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="large" type="number" min="0" max="100" style="text-transform: uppercase;" name="participantescelulas" id="participantescelulas" placeholder="Participantes Celulas Quantidade" value=""/><span class="icon-place"></span></div></div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="large" type="number" min="0" max="100" style="text-transform: uppercase;" name="quantidadereunioes" id="quantidadereunioes" placeholder="Quantidade Reuniões" value=""/><span class="icon-place"></span></div></div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="large" type="number" min="0" max="100" style="text-transform: uppercase;" name="quantidaensamensal" id="quantidaensamensal" placeholder="Quantidade Ensaios Mensais" value=""/><span class="icon-place"></span></div></div>
	<div class="element-multiple"><label class="title"></label><div class="item-cont"><div class="large"><select data-no-selected="SELECIONE...." name="diaensaio" id="diaensaio" multiple="multiple" >

		<option value="Segunda">SEGUNDA</option>
		<option value="Terça">TERÇA</option>
		<option value="Quarta">QUARTA</option>
		<option value="Quinta">QUINTA</option>
		<option value="Sexta">SEXTA</option>
		<option value="Sabado">SABADO</option>
		<option value="Domingo">DOMINGO</option>
		</select><span class="icon-place">
		</span>
		</div>
		</div>
		</div>
	<div class="element-input"><label class="title"></label><div class="item-cont"><input class="medium" type="text" name="horaensaio" id="horaensaio" onkeypress="mascara(this,'--:--')" maxlength="5" placeholder="Hora do Ensaio"/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="large" type="number" min="0" max="100" name="totalmembrosdepartamento" id="totalmembrosdepartamento" placeholder="Total de Membros do departamento:" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="vocal" id="vocal" placeholder="Vocal:(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-separator"><hr><h3 class="section-break-title">Mulheres</h3></div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="mulhercontralto" id="mulhercontralto" placeholder="Contralto(qtas)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="large" type="number" min="0" max="100" name="mezzosoprano" id="mezzosoprano" placeholder="Mezzo-soprano(qtas)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="soprano" id="soprano" placeholder="Soprano(qtas)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-separator"><hr><h3 class="section-break-title">Homens</h3></div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="homensbaixo" id="homensbaixo" placeholder="Baixo(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="baritono" id="baritono" placeholder="Barítono(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="tenor" id="tenor" placeholder="Tenor(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-separator"><hr><h3 class="section-break-title"></h3></div>
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="guitarrista" id="guitarrista" placeholder="Guitarrista:(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="bateristas" id="bateristas" placeholder="Bateristas:(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="tecladistas" id="tecladistas" placeholder="Tecladista:(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="violao" id="violao" placeholder="Violão(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100"name="baixistas" id="baixistas" placeholder="Baixistas(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="meialua" id="meialua" placeholder="Meia Lua(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-number"><label class="title"></label><div class="item-cont"><input class="medium" type="number" min="0" max="100" name="cajon" id="cajon" placeholder="Cajon(qtos)" value=""/><span class="icon-place"></span></div></div>
	
	<div class="element-input"><label class="title"></label><div class="item-cont"><input class="large" type="text" name="outros" id="outros" style="text-transform: uppercase;" placeholder="Outros:"/><span class="icon-place"></span></div></div>
	
	<div class="element-radio"><label class="title">Ministério de carreira:</label>		<div class="column column2"><label><input type="radio" name="ministeriocarreira" value="Sim" /><span>Sim</span></label></div><span class="clearfix"></span>
		<div class="column column2"><label><input type="radio" name="ministeriocarreira" value="Não" /><span>Não</span></label></div><span class="clearfix"></span>
</div>
	<div class="element-textarea"><label class="title"></label><div class="item-cont"><textarea class="medium" style="text-transform: uppercase;" name="nomeministeriocarreira" id="nomeministeriocarreira" cols="20" rows="5" placeholder="Nome dos ministérios de carreira"></textarea><span class="icon-place"></span></div></div>
	
<div class="submit"><input type="submit" value="Salvar"/></div></form>



<!-- Stop Formoid form-->



</body>


<script type="text/javascript" src="fichacadastralmusica_files/formoid1/formoid-solid-blue.js"></script>
</html>

Page that saves the information in the database

saveFichaCadastralMusica.php

<?php

 include ("validacao.php");
 
 
$_SESSION['CodUsuario'];
$ieqbairro = $_POST['ieqbairro'];
$pastor = $_POST['pastor'];
$lider = $_POST['lider'];
$celulaAtivas = $_POST['celulasativas'];
$participantes = $_POST['participantescelulas'];
$quantidadereunioes = $_POST['quantidadereunioes'];
$quantidaensamensal = $_POST['quantidaensamensal'];
$diaensaio = $_POST['diaensaio'];
$horaensaio = $_POST['horaensaio'];
$totalmembrosdepartamento = $_POST['totalmembrosdepartamento'];
$vocal = $_POST['vocal'];
$mulhercontralto = $_POST['mulhercontralto'];
$mezzosoprano = $_POST['mezzosoprano'];
$soprano = $_POST['soprano'];
$homensbaixo = $_POST['homensbaixo'];
$baritono = $_POST['baritono'];
$tenor = $_POST['tenor'];
$guitarra = $_POST['guitarrista'];
$baterista = $_POST['bateristas'];
$tecladista = $_POST['tecladistas'];
$violao = $_POST['violao'];
$baixo = $_POST['baixistas'];
$meialua = $_POST['meialua'];
$cajon = $_POST['cajon'];
$outros = $_POST['outros'];
$ministeriodecarreira = $_POST['ministeriocarreira'];
$descrinomemstcarreira = $_POST['nomeministeriocarreira'];
$connect = mysqli_connect('localhost','root','') or die('Erro ao conectar ao banco de dados');
$db = mysqli_select_db($connect,'db_uberlandia');
mysqli_set_charset($connect,'utf8');
$query = mysqli_query($connect,"INSERT INTO ficha_Cadastral_Musica (CodUsuario,ieqbairro, pastor, lider, celulaAtivas, participantescelulas, quantidadereunioes, quantidaensamensal,diaensaio, horaensaio, totalmenbrosminis, vocalquant, mulhercontralto, mulhermezzosoprano, mulhersoprano, homensbaixo, homensbaritono, homenstenor, guitarraqtd, bateristaqtd, tecladistaqtd, violaoqtd, baixoqtd, meialuaqtd, cajonqtd, outros, ministeriodecarreira, descrinomemstcarreira) VALUES ('$_SESSION['CodUsuario']','$ieqbairro', '$pastor', '$lider', '$celulaAtivas', '$participantes', '$quantidadereunioes', '$quantidaensamensal', '$diaensaio', '$horaensaio', '$totalmembrosdepartamento','$vocal', '$mulhercontralto', '$mezzosoprano','$soprano', '$homensbaixo', '$baritono', '$tenor', '$guitarra', '$baterista', '$tecladista', '$violao', '$baixo', '$meialua', '$cajon', '$outros', '$ministeriodecarreira', '$descrinomemstcarreira')") or die('Erro ao inserir ao banco de dados'); 
 
if($query){
      /* echo"<script language='javascript' type='text/javascript'><div class="alert alert-success"><strong>Success!</strong></div>;window.location.href='menuMusica.php'</script>";*/
	  
	  echo '<div class="alert alert-success">Thank You! I will be in touch</div>';
    }
		  

mysqli_close($connect);
?>

Well ai when I submit the form, is presented this error on the screen, see below:

inserir a descrição da imagem aqui

1 answer

2


The mistake is in this part: ... VALUES ('$_SESSION['CodUsuario']', .... Since the string is being created from double quotes (") PHP uses an additional feature in the reading of the string. This feature is responsible for reading variables, special characters (" n" to skip line) and array/object values so that their contents are interpolated to the text.

Example of literal string

$name = 'Victor';
$text = 'Hi, $name!'; // Note o uso de aspas simples
echo $text; // Saída: Hi, $name!

String example "complex"

$name = 'Victor';
$text = "Hi, $name!"; // Note o uso de aspas duplas
echo $text; // Saída: Hi, Victor!

Another important point is that a string is delimited by quotation marks, i.e., for this case "... VALUES ('$_SESSION['CodUsuario']', ..." we have two texts delimited by single quotes: '$_SESSION[' and ']'. Then, when the string interpreter identifies the possible variable $_SESSION[, will return the error you are receiving. To resolve this issue, follow a few suggestions.

Assign session value to a variable:

$codUsuario = $_SESSION['CodUsuario'];
$query = "... VALUES ('$codUsuario', ...";

Concatenate using the point (.):

$query = "... VALUES ('" . $_SESSION['CodUsuario'] . "', ...";

Or using keys:

$query = "... VALUES ('{$_SESSION['CodUsuario']}', ...";

The use of keys is paramount for arrays and objects and can also be used with variables in specific cases.

$name = 'Victor';
echo "{$name}'s Family"; // Victor's Family
  • Victor thank you so much for your help, the part of Séssion, it seems to me that worked, more now when I will submit the form of the following error. Parse error: syntax error, Unexpected '$ieqbairro' (T_VARIABLE) in C: xampp htdocs commeq salvarFichaCadastralMusica.php on line 7

  • You forgot to add the semicolon after attribution $codUsuario = $_SESSION['UsuarioID'].

  • 1

    Victor worked, thank you very much you saw, congratulations on your knowledge... :)

  • Give me nothing @Ravlog, I’m glad I helped you. Don’t forget to mark as the best response/

  • I’m having another problem now, I wanted after you enter in the database the data that presents a beautiful Alert on the screen, I’m trying to do this way. if($query){ echo "<div class="panel-Success"> <div class="panel-Heading">Data Saved Successfully! </div> </div>"; } , but the error Parse error: syntax error, Unexpected 'panel' (T_STRING), expecting ',' or ';' in C: xampp htdocs commeq salvarFichaCadastralMusica.php on line 41

  • Always be alert with quotation marks and semicolons. In your case, the ideal is to use an IDE that shows the errors you comment on during coding. if($query) { echo '<div class="panel-Success"><div class="panel-Heading">Data Successfully Saved! </div></div>'; }

  • look at the image I put below, kind of what I’m trying to do.

Show 2 more comments

Browser other questions tagged

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