I´m trying to insert new users in my database, but everytime i do that, my page only refreshes, instead of headind to the location that it should.The query is the correct one.This is the code that i'm using currently.
<?php
require_once('bd.inc.php');
if (!empty($_POST["submit"])){
if($_POST['submit']==1){}
// verificar se foi submetido o formulário... se sim verificar dados submetidos e enviar info para a base de dados
$nome1 = $_POST['1_nome'];
$nome2 = $_POST['2_nome'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// Cmd Inserir Tabela valores
$comando = "INSERT INTO utilizadores VALUES ('', '$nome1', '$nome2','$email','$username','$password','2')"; // pergunta a enviar à BD
$resultado = mysqli_query($ligacao,$comando) or die ("Operação inválida");
if(mysqli_affected_rows($ligacao))
echo "Operação efectuada";
header('location: backoffice.php?msg=ok');// passamos a variavel msg por get de forma a podermos apresentar a informação de sucesso na página de listar utilizadores
}
?>
<html>
<head>
<meta charset="utf-8">
<link href='css/login.css' rel='stylesheet' type='text/css'>
<title>Backoffice</title>
<meta charset="utf-8">
</head>
<body>
<div id="main" style="max-width:400px;margin-left:450px;margin-top:90px;">
<form name="formulario" action="registar.php" method="post" />
<legend>Registe-se</legend>
<p>Primeiro Nome</p><input type="text" class="form" name="1_nome"/> </br>
<p>Segundo Nome</p><input type="text" name="2_nome"/> </br>
<p>Email</p><input type="email" name="email"/> </br>
<p>Username</p><input type="text" name="username"/> </br>
<p>Password</p><input type="password" name="password"/> </br>
<button type="submit" name="submit" />Registe-se</button>
</div>
</form>
</body>
</html>
The first few problems are some invalid HTML, the </br>
should be <br />
. The <form>
should be closed before the outer div
, etc. But the main problem, and the reason why nothing seems to be happening is because of your submit button:
<button type="submit" name="submit" />Registe-se</button>
The value of $_POST["submit"]
is dependent on your value
attribute, which in your case because there is none it will always be empty. Simply assign a value to your button that isn't 1
<button type="submit" name="submit" value="someValue" />Registe-se</button>
Or rather check for other values such as if $_POST['1_nome']
is empty if you do no wish to assign a value for your submit button. This will allow your code to get to your query.
The reason it only refreshes is that nothing in the body of if (!empty($_POST["submit"]))
gets executed. Because $_POST["submit"]
contains nothing.
Updating the form element to following should suffice.
<button type="submit" name="submit" value='something' />Registe-se</button>