what is happening?

1

I am doing a CRUD and when I finish filling out the form it appears that the "patient has registered", that is what I should say if the records are sent correctly to the table. BUT when going to the table there is nothing (records do not appear) the code does not seem to have syntax errors according to the word processor. can you help me?

the codes are as follows:

/ conexion /

<?php

try {

    $base=new PDO('mysql:host=localhost; dbname=bdnutriologo','root','');

    $base->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $base->exec("SET CHARACTER SET UTF8");

}catch(Exception $e){

    die ('error' .$e->getMessage());
    echo "linea del error" .$e->getMessage();
}

?>

/ inserting records into the database using PDO /

<?php

include ("conexion.php");

 $registros=$base->query("SELECT * FROM expediente")- 
 >fetchAll(PDO::FETCH_OBJ); 

 if(isset($_POST["cr"])){

 $id_exp=$_POST["id_exp"];

 $peso=$_POST["peso"];

 $edad=$_POST["edad"];

 $estatura=$_POST["estatura"];

 $fecha_registro=$_POST["fecha_registro"];

$sexo=$_POST["sexo"];

$objetivo=$_POST["objetivo"];

$sql="INSERT INTO expediente (id_exp, peso, edad, estatura, fecha_registro, sexo, objetivo ) VALUES (:idx, :pes, :edd, :est, :fech, :sex, :obj)";


$resultado=$base->prepare($sql);

$resultado->execute(array(":idx"=>$id_exp, ":pes"=>$peso, ":edd"=>$edad, ":est"=>$estatura, ":fech"=>$fecha_registro, ":sex"=>$sexo, ":obj"=>$objeto)); 

}

echo "El paciente fue dado de alta.";

?>
    
asked by Digital Renegade 17.04.2018 в 08:32
source

2 answers

1

I think several things must be taken into account to optimize your code:

  • Evaluate correctly what is happening at each moment, writing a controlled code
  • Make error handling as specific as possible. In the case of PDO, errors can be obtained relative to the object PDO itself, or object PDOStatement . I think that here it is convenient to use the latter, to be more specific.
  • You can also use rowCount() to show the number of rows that were inserted.

I would propose this solution:

$sql="INSERT INTO expediente (id_exp, peso, edad, estatura, fecha_registro, sexo, objetivo ) VALUES (:idx, :pes, :edd, :est, :fech, :sex, :obj)";

$stmt=$base->prepare($sql);
$arrParams=array(":idx"=>$id_exp, ":pes"=>$peso, ":edd"=>$edad, ":est"=>$estatura, ":fech"=>$fecha_registro, ":sex"=>$sexo, ":obj"=>$objeto);
$resultado=$stmt->execute($arrParams); 

$msgInfo=($resultado) ? "Se insertaron ".$stmt->rowCount(). " registros" : "¡Error! ".$stmt->errorInfo()[2];
echo $msgInfo;

The key here is the line where the variable $msgInfo is created. It evaluates the value of $resultado through a ternary operator. If it is true, it means that the query occurred successfully, in that case $msgInfo will be a message about it, indicating the number of rows that were inserted. Otherwise, $msgInfo will acquire the value of an error message, obtained from $stmt->errorInfo()[2] . The value 2 that appears there is because errorInfo returns an array, and the error message is found in the key 2 of that array.

Optimize the connection string

Seeing the way you connect, I commented that you can optimize your connection in this way:

    $arrOptions = array(
        PDO::ATTR_EMULATE_PREPARES => FALSE, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
    );

    $base=new PDO('mysql:host=localhost; dbname=bdnutriologo','root',$arrOptions);

As you can see, I have created a variable $arrOptions in which I indicate how I want my connection and pass that array as the last parameter of my connection. This will prevent applying two methods to the object after it has been created .

Among the options I have put one that is very important for security: PDO::ATTR_EMULATE_PREPARES => FALSE , not put it could suppose that PDO could emulate the prepared queries and in some scenarios you could strain an SQL injection.

    
answered by 17.04.2018 / 12:39
source
3

The discharged message comes out because it is independent of the result of the insert.

The method execute returns a True or False depending on the success of the query Why do not you try control it with that?

Edit: The specific method for errors with PDO is ErrorInfo () , on the sample page It comes out like that.

$stmt = $dbh->prepare('bogus sql');

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}

Where $ stmt would be your $ result .

    
answered by 17.04.2018 в 09:30