Ir para conteúdo
Fórum Script Brasil
  • 0

Formulário De Cadastramento


Hoopkins

Pergunta

Seguinte pessoal fiz um formulário simples pra cadstrar usuários.. aí fuçando lá no phpMyAdmin consegui estabelecer pro campo e-mail que ele seja unico.. mais aí quando vou cadastrar um e-mail igual aparece assim em uma página em branco:

Duplicate entry 'email@email.com' for key 2

Tem como aparecer na mesma página apenas algum aviso de e-mail inválido ?

Agradeço a atenção!

Link para o comentário
Compartilhar em outros sites

8 respostass a esta questão

Posts Recomendados

  • 0

Bom, vamos supor que você tem um formulário que manda o campo email por post.

Aí, lá no seu database, você tem uma tabela chamada usuários e um campo chamado email também, o qual não pode ser igual, né? =)

Bom, eu vou colocar a consulta aqui para você adaptar no seu script, aí você altera o nome dos campos e tal.

$email = $_POST["email"];
$consulta0 = mysql_query("SELECT * FROM `usuarios` WHERE `email` = '$email'");
if ($resultado0 = mysql_fetch_array($consulta0)){
    echo "Este e-mail já esta cadastrado!";
    }
else {
    // Aqui vai o resto do seu código, aquela parte que vai cadastrar o e-mail do seu usuário
    }

Qualquer dúvida, posta seu código aí que damos um jeito nele!

Abraços!

Link para o comentário
Compartilhar em outros sites

  • 0

Opa! Obrigado!

To tentando encaixar aqui.. mas por enquanto não consegui o meu php é assim:

<?php require_once('../Connections/ConSimpleNews.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
    
  $logoutGoTo = "login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO usuarios (usu_nome, usu_email, usu_senha, usu_data) VALUES (%s, %s, md5(%s), %s)",
                       GetSQLValueString($_POST['usu_nome'], "text"),
                       GetSQLValueString($_POST['usu_email'], "text"),
                       GetSQLValueString($_POST['usu_senha'], "text"),
                       GetSQLValueString($_POST['usu_data'], "date"));

  mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
  $Result1 = mysql_query($insertSQL, $ConSimpleNews) or die(mysql_error());

  $insertGoTo = "cadastrar_admins.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsUsuariosCadastrados = "SELECT *, date_format(usu_data, '%d/%m/%Y') as usu_data FROM usuarios ORDER BY usu_data ASC";
$rsUsuariosCadastrados = mysql_query($query_rsUsuariosCadastrados, $ConSimpleNews) or die(mysql_error());
$row_rsUsuariosCadastrados = mysql_fetch_assoc($rsUsuariosCadastrados);
$totalRows_rsUsuariosCadastrados = mysql_num_rows($rsUsuariosCadastrados);

$colname_rsNomeDoUser = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_rsNomeDoUser = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']);
}
mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsNomeDoUser = sprintf("SELECT usu_nome FROM usuarios WHERE usu_email = '%s'", $colname_rsNomeDoUser);
$rsNomeDoUser = mysql_query($query_rsNomeDoUser, $ConSimpleNews) or die(mysql_error());
$row_rsNomeDoUser = mysql_fetch_assoc($rsNomeDoUser);
$totalRows_rsNomeDoUser = mysql_num_rows($rsNomeDoUser);
?>

Link para o comentário
Compartilhar em outros sites

  • 0

Você pode tentar desta maneira:

<?php require_once('../Connections/ConSimpleNews.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
    
  $logoutGoTo = "login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
  // For security, start by assuming the visitor is NOT authorized.
  $isValid = False;

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
  // Therefore, we know that a user is NOT logged in if that Session variable is blank.
  if (!empty($UserName)) {
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
    // Parse the strings into arrays.
    $arrUsers = Explode(",", $strUsers);
    $arrGroups = Explode(",", $strGroups);
    if (in_array($UserName, $arrUsers)) {
      $isValid = true;
    }
    // Or, you may restrict access to only certain users based on their username.
    if (in_array($UserGroup, $arrGroups)) {
      $isValid = true;
    }
    if (($strUsers == "") && true) {
      $isValid = true;
    }
  }
  return $isValid;
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {  
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo);
  exit;
}
?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $email = $_POST['usu_email'];
  mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
  $consulta = mysql_query("SELECT * FROM usuarios WHERE usu_email = $email");
  if ($resultado = mysql_fetch_array($consulta)){
  $insertSQL = sprintf("INSERT INTO usuarios (usu_nome, usu_email, usu_senha, usu_data) VALUES (%s, %s, md5(%s), %s)",
                       GetSQLValueString($_POST['usu_nome'], "text"),
                       GetSQLValueString($_POST['usu_email'], "text"),
                       GetSQLValueString($_POST['usu_senha'], "text"),
                       GetSQLValueString($_POST['usu_data'], "date"));

  mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
  $Result1 = mysql_query($insertSQL, $ConSimpleNews) or die(mysql_error());

  $insertGoTo = "cadastrar_admins.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
else {
    echo "Este e-mail já exise";
    }
}

mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsUsuariosCadastrados = "SELECT *, date_format(usu_data, '%d/%m/%Y') as usu_data FROM usuarios ORDER BY usu_data ASC";
$rsUsuariosCadastrados = mysql_query($query_rsUsuariosCadastrados, $ConSimpleNews) or die(mysql_error());
$row_rsUsuariosCadastrados = mysql_fetch_assoc($rsUsuariosCadastrados);
$totalRows_rsUsuariosCadastrados = mysql_num_rows($rsUsuariosCadastrados);

$colname_rsNomeDoUser = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_rsNomeDoUser = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']);
}
mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsNomeDoUser = sprintf("SELECT usu_nome FROM usuarios WHERE usu_email = '%s'", $colname_rsNomeDoUser);
$rsNomeDoUser = mysql_query($query_rsNomeDoUser, $ConSimpleNews) or die(mysql_error());
$row_rsNomeDoUser = mysql_fetch_assoc($rsNomeDoUser);
$totalRows_rsNomeDoUser = mysql_num_rows($rsNomeDoUser);
?>
Logicamente, você poderá modificar o:
else {
    echo "Este e-mail já exise";
    }

Por qualquer outra coisa que você quiser.

Pode inclusive chamar uma função ou redirecionar a página atual.

Abraços!

Editado por Lvcifer!
Link para o comentário
Compartilhar em outros sites

  • 0

Porque eu digitei o seu código errado!

Me desculpe, ontem eu conferí, conferí outra vez, mas nem reparei!

Bom, segue o código corrigido...

<?php require_once('../Connections/ConSimpleNews.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
    
  $logoutGoTo = "login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
  // For security, start by assuming the visitor is NOT authorized.
  $isValid = False;

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
  // Therefore, we know that a user is NOT logged in if that Session variable is blank.
  if (!empty($UserName)) {
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
    // Parse the strings into arrays.
    $arrUsers = Explode(",", $strUsers);
    $arrGroups = Explode(",", $strGroups);
    if (in_array($UserName, $arrUsers)) {
      $isValid = true;
    }
    // Or, you may restrict access to only certain users based on their username.
    if (in_array($UserGroup, $arrGroups)) {
      $isValid = true;
    }
    if (($strUsers == "") && true) {
      $isValid = true;
    }
  }
  return $isValid;
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {  
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo);
  exit;
}
?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $email = $_POST['usu_email'];
  mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
  $consulta = mysql_query("SELECT * FROM usuarios WHERE usu_email = $email");
  if ($resultado = mysql_fetch_array($consulta)){
      echo "Este e-mail já exise";
    }
else {
  $insertSQL = sprintf("INSERT INTO usuarios (usu_nome, usu_email, usu_senha, usu_data) VALUES (%s, %s, md5(%s), %s)",
                       GetSQLValueString($_POST['usu_nome'], "text"),
                       GetSQLValueString($_POST['usu_email'], "text"),
                       GetSQLValueString($_POST['usu_senha'], "text"),
                       GetSQLValueString($_POST['usu_data'], "date"));

  mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
  $Result1 = mysql_query($insertSQL, $ConSimpleNews) or die(mysql_error());

  $insertGoTo = "cadastrar_admins.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
    }
}

mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsUsuariosCadastrados = "SELECT *, date_format(usu_data, '%d/%m/%Y') as usu_data FROM usuarios ORDER BY usu_data ASC";
$rsUsuariosCadastrados = mysql_query($query_rsUsuariosCadastrados, $ConSimpleNews) or die(mysql_error());
$row_rsUsuariosCadastrados = mysql_fetch_assoc($rsUsuariosCadastrados);
$totalRows_rsUsuariosCadastrados = mysql_num_rows($rsUsuariosCadastrados);

$colname_rsNomeDoUser = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_rsNomeDoUser = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']);
}
mysql_select_db($database_ConSimpleNews, $ConSimpleNews);
$query_rsNomeDoUser = sprintf("SELECT usu_nome FROM usuarios WHERE usu_email = '%s'", $colname_rsNomeDoUser);
$rsNomeDoUser = mysql_query($query_rsNomeDoUser, $ConSimpleNews) or die(mysql_error());
$row_rsNomeDoUser = mysql_fetch_assoc($rsNomeDoUser);
$totalRows_rsNomeDoUser = mysql_num_rows($rsNomeDoUser);
?>

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,7k
×
×
  • Criar Novo...