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

como inserir varios registros em sequencia


ferspaik

Pergunta

pessoal, estou com um problema, preciso criar uma pagina, para inserir numeros em serie, por exemplo: 10500, 10501, 10502, 10503 etc....... e assim por diante, mas como preciso inserir mais de 300 sempre, queria fazer uma pagina q eu colocasse o primeiro valor, e ele automaticamente gravasse as mesmas informações em serie, repetindo apenas o campo nome, por exemplo: CARTÃO RECARGA TIM DE 10 REAIS, número de série 10500789, dae ele gravasse sei lá, 50 registros identicos no banco de dados, alterando apenas o ultimo numero do cartao, ficando assim na tabela do BD:

Banco de Dados ------ tabela: num_seriais ----- Campo1: serial_id -------- Campo2: serial_nome -------Campo3: serial_numero

campo1=1 campo2=Cartão de R$10 campo3=10500789

campo1=2 campo2=Cartão de R$10 campo3=10500790

campo1=3 campo2=Cartão de R$10 campo3=10500791

campo1=4 campo2=Cartão de R$10 campo3=10500792

campo1=5 campo2=Cartão de R$10 campo3=10500793

campo1=6 campo2=Cartão de R$10 campo3=10500794

etc.......

sou novo na linguagem, se alguém poder me ajudar, eu agradeço muiiiiito...

Link para o comentário
Compartilhar em outros sites

6 respostass a esta questão

Posts Recomendados

  • 0

Pessoal, consegui o comando FOR, mas algum expert ai poderia me ajudar com ele, coloquei um echo para ver o que acontecia, ele esta rodando, mas não esta dando as entradas como desejado, ele da somente 1 entrada para mim, a segunda ele da entrada em branco no BD, e não da mais entradas....

<?php require_once('Connections/alexandre.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $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 adm_seriais (serial_produto_id, serial_n_serie) VALUES (%s, %s)",
                       GetSQLValueString($_POST['serial_produto_id'], "text"),
                       GetSQLValueString($_POST['serial_n_serie'], "text"));

  mysql_select_db($database_alexandre, $alexandre);
  $Result1 = mysql_query($insertSQL, $alexandre) or die(mysql_error());
}

$colname_RsSeriais = "-1";
if (isset($_POST['serial_n_serie'])) {
  $colname_RsSeriais = (get_magic_quotes_gpc()) ? $_POST['serial_n_serie'] : addslashes($_POST['serial_n_serie']);
}
mysql_select_db($database_alexandre, $alexandre);
$query_RsSeriais = sprintf("SELECT * FROM adm_seriais WHERE serial_n_serie = %s", GetSQLValueString($colname_RsSeriais, "int"));
$RsSeriais = mysql_query($query_RsSeriais, $alexandre) or die(mysql_error());
$row_RsSeriais = mysql_fetch_assoc($RsSeriais);
$totalRows_RsSeriais = mysql_num_rows($RsSeriais);

for($entradas=0; $entradas <= $_POST['entradas']; $entradas++) {
mysql_select_db($database_alexandre, $alexandre);
$qsqlseriais = "INSERT INTO adm_seriais (serial_produto_id, serial_n_serie) VALUES ('".$_POST['serial_produto_id']."', '".$_POST['serial_n_serie']."')";
$sqlseriais = mysql_query($qsqlseriais, $alexandre);

echo "Entrada: ". $entradas . "<br>";
echo "ID: ".$_POST['serial_produto_id']. "<br>";
$soma = $_POST['serial_n_serie']+$entradas;
echo "Serial: ". $soma. "<br>";
}
?><!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=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">Produto:</td>
      <td nowrap align="right"><input type="text" name="serial_produto_id" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Serial Inicial: </td>
      <td nowrap="nowrap" align="right"><input type="text" name="serial_n_serie" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
        <td nowrap align="right">Entradas: </td>
        <td nowrap align="left">
            <select name="entradas" id="entradas">
                <option value="1">01 Entrada</option>
                <option value="5">05 Entradas</option>
                <option value="10">10 Entradas</option>
                <option value="20">20 Entradas</option>
                <option value="30">30 Entradas</option>
                <option value="40">40 Entradas</option>
                <option value="50">50 Entradas</option>
          </select>
      </td>
       </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td nowrap align="right"><input name="submit" type="submit" value="Inserir" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result($RsSeriais);
?>

Link para o comentário
Compartilhar em outros sites

  • 0
quantos INSERTs aparecem quando você dá o ECHO?

aparecem mais que 1?

Se sim, execute o segundo insert direto no console pra ver o que o mysql te retorna, ou use o mysql_error pra pegar o erro.

sim, no echo aparece todos os inserts, dependo da quantidade q escolho, vou testar aqui o que você disse e já respondo novamente

Link para o comentário
Compartilhar em outros sites

  • 0
quantos INSERTs aparecem quando você dá o ECHO?

aparecem mais que 1?

Se sim, execute o segundo insert direto no console pra ver o que o mysql te retorna, ou use o mysql_error pra pegar o erro.

sim, no echo aparece todos os inserts, dependo da quantidade q escolho, vou testar aqui o que você disse e já respondo novamente

ok, a fonte do problema 'e essa, ele não esta cadastrando em serie, na hr do cadastro ele tenta cadastrar novamente o mesmo numero...

Link para o comentário
Compartilhar em outros sites

  • 0

pessoal, consegui resolver parte do meu problema, agora ele insere, só q ainda estou com um pequeno BUG, por exemplo, se eu escolher 50 inserções, começando do numero 1, a primeira inserção fica em branco no BD, dae ele começa do 1, 2, 3, 4, 5, 6, etc.... e para na inserção 49, ou seja, ele faz 50 inserções, porém a primeira dela fica em branco....

alguém consegue enxergar esse erro no codigo?:

<?php require_once('Connections/alexandre.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $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 adm_seriais (serial_produto_id, serial_n_serie) VALUES (%s, %s)",
                       GetSQLValueString($_POST['serial_produto_id'], "text"),
                       GetSQLValueString($_POST['serial_n_serie'], "text"));

  mysql_select_db($database_alexandre, $alexandre);
  $Result1 = mysql_query($insertSQL, $alexandre) or die(mysql_error());
}

$colname_RsSeriais = "-1";
if (isset($_POST['serial_n_serie'])) {
  $colname_RsSeriais = (get_magic_quotes_gpc()) ? $_POST['serial_n_serie'] : addslashes($_POST['serial_n_serie']);
}
mysql_select_db($database_alexandre, $alexandre);
$query_RsSeriais = sprintf("SELECT * FROM adm_seriais WHERE serial_n_serie = %s", GetSQLValueString($colname_RsSeriais, "int"));
$RsSeriais = mysql_query($query_RsSeriais, $alexandre) or die(mysql_error());
$row_RsSeriais = mysql_fetch_assoc($RsSeriais);
$totalRows_RsSeriais = mysql_num_rows($RsSeriais);

for($entradas=1; $entradas <= $_POST['entradas']; $entradas++) {
mysql_select_db($database_alexandre, $alexandre);
$qsqlseriais = "INSERT INTO adm_seriais (serial_produto_id, serial_n_serie) VALUES ('".$_POST['serial_produto_id']."', '".$soma."')";
$sqlseriais = mysql_query($qsqlseriais, $alexandre);

echo "Entrada: ". $entradas . "<br>";
echo "ID: ".$_POST['serial_produto_id']. "<br>";
$soma = $_POST['serial_n_serie']+$entradas;
echo "Serial: ". $soma. "<br>";
}
?><!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=iso-8859-1" />
<title>Cadastro de Seriais</title>
</head>
<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">Produto:</td>
      <td nowrap align="right"> <div align="left">
        <select name="serial_produto_id" id="serial_produto_id">
          <option value="Cartão 10U$">Cartão 10U$</option>    
          <option value="Cartão 25U$">Cartão 25U$</option>
          <option value="Cartão 50U$">Cartão 50U$</option>  
        </select>
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Serial Inicial: </td>
      <td nowrap="nowrap" align="right"><input type="text" name="serial_n_serie" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
        <td nowrap align="right">Entradas: </td>
        <td nowrap align="left">
            <select name="entradas" id="entradas">
                <option value="1">01 Entrada</option>
                <option value="5">05 Entradas</option>
                <option value="10">10 Entradas</option>
                <option value="20">20 Entradas</option>
                <option value="30">30 Entradas</option>
                <option value="40">40 Entradas</option>
                <option value="50">50 Entradas</option>
          </select>
      </td>
       </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td nowrap align="right"><input name="submit" type="submit" value="Inserir" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result($RsSeriais);
?>

Link para o comentário
Compartilhar em outros sites

  • 0

RESOLVI O SEU PROBLEMA COMPANHEIRO. DA UMA OLHADA. AQUI FUNCIONOU PERFEITAMENTE

<?php require_once('conexao.php'); 

        // Consulta a tabela ADM_SERIAIS e pega o último registro do BD
        $query_rs_carrinho = "SELECT * FROM adm_seriais order by serial_n_serie DESC";
        $rs_carrinho = mysql_query($query_rs_carrinho, $conn) or die(mysql_error());
        $row_rs_carrinho = mysql_fetch_assoc($rs_carrinho);
        $totalRows_rs_carrinho = mysql_num_rows($rs_carrinho);

        // Realiza o LOOP na Tabela ADM_SERIAIS
        // Montei para que o sistema busque os produtos na tabela PRODUTOS
        for($entradas=1; $entradas <= $_POST['entradas']; $entradas++) {
            mysql_select_db($db, $data);
            $soma = $_POST['serial_n_serie']+$entradas;;
            $qsqlseriais = "INSERT INTO adm_seriais (serial_produto_id, serial_n_serie) VALUES ('".$_POST['serial_produto_id']."', '".$soma."')";
            $sqlseriais = mysql_query($qsqlseriais, $data);

        echo "Entrada: ". $entradas . "<br>";
        echo "ID: ".$_POST['serial_produto_id']. "<br>";
        $soma = $_POST['serial_n_serie']+$entradas;
        echo "Serial: ". $soma. "<br>";
        }
?>

<!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=iso-8859-1" />
<title>Cadastro de Seriais</title>
</head>
<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">Produto:</td>
      <td nowrap align="right"><div align="left"><span class="style1"> 
          <select size="1" name="serial_produto_id" id="serial_produto_id">
           <?php
           // BUSCA AS INFORMAÇÕES NA TABELA PRODUTOS COD + NOME DO PRODUTO
           mysql_connect($host, $user, $pass);
            mysql_select_db($db);
               $sQuery = " select * from produtos order by nome ASC";
               $oUsers = mysql_query($sQuery);
                 while ($tipos = mysql_fetch_array($oUsers, MYSQL_ASSOC)){
               echo "<option class=\"formulario\" value=\"".$tipos['cod']."\">".$tipos['cod']." :: " .$tipos['nome']. "</option>\n";
            }
           ?>
          </select>
          </span> </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Serial Inicial: </td>
      <td nowrap="nowrap" align="right"><div align="left">
          <input type="text" name="serial_n_serie" value="<?=$row_rs_carrinho['serial_n_serie']?>" size="10" />
        </div></td>
    </tr>
    <tr valign="baseline">
        <td nowrap align="right">Entradas: </td>
        <td nowrap align="left">
            <select name="entradas" id="entradas">
                <option value="1">01 Entrada</option>
                <option value="5">05 Entradas</option>
                <option value="10">10 Entradas</option>
                <option value="20">20 Entradas</option>
                <option value="30">30 Entradas</option>
                <option value="40">40 Entradas</option>
                <option value="50">50 Entradas</option>
          </select>
      </td>
       </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td nowrap align="right"><input name="submit" type="submit" value="Inserir" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
</body>
</html>

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
      152k
    • Posts
      651,7k
×
×
  • Criar Novo...