Limit number of data to be inserted in the mysql database

1

I insert a name from a form into a database that represents the participants of a workshop. In the workshop there is only room for 30 people and try to limit that with the COUNT (*) function. My problem is that the form keeps sending data even if the database already has 30 entries. Thanks for your help.

<?php
$link = mysqli_connect("localhost", "user", "pass", "base");
if($link === false){
  die("ERROR: No se puede conectar. " . mysqli_connect_error());
 }

 $name = mysqli_real_escape_string($link, $_REQUEST['name']);

 $res = mysqli_query("SELECT COUNT(*) as cnt FROM 'taller1' "); 
 $row = mysqli_fetch_assoc($res);

 if($row['cnt']<30){
   $sql = "INSERT INTO taller1 (name) VALUES ('".$name."')";
   if(mysqli_query($link, $sql)){
     echo "Su registro se ha realizado correctamente.";
   }
   else{
     echo "ERROR: no se pudo añadir $sql. " . mysqli_error($link);
   }
 }
 else{
   echo "Taller lleno";
 }

 mysqli_close($link);
?>
    
asked by omarcea343 14.05.2018 в 01:23
source

1 answer

1

I'll give you an example, and you only have to adapt them to your needs:

<?php

$link = mysqli_connect("localhost", "root", "", "demo");
$res = mysqli_query($link, "SELECT * FROM alumnos ");

$fila = mysqli_num_rows($res);

printf($fila);

if($fila <= 2){
  $sql = "INSERT INTO alumnos (nombre, edad, sexo) VALUES ('dato1', 34, 'dato1')";
  mysqli_query($link, $sql);
}
else{
  echo "Taller lleno";
}

I make the following comments to you

  
  • To read the number of rows I use the mysqli_num_rows method, which receives as parameter the variable that contains the query
  •   
  • Thanks to the function that I mentioned in point 1, I no longer need to count the records; just make a select * from   table and it will work
  •   
        
    answered by 14.05.2018 / 02:32
    source