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

Inserir um Numero Randomico na db


KiiroGAZEROCK

Pergunta

Olá pessoal , sou novo aqui , não sei se estou na area certa , então me desculpe qualquer coisa

enfim , eu estou com uma duvida chata aqui , eu quero gerar um "id" para a DB só que randomica

Cadastra.php

<?php
$conecta = mysql_connect('localhost','','');
mysql_select_db('kyoridb');

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];
$nome = $_POST['nome'];
$id = $_POST['id'];

$query = mysql_query("INSERT INTO usuarios VALUES ('$usuario','$senha','$nome','$id')");

 if($query){
     echo 'Cadastro efetuado com sucesso';
} else{
    echo 'Não foi possivel cadastrar!';
}


?>
Registro.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
body {
    font: 100% Verdana, Arial, Helvetica, sans-serif;
    background: #666666;
    margin: 0; /* it's good practice to zero the margin and padding of the body element to account for differing browser defaults */
    padding: 0;
    text-align: center; /* this centers the container in IE 5* browsers. The text is then set to the left aligned default in the #container selector */
    color: #000000;
}

/* Tips for Elastic layouts 
1. Since the elastic layouts overall sizing is based on the user's default fonts size, they are more unpredictable. Used correctly, they are also more accessible for those that need larger fonts size since the line length remains proportionate.
2. Sizing of divs in this layout are based on the 100% font size in the body element. If you decrease the text size overall by using a font-size: 80% on the body element or the #container, remember that the entire layout will downsize proportionately. You may want to increase the widths of the various divs to compensate for this.
3. If font sizing is changed in differing amounts on each div instead of on the overall design (ie: #sidebar1 is given a 70% font size and #mainContent is given an 85% font size), this will proportionately change each of the divs overall size. You may want to adjust based on your final font sizing.
*/
.oneColElsCtrHdr #container {
    width: 46em;  /* this width will create a container that will fit in an 800px browser window if text is left at browser default font sizes */
    background: #FFFFFF;
    margin: 0 auto; /* the auto margins (in conjunction with a width) center the page */
    border: 1px solid #000000;
    text-align: left; /* this overrides the text-align: center on the body element. */
}
.oneColElsCtrHdr #header { 
    background: #DDDDDD; 
    padding: 0 10px 0 20px;  /* this padding matches the left alignment of the elements in the divs that appear beneath it. If an image is used in the #header instead of text, you may want to remove the padding. */
} 
.oneColElsCtrHdr #header h1 {
    margin: 0; /* zeroing the margin of the last element in the #header div will avoid margin collapse - an unexplainable space between divs. If the div has a border around it, this is not necessary as that also avoids the margin collapse */
    padding: 10px 0; /* using padding instead of margin will allow you to keep the element away from the edges of the div */
}
.oneColElsCtrHdr #mainContent {
    padding: 0 20px; /* remember that padding is the space inside the div box and margin is the space outside the div box */
    background: #FFFFFF;
}
.oneColElsCtrHdr #footer { 
    padding: 0 10px; /* this padding matches the left alignment of the elements in the divs that appear above it. */
    background:#DDDDDD;
} 
.oneColElsCtrHdr #footer p {
    margin: 0; /* zeroing the margins of the first element in the footer will avoid the possibility of margin collapse - a space between divs */
    padding: 10px 0; /* padding on this element will create space, just as the the margin would have, without the margin collapse issue */
}
-->
</style></head>

<body class="oneColElsCtrHdr">

<div id="container">
  <div id="header">
    <h1>Cadastro</h1>
  <!-- end #header --></div>
  <div id="mainContent">
    <h1> </h1>
<hr />
<form id="form1" name="form1" method="post" action="cadastrar.php">
      <p>
        <label>Login:
          <input type="text" name="nome" id="nome" />
        </label>
      </p>
      <p>Nome:
        <label>
          <input type="text" name="senha" id="senha" />
        </label>
      </p>
      <p>Senha:
        <label>
          <input type="password" name="id" id="id" />
        </label>
      </p>
      <p>Confirmar:
        <label>
          <input type="password" name="usuario" id="usuario" />
        </label>
      </p>
      <p> </p>
      <p>
        <input type="submit" name="button" id="button" value="Registrar" />
      </p>
    </form>
    <p> </p>
<p> </p></div>
  <div id="footer">
  <!-- end #footer --></div>
<!-- end #container --></div>
</body>
</html>

Obs: é claro que eu botei a senha e o login da db , só não vou disponibilizar aqui no forum

ps: Eu também estou com um problema no "registo.php" se eu tirar o button "confirmar" ele não registra mais esse "confirmar" edita o id então , eu gostaria de tirar esta caixa e fazer que insira um numero randomico no lugar

mais não sei como pois sou iniciante em PHP e Mysql

Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

KiiroGAZEROCK,

Pode ser feita de no mínimo duas formas, que são:

1) Substitua o código seu input conforme abaixo, ou seja aonde era:

...
<input type="password" name="id" id="id" />
...
Substitua por:
<?php
     $valorInicial = 0;      
     $valorFinal = 10000;

      //Irá gerar um valor randômico de $valorInicial até $valorFinal, incluindo-os
     $valorRand = rand($valorInicial ,$valorFinal);
      
     //Se você não quiser que o usuário veja, comente a próxima linha:
     echo $valorRand;

     echo "<input type='hidden' name='id' id='id' value='$valorRand'/>";
?>
2) Caso você não queira mostrar ao usuário o número aleatório, mude apenas o código seguinte da página Cadastra.php:
...
$id = $_POST['id'];
...
Para:
$valorInicial = 0;      
     $valorFinal = 10000;

      //Irá gerar um valor randômico de $valorInicial até $valorFinal, incluindo-os
     $valorRand = rand($valorInicial ,$valorFinal);
     $id = $valorRand;

Att

Editado por M@RcOs pS09
Link para o comentário
Compartilhar em outros sites

  • 0

é mais seguro você apagar esta parte do seu formulário Registo.php

...
      <p>Senha:
        <label>
          <input type="password" name="id" id="id" />
        </label>
      </p>
...
e no arquivo Cadastra.php apaga o
$id = $_POST['id'];
e no lugar cola assim
$id = rand(0,9999999); //esse "9" que aparece 7x é o tanto de números que pode aparecer randomicamente, pode substituir por qualquer número até 9x

desse jeito fica mais seguro, até por que a pessoa pode abrir o seu código fonte e ver o ID.

Á, você pode colocar os dados do <style> até o </style> em um arquivo CSS, sua página ficaria mais livre e mais leve ..

espero ter ajudado, Abs ;D

Editado por ๖ۣۜωℋĦτکﬠσ̲η ॐ
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,8k
×
×
  • Criar Novo...