Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá amigos do iMasters,
recentemente fiz um sistema de cadastro para meu site,
fiz o formulario de cadastro normalmente e usei este escript PHP:
<?php require_once('Connections/config.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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 users (nome, email, login, senha) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['nome'], "text"),
GetSQLValueString($_POST['email'], "text"),
GetSQLValueString($_POST['login'], "text"),
GetSQLValueString($_POST['senha'], "text"));
mysql_select_db($database_config, $config);
$Result1 = mysql_query($insertSQL, $config) or die(mysql_error());
$insertGoTo = "ativado.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
?>
E usei uns Spry para confirmar senha e outros, mas a minha dúvida é a seguinte:
eu gostaria que ao usuário tentar cadastrar um login que já existia o servidor retornasse com uma resposta que o login já existe no banco de dados.
OBS: Já coloquei no Banco de dados o login como UNIQUE, Mais a resposta que da não é muito clara.
Caso vocês precisem da formatação em HTML do cadastro ta aqui:
<html xmlns="[http://www.w3.org/1999/xhtml">](http://www.w3.org/1999/xhtml)
<script src="SpryAssets/SpryValidationConfirm.js" type="text/javascript"></script>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationConfirm.css" rel="stylesheet" type="text/css" />
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="cadastroarea">
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
<table align="center" cellpadding="5" cellspacing="2">
<tr valign="baseline">
<td width="41" align="left" nowrap="nowrap">Nome:</td>
<td width="219"><span id="sprytextfield2">
<input type="text" name="nome" class="cadastro" value="" size="32" />
<span class="textfieldRequiredMsg">Digite seu nome!</span></span></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="left">Email:</td>
<td><span id="sprytextfield1">
<input type="text" name="email" class="cadastro" value="" size="32" />
<span class="textfieldRequiredMsg">Digite seu e-mail!</span><span class="textfieldInvalidFormatMsg">E-Mail inválido.</span></span></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="left">Login:</td>
<td><span id="sprytextfield3">
<input type="text" name="login" class="cadastro" value="" size="32" />
<span class="textfieldRequiredMsg">Digite seu login!</span><span class="textfieldMinCharsMsg">Login muito pequeno!</span></span></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="left">Senha:</td>
<td><span id="sprytextfield4">
<input type="password" id="senha" name="senha" class="cadastro" size="32" />
<span class="textfieldRequiredMsg">Digite sua senha.</span><span class="textfieldMinCharsMsg">Senha muito fraca !</span></span></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="left">Re-Senha:</td>
<td><span id="resenha">
<label for="re-senha"></label>
<input name="re-senha" type="password" id="re-senha" size="32" class="cadastro" />
<span class="confirmRequiredMsg">Confirme a senha!</span><span class="confirmInvalidMsg"><br>Por favor, digite as senhas corretamente!</span></span></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"> </td>
<td><input type="submit" class="botao" value=" " /></td>
</tr>
</table>
<p>
<input type="hidden" name="MM_insert" value="form1" />
</p>
</form>
<p> </p>
</div>
<script type="text/javascript">
var spryconfirm1 = new Spry.Widget.ValidationConfirm("resenha", "senha");
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "email");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2");
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none", {minChars:3});
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none", {minChars:3});
</script>
</body>
</html>>
Você diz que a resposta não é muito clara...
Então há uma resposta???
O que vem?? Se for a resposta do banco, você pode verificar o código de erro com um if e enviar a resposta desejada no lugar.
Sim a resposta vem do banco de dados por que eu defini login como UNIQUE
e a resposta quando já existe o login é essa: Duplicate entry 'vitor' for key 'login'
eu gostaria que ficasse uma como: Login "logindapessoa" já esta em uso.
você pode usar mysql_errno() para verificar o código de erro. Se for 1062, o login já existe
lista de códigos de erros do mysql:
http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
>
você pode usar mysql_errno() para verificar o código de erro. Se for 1062, o login já existe
lista de códigos de erros do mysql:
http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
Eu posso usar o código assim?
if (mysql_errno() == 1062)
{
// Login já existente
}
e onde eu posso coloca-lo em qualquer lugar?
>
Eu posso usar o código assim?
if (mysql_errno() == 1062)
{
// Login já existente
}
sim. isso está correto
>
e onde eu posso coloca-lo em qualquer lugar?
após o insert, onde quiser testar o retorno :)
Vlw problema resolvido! :thumbsup:
Não sei colocar [ Resolvido ] no tópico então algum moderador edita ae.
Você diz que a resposta não é muito clara...
Então há uma resposta???
O que vem?? Se for a resposta do banco, você pode verificar o código de erro com um if e enviar a resposta desejada no lugar.