Error entering data to MYSQL

1

What happens is that everything worked fine until I added codsem - > which is semester code. Now he tells me registered assistance when the student does not exist and not even.

<?php
$link = mysql_connect('localhost', 'root', '') or die('No se pudo conectar: ' . mysql_error());
echo 'Connected succedsrssfully';
mysql_select_db('controlasistencia') or die('No se pudo seleccionar la base de datos');
$query = 'SELECT * FROM asistencia';
$codes=$_POST['codes'];
$coddo=$_POST['coddo'];
$codsem=$_POST['codsem'];
$query_search = "Insert into asistencia (coddo,codsem,codes) values ('".$codes."','".$coddo."','".$codsem."')";
$query_exec = mysql_query($query_search) or die(mysql_error());
mysql_close($link);
?>

How could I do so that when a student does not exist in the table and I try to enter their assistance I get an error

Here I leave the assistance table

CREATE TABLE 'asistencia' (
'coddo' bigint(20) NOT NULL,
'codsem' bigint(20) NOT NULL,
'codes' bigint(20) NOT NULL,
'fecha' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

And its key

ALTER TABLE 'asistencia'
ADD KEY 'codsem' ('codsem'),
ADD KEY 'codes' ('codes'),
ADD KEY 'coddo' ('coddo');
    
asked by Rodolfo Gav 08.12.2016 в 16:12
source

3 answers

0

The best way, is the one that you mentioned, created relationships between these tables, with claves foráneas .

You also have to bear in mind that mysql has become obsolete according to the official documentation and instead you should use mysqli , or I personally advise you sentencias preparadas .

  

Manual prepared sentences:
link

Even so, I'll leave an example, as it could be without claves foráneas , but simply doing a check if there is any relationship, and if there is inserted the data.

For this we make a SELECT in the student table where we imagine that you have put the column code with the same relation as your attendance table, column codsem, important that the code is unique (unique) , to be able to work as an identifier.

The code could be as follows:

<?php    
//Data conexión.
$servidor = 'localhost';
$usuario = 'root';
$contrasena = '';
$base_datos = 'controlasistencia';

//Conexión.
$link = mysqli_connect($servidor, $usuario, $contrasena, $base_datos);

//Comprobamos conexión.
if (!$link) {
    die("No se pude conectar: " . mysqli_connect_error());
} 

echo "Conectado con exito";

//Obtenemos datos de manera mas segura (mysqli_real_escape_string).
$codes = mysqli_real_escape_string($link,$_POST['codes']);
$coddo = mysqli_real_escape_string($link,$_POST['coddo']);
$codsem = mysqli_real_escape_string($link,$_POST['codsem']);

//Sentencia, comprobación existencia.
$existe = mysqli_query($link,"SELECT codigo FROM estudiantes WHERE codigo='$codsem' ");
//Comprobamos existencia.
if (mysqli_num_rows($existe) === 1) {

  //Sentencia, insertar registro.
  $insertar = mysqli_query($link,"INSERT INTO asistencia (coddo,codsem,codes) VALUES ('".$codes"','".$coddo"','".$codsem"')");

  if ($insertar) {    
    echo "El registro se inserto con exito.";
  } else {
    echo "Hubo un error, no se inserto el registro.";
  }

} else { //Caso falso, tu mensaje de error.
  //Mensaje.
  echo "0 registros encontrados.";
}
//Cerramos conexión.
mysqli_close($link);
    
answered by 08.12.2016 / 20:03
source
1

I recommend you use foreign keys . Here is the official documentation .

Example:

ALTER TABLE 'asistencia'
  ADD FOREIGN KEY (codes)
    REFERENCES estudiantes(codigo)
    ON DELETE CASCADE;

This way, if there is no item in the estudiantes table whose codigo field does not match the codes field in the asistencia table it will give you an error and it will not allow you to insert the record into the table asistencia .

Edit: For more information, the error that will generate you will be a code ERROR 1452 (23000): Can not add or update to child row: a foreign key constraint fails (...) . It will be useful if you want to capture it with mysql_errno() .

PS: I highly recommend that you migrate your code to MySQLi or PDO (I prefer to use the latter). Learning or continuing to use the functions mysql_* is lost time. As of version 5.5 they were considered obsolete and have been deleted in version 7.

    
answered by 08.12.2016 в 18:17
-1

You could make a selection before to determine if a student exists or not. Then, if that student does not exist, you do not insert; if there are inserts.

// Buscar si existe estudiante.
    $query_estudiante = "Select * from estudiate where estudiante_id = $codes")";    

    // Si existe un registro, inserta
    if (count($query_estudiante) > 0){
        $query_search = "Insert into asistencia (coddo,codsem,codes) values ('".$codes."','".$coddo."','".$codsem."')";
        $query_exec = mysql_query($query_search) or die(mysql_error());
    }
    mysql_close($link);
    
answered by 08.12.2016 в 16:20