The form that is inside a while is saved twice in the database

0

The form I have it in a while loop within an echo to be able to resivir the data of a query and then with a form send it to another table in the database but it is saved twice as I can do so that they are saved just one time?

    <?php
//Mostramos los registros
while ($row=mysql_fetch_array($result))
{
echo " <table width='100%' align='center' >
      <tr><!--<h2 align='center'>Registro de Empresas</h2>-->
      <td>
      <div class='containere'>
          <div class='row'>
            <div class='col-md-6 col-md-offset-3'>
      <form action='' id='formpost' class='formulario'   name='otro' onsubmit='return agregaRegistro();'  enctype='multipart/form-data'>
          <div class='form-group'>      
     <input type='text'  class='form-control' name='ide' id='ide' value='".$row['id_e']."' >
          </div>
          <div class='form-group'>  
     <input type='text'  class='form-control' name='idp' id='idp' value='".$row['id_p']."' >
          </div>      
           <div class='form-group'>      
     <input type='text'  class='form-control' name='ida' id='ida' value='".$_SESSION['id_a']."'  >
          </div>      
          <div class='form-group' align='right'>
    <input type='submit' name='submit' id='agregar' value='agregar' class='btn btn-primary' >
                </form>
                </div>
                </div>
                </div>
       <div id='cargando'> </div>            
        </td>
        </tr>
        </table>
}
mysql_free_result($result)
?>

I pick it up with this

function agregaRegistro(){
    var url = 'postula.php';
    $.ajax({
        type:'POST',
        url:url,
        data:$('#formpost').serialize(),
        success: function(registro){
            $('#formulario')[0].reset();
        $("#cargando").html(data);
        }
    });
    return false;
}

and the process with this PHP

<?php
//copy ($ruta,$destino);
    //conexión a la base de datos
            $con = mysqli_connect("localhost", "root", "", "bd");
            if (mysqli_connect_errno()){
                echo "No se pudo conectar a la base de datos" .mysqli_connect_error();
            }
$ide = mysqli_real_escape_string($con, $_POST["ide"]);          
$idp = mysqli_real_escape_string($con, $_POST["idp"]);          
$ida = mysqli_real_escape_string($con, $_POST["ida"]);
$sqli= mysqli_query($con,"select  COUNT(*) AS total from postulado where id_emp='$ide' AND id_pub='$idp' AND id_alu='$ida'");
$row=mysqli_fetch_object($sqli);
if($row->total == 0){
    // insert va aquí, y sólo se ejecuta si no hay ningún usuario con estos parametros 
$sql = "INSERT INTO postulado (id_pos,id_pub,id_emp,id_alu)
            VALUES ('', '$idp', '$ide', '$ida')";


            if (!mysqli_query($con,$sql)) {


                    die('Error: ' . mysqli_error($con));
                } 
                else{ 


echo " POSTULADO "; 

                    }



} else {
    echo " no ";
    }
                ?>

This is an example of what you print on the postulate button that is the button that sends the form

    
asked by ivanrangel 18.03.2017 в 22:38
source

5 answers

0

Talves is not the best way but I already solve it I send my for a modal and from there I send it to save

function post(ide,idp,ida){
    $('#formpost')[0].reset();
        $.ajax({

        success: function(valores){
                $('#ide').hide();
                $('#idp').hide();
                $('#ida').hide();
                $('#formpost').show();
                $('#postular').show();
                $('#ide').val(ide);
                $('#idp').val(idp);
                $('#ida').val(ida);
                $('#postularm').modal({
                    show:true,
                    backdrop:'static'
                });
            return false;
        }
    });
    return false;
}

function postu(){
    console.log($('#formpost').serialize()  );
    var data = $('#formpost').serialize();
    var url = 'postula.php';
    $.ajax({
        type:'POST',
        url:url,
        data:data,

        success: function(data){
            //$('#formulario')[0].reset();
        $("#cargando").html(data);
        }
    });
    return false;
}
    
answered by 20.03.2017 / 09:35
source
0
        <?php
        //copy ($ruta,$destino);
            //conexión a la base de datos
                    $con = mysqli_connect("localhost", "root", "", "bd");
                    if (mysqli_connect_errno()){
                        echo "No se pudo conectar a la base de datos" .mysqli_connect_error();
                    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        $ide = mysqli_real_escape_string($con, $_POST["ide"]);          
        $idp = mysqli_real_escape_string($con, $_POST["idp"]);          
        $ida = mysqli_real_escape_string($con, $_POST["ida"]);
        $sqli= mysqli_query($con,"select  COUNT(*) AS total from postulado where id_emp='$ide' AND id_pub='$idp' AND id_alu='$ida'");
        $row=mysqli_fetch_object($sqli);
        if($row->total == 0){
            // insert va aquí, y sólo se ejecuta si no hay ningún usuario con estos parametros 
        $sql = "INSERT INTO postulado (id_pos,id_pub,id_emp,id_alu)
                    VALUES ('', '$idp', '$ide', '$ida')";

                    if (!mysqli_query($con,$sql)) {
                            die('Error: ' . mysqli_error($con));
                        } 
                        else{ 
                          echo " POSTULADO "; 
                        }



        } else {
           echo " no ";
        }
   }
                        ?>

the validation that only post-type calls can eliminate that error, the other is to modify a file on the server called .httpaccess

    
answered by 19.03.2017 в 00:45
0

Another thing that occurred to me because I was trying with this:

$query="INSERT INTO postulado (id_pub,id_emp,id_alu) VALUES ('$idp', '$ide', '$ida')";

    $result=$conn->query($query);
    if ($result === TRUE) {
    echo "POSTULADO";
    } else {
     echo "Error: " . $query . "<br>" . $conn->error;
     }
 $conn->close();
    
answered by 19.03.2017 в 03:04
0

I'll give you an example that could possibly work for you.

  

WARNING: MySQL* was declared obsolete in PHP 5.5.0 and removed in PHP 7.0.0. Instead you should use the extensions MySQLi or PDO_MySQL .

Example:

Form:

<?php
while ($row=mysqli_fetch_array($result)) {
    $ide = $row['id_e'];
    $idp = $row['id_p'];
    $ida = $_SESSION['id_a'];

    echo "
        <form id=formpost class=formulario name=otro onsubmit='return agregaRegistro();'>
            <input type=text name=ide id=ide value=$ide />
            <input type=text name=idp id=idp value=$idp />
            <input type=text name=ida id=ida value=$ida />

            <input type=submit name=submit id=agregar value=agregar />

        </form>

        <div id=cargando></div>
    ";
}

mysqli_free_result($result)
?>

Function

function agregaRegistro(){

    var url = 'postula.php';

    $.ajax({
        type:'POST',
        url: url,
        data: $('#formpost').serialize(),
        success: function(registro){
            $('#formulario')[0].reset();
            $("#cargando").html(data);
        }
    });
    return false;
}

postula.php

<?php
//Si esta defenido el formulario y no es NULL (mediante el identificador de nuestro boton).
if (isset($_POST['submit'])) {

    //conexión a la base de datos
    $con = @mysqli_connect('localhost', 'root', '', 'bd');
    //Verificar conexión.
    if (!$con) {
        exit('La conexión fallo: ' . mysqli_connect_errno());
    }

    //Obtenemos datos.
    $ide = mysqli_real_escape_string($con, $_POST["ide"]);          
    $idp = mysqli_real_escape_string($con, $_POST["idp"]);          
    $ida = mysqli_real_escape_string($con, $_POST["ida"]);

    //Sentencia SELECT.
    $sqli= mysqli_query($con,"SELECT id_emp from postulado where id_emp='$ide' AND id_pub='$idp' AND id_alu='$ida'");

    //Comprobamos existencia de registro.
    if (mysqli_num_rows($sqli)===0) {

        //Sentencia INSERT
        $insertar = mysqli_query($con,"INSERT INTO postulado (id_pub,id_emp,id_alu) VALUES ('$idp', '$ide', '$ida')");

        //Comprobamos que se inserto correctamente.
        if(!$insertar) { #falso.
           printf("Error: %s\n", mysqli_error($con));
        } else { #verdadero.
            echo " POSTULADO ";
        }

    } else {
        echo "No se inserto. Ya existen un registro en la Base de datos.";
    }
}
?>
    
answered by 19.03.2017 в 14:32
0

with this modified script it only sends 1 but it does not want to send the other forms it stays with the data of the first form

function postu(){
    console.log($('#formpost').serialize()  );
    var data = $('#formpost').serialize();
    var url = 'postula.php';
    $.ajax({
        type:'POST',
        url:url,
        data:data,
        success: function(data){
            //$('#formulario')[0].reset();
        $("#cargando").html(data);
        }
    });
    return false;
}
    
answered by 19.03.2017 в 22:18