limit daily records

1

I have edited this post to see if I can understand I'm trying to make an insert so that only allows 3 records to enter per date, I mean 2017-02-12, to this date there can only be three records, for a new record you should try another day or better with another date, If there are already three records with the same date and it is about making another record with the same date already registered, you should send a message:  ('The limit of daily records has been exceeded, try another date!') I currently have this, but the error it gives me is that it only sends the message that ('The limit of daily records has been exceeded, try another date. ! ') and does not register

   <?php 
    include("conexion.php");

    if (isset ($_POST['guardar'])){ 
        $cedula=$_REQUEST['cedula'];
        $idtipodecita=$_REQUEST['idtipodecita'];
        $fecha_cita=$_REQUEST['fecha_cita'];
        $estado=$_REQUEST['estado'];
        $telefono=$_REQUEST['telefono'];

        $cita_x_dia = 2;
        $sql="SELECT COUNT(*) FROM cita_previa WHERE fecha_cita='$fecha_cita'";
        $res=mysql_query($sql,$link) or die ( mysql_error());
        $nrows=mysql_num_rows($res);
        if($res <= $cita_x_dia) 
        {
            if (mysql_query("INSERT INTO cita_previa (cedula,idtipodecita,fecha_cita,estado,telefono) VALUES 
('$cedula','$idtipodecita','$fecha_cita','$estado','$telefono')",$link)){

                echo "<script>alert ('Cita Previa registrada, pronto lo contactaremos!');</script>
<META HTTP-EQUIV='REFRESH' CONTENT=0;URL=http:citaprevia.php>";
            }else{
                echo "<script>alert ('Se ha superado el limite de registros diarios, intente con otra Fecha!');</script>
<META HTTP-EQUIV='REFRESH' CONTENT=0;URL=http:citaprevia.php>";
     }


?>

I have finally solved it and in this way I am adding the cod for those who can use it thanks to a friend ... with this I give the subject as closed

<?php 
include("conexion.php");

if (isset ($_POST['guardar'])){ 
    $cedula=$_REQUEST['cedula'];
    $idtipodecita=$_REQUEST['idtipodecita'];
    $fecha_cita=$_REQUEST['fecha_cita'];
    $estado=$_REQUEST['estado'];
    $telefono=$_REQUEST['telefono'];



    $sql="SELECT COUNT(*) AS 'Registros' FROM cita_previa WHERE fecha_cita='$fecha_cita'";
    $res=mysql_query($sql,$link) or die ( mysql_error());
    $nrows=mysql_num_rows($res);
    list( $no_registros ) = mysql_fetch_array($res);
    if( $no_registros >= 2 ) {

        echo "<script>alert ('Se ha superado el limite de registros diarios, intente con otra Fecha!');</script><META HTTP-EQUIV='REFRESH' CONTENT=0;URL=http:citaprevia.php>";

        die (' ');
    }else{

    mysql_query("INSERT INTO cita_previa (cedula,idtipodecita,fecha_cita,estado,telefono) VALUES('$cedula','$idtipodecita','$fecha_cita','$estado','$telefono')",$link);

    echo "<script>alert ('Cita Previa registrada, pronto lo contactaremos!');</script><META HTTP-EQUIV='REFRESH' CONTENT=0;URL=http:citaprevia.php>";
    }
?>
    
asked by yoclens 11.02.2017 в 21:25
source

5 answers

0

the solution was:

$sql="SELECT COUNT(*) AS 'Registros' FROM cita_previa WHERE 
fecha_cita='$fecha_cita'";
$res=mysql_query($sql,$link) or die ( mysql_error());
$nrows=mysql_num_rows($res);
list( $no_registros ) = mysql_fetch_array($res);
if( $no_registros >= 2 ) {
    
answered by 16.03.2017 / 14:52
source
1

Use the count () function to know the number of lines in the list.

$sql="SELECT * FROM cita_previa WHERE fecha_cita='$fecha_cita'";

$res=mysql_query($sql,$link);
#$nrows=mysql_num_rows($res);
if(count($res)<=15){ # utiliza count()

on the other hand the mysql_ * functions are OBSOLETE using a PDO object Good luck!

EDITED

I leave you an example with a PDO object, a query function and the use of COUNT () outside the query.

PDO dbcore.php stackoverflow Warning ! may contain tabulation errors if you copy the following

<?php
Config::write('db.host', 'localhost');
Config::write('db.port', '3306');
Config::write('db.basename', 'puravida');
Config::write('db.user', 'root');
Config::write('db.password', '');

class Config {

    static $confArray; 

    public static function read($name) {
        return self::$confArray[$name];
    }

    public static function write($name, $value) {
        self::$confArray[$name] = $value;
    }
}

class Core {
    public $dbh; // manejador de conexion de la base de datos.
    private static $instance;

    private function __construct()  {

        $conexion = 'mysql:host=' . Config::read('db.host') . ';dbname=' . Config::read('db.basename') .';charset=utf8'. ';port=' . Config::read('db.port') .';connect_timeout=15';
        $user = Config::read('db.user');
        $password = Config::read('db.password');
        $this->dbh = new PDO($conexion, $user, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
        $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);// desactivar emulación de querys peparadors
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// lanzar excepciones.
    }

    public static function getInstance() {
        if (!isset(self::$instance)) {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }
}
<?php

FUNCTION agenda.php Warning ! may contain tabulation errors if you copy the following

    public static function Ver($idpaciente, $idpersonal)
    {
    if (!isset($idpaciente)) {
       $idpaciente=0;
    }
    if (!isset($idpersonal)) {
        $idpersonal=0;
    }

    // section 10-0-0-5-4286bd1e:14f806bdbcd:-8000:0000000000000C73 begin
    $qury='select DISTINCT
    agenda.idagenda as id,
    agenda.horainicio AS hora,
    agenda.horafinal AS hasta,
    salas.sala 
    FROM
    agenda
    INNER JOIN salasagenda ON salasagenda.idagenda = agenda.idagenda
    INNER JOIN salas ON salas.idsala = salasagenda.idsala
    INNER JOIN personal ON personal.idpersonal = agenda.idpersonal
    INNER JOIN pacientes ON pacientes.idpaciente = agenda.idpaciente
    INNER JOIN personas ON personas.ci = pacientes.ci
    INNER JOIN roles ON roles.idrol = pacientes.idrol
    WHERE
    (agenda.FechaFinal >='.date('Y-m-d').') AND (
    agenda.horainicio BETWEEN DATE_SUB(NOW(), INTERVAL "4" HOUR) and TIME("21:00:00")) and (agenda.idpaciente='.$idpaciente.' OR agenda.idpersonal='.$idpersonal.') ORDER BY agenda.horainicio';
    try {
    $bd=Core::getInstance();
    $qbdobj=$bd->dbh->prepare($qury);
    if ($qbdobj->execute()) {
        $qbdobj->setFetchMode(PDO::FETCH_ASSOC);
         return $qbdobj->fetchall();
         //print_r($qbdobj);
    }else{
        //print_r($qbdobj);
    }

USING COUNT () miagenda.php. Warning ! may contain tabulation errors if you copy the following

<?php
include $_SERVER['DOCUMENT_ROOT'] .'/Clases/class.Agenda.php';
$agenda=Clases_Agenda::Ver($idpaciente,$idpersonal);
?>
<div class="agenda">
<section>
    <h3>Hola <?php echo $nombre."! "; ?>para hoy <b><?php
    echo date('Y-m-d');  ?></b> tiene <b><?php echo count($agenda); ?></b> recordatorio(s);</h3><br>
    <?php 
    //print_r($idpaciente);
    //print_r($idpersonal);
    //$agenda= new Clases_Agenda();
    //print_r($agenda);
    if (!is_array($agenda)) {
        echo "No tienes nada para hoy.";
    }else{
         echo "<table border=1 width=100%><tr>";
         echo "<th>Desde hora</th>";
         echo "<th>Hasta hora</th>";
         echo "<th>Sala</th><th>acciones</th></tr>";
         for ($i=0; $i <count($agenda) ; $i++) {    
                echo"<tr><td>".$agenda[$i]['hora']."</td><td>".$agenda[$i]['hasta']."</td><td>".$agenda[$i]['sala']."</td>";
                //echo"<tr><td>".$agenda[$i]['hasta']."</td>";
                echo '<td><a href="agenda.php?url=modificar&id='.$agenda[$i]['id'].'">modificar</a></td>';
        }                       
             echo"</tr>";
         }
         echo"</table>";
         echo"<p></p>";

     ?>
     </section>
     </div>

Also if you notice that I am checking that $ agenda is an array.

if (!is_array($agenda))

luck!

    
answered by 11.02.2017 в 21:52
1

Friend, my answer, similar to the previous ones, I also add that you can occupy the functions of mysqli instead of those of mysql, I leave this link: When you stopped using mysql_comando commands and what version of php ?

$sql="SELECT * FROM cita_previa WHERE fecha_cita='$fecha_cita'";

$res=mysql_query($sql,$link);
#$nrows=mysql_num_rows($res);
if(count($res)<15){ # utiliza count()

I saw that in all the examples (answers), even in your question it says $res <= 15 in strict rigor if you want the maximum to be 15 should be so $res < 15 or in the case of this example count($res) < 15 If not, when you reach 15 you will enter one more record.

I hope it serves you.

This is to answer the question, and to give as an example according to the conversation of this answer.

Assuming you have a table cita_previa and it has 15 records where in the field fecha_cita , of all records has the value of 2010-10-10 . Then there is a daily limit of records, where the limit is 15 records, that is, in this example, no more records should be allowed for the 2010-10-10 date.

Then in the PHP page that enters records we will have.

<?php 

// donde $_POST['fecha'], viene de un formulario enviado por POST y el valor de este es '2010-10-10'
$fecha_cita = isset($_POST['fecha']) ? $_POST['fecha']: '';

// Comprobamos que ya no hayan mas de 15 registros con esa fecha.
$rs = mysql_query("SELECT * FROM tabla WHERE fecha = '$fecha_cita'", $link)
// Basicamente la consulta dice 'SELECT * FROM tabla WHERE fecha = '2010-10-10''
// comparamos la cantidad con el numero que le pusimos de limite
if(mysql_num_rows($rs) < 15){ 
// si habiamos dicho que teniamos 15 registros con esa fecha, estara preguntando si 15 < 15, como no lo es, irá al else.
// si es menor, ingresará uno nuevo
} else {
// si es 15 o mayor a 15 no ingresará un nuevo registro.
}

I hope it can work.

    
answered by 12.02.2017 в 04:56
1

I do not advise you to keep using MySQL* , they are insecure against SQL injection .

  

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 .

Let's look at an example MySQLi:

//Fecha obtenido desde tu formulario.
$fecha_cita = $_REQUEST['fecha_cita'];

//Sentencia.
$sql = mysqli_query($link, "SELECT cedula FROM cita_previa WHERE fecha_cita='$fecha_cita'";
//Comprobamos existencia de registros en Base de datos y mientras sea inferior a total de (3) registros, insertamos un registro nuevo.
if(mysqli_num_rows($sql) < 3) {
    //Insertamos registro nuevo a la Base de datos.
} else {
   echo 'Tu registro no se inserto, la Base de datos ya cumple con los regisrtos permitidos.';
}

I advise you to use sentences prepare () or PDO , to achieve greater security in your web application.

Example mysqli_prepare ():

//Fecha obtenido desde tu formulario.
$fecha_cita = $_REQUEST['fecha_cita'] ?: '';

//Sentencia (SELECT).
$stmt = $link->prepare("SELECT cedula FROM cita_previa WHERE fecha_cita = ?");
$stmt->bind_param("s",$fecha_cita);//Ligamos parametros marcadores, es decir los valores ?.
$stmt->execute();//Ejecutamos sentencia.
//Comprobamos registros.
$stmt->store_result();
if($stmt->num_rows < 3) {

   $stmt->close();//Cerramos sentencia.

   //Sentencia (INSERT).
   $stmt = $link->prepare("INSERT INTO cita_previa (cedula,idtipodecita,fecha_cita,estado,telefono) VALUES(?,?,?,?,?)";
   $stmt->bind_param("iisss",$cedula,$idtipodecita,$fecha_cita,$estado,$telefono); //Atención, iisss,  son los tipos para el correspondiente enlazado de variable, deben de coincidir.

   //i     la variable correspondiente es de tipo entero
   //d     la variable correspondiente es de tipo double
   //s     la variable correspondiente es de tipo string
   //b     la variable correspondiente es un blob y se envía en paquetes

   $stmt->execute(); //Ejecutamos sentencia
   $stmt->close(); //Cerramos sentencia.
   echo 'Tu registro se inserto correctamente a la Base de Datos.';

} else {
    $stmt->close();//Cerramos sentencia.
   echo 'Tu registro no se inserto, la Base de datos ya cumple con los regisrtos permitidos.';
}
    
answered by 12.03.2017 в 12:57
0

I think you should make a query using the COUNT function of mysql to tell you the records that meet the following criteria WHERE fecha_cita = 'Fecha_yday';

if the number of records is equal to or greater than 15 you throw the message that there are already more than 15 records and you are ready

    
answered by 11.02.2017 в 21:55