Why does not a form save data in the database using PHP?

2

I am making a system to store data, very simply.

The problem: when saving it says that the connection variable does not exist, despite being included in the php file, then it says that I keep it correctly, but it does not save anything in the database

Conexion.php:

<?php
$host = "localhost";
$usua = "root";
$pass = "";
$base = "php_practica";
$cone = new mysqli($host, $usua, $pass, $base);

if ($cone->connect_error)
    {
    die("Error de Conexion: " . $cone->connect_error);
    }

?>

Registration form:

<?php
include ("conexion.php");
?>
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title> </title>
</head>

<body>
    <form method="POST" action="procesar.php">
        <h1 align="center">Bienvenido</h1>
        <a href="index.html">
            <ol>Pagina Principal</ol>
        </a>
        <a href="registrar.html">
            <ol>Registrar</ol>
        </a>
        <a href="listado.html">
            <ol>Listado</ol>
        </a>
        <a href="Sancion.html">
            <ol>Sancion</ol>
        </a>
        <div> Ingrese su nombre </div>
        <input type="text" name="nombre">

        <div> Ingrese su apellido </div>
        <input type="text" name="apellido">

        <div> Ingrese su cedula </div>
        <input type="text" name="cedula">

        <div> Ingrese su rango </div>
        <div>
            <select name="rango">
                <option value="1">First</option>
                <option value="2">Second</option>
                <option value="3">Third</option>
            </select>
        </div>
        <input type="submit" value="enviar">
</body>

</html>

Process.php

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

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title> </title>
</head>

<body>
    <form method="POST" action="funciones.php">
        <?php

bd_agregar($_REQUEST);
?>
</body>

</html>

Functions.php:

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

function bd_agregar($temp){
$nombre=$_REQUEST["nombre"];
$apellido=$_REQUEST["apellido"];
$cedula=$_REQUEST["cedula"];
$rango=$_REQUEST["rango"];
mysqli_query($cone,"INSERT INTO personal (nombre,apellido,cedula,rango)
VALUES ('$nombre','$apellido','$cedula','$rango')");
}


//Revisar si guardo correctamente//
if (mysqli_connect_errno($cone)) 
  {
  echo "Error al guardar los datos:" . mysqli_connect_error(); 
  }
  else
  {
    echo "Datos guardados correctamente:";
    }

mysqli_close($cone); 
?>

ERROR:

  

Notice: Undefined variable: cone in C: \ xampp \ htdocs \ PHP \ System of practice \ functions.php on line 9 --- Warning: mysqli_query () expects parameter 1 to be mysqli, null given in C: \ xampp \ htdocs \ PHP \ System of practice \ functions.php on line 10

    
asked by Victor Alvarado 17.01.2017 в 01:56
source

4 answers

0

Another small error that I see is that in your connection you have set connect_error and should be connect_errno

Conexion.php

Your code:

$host="localhost";
$usua="root";
$pass="";
$base="php_practica";
$cone = new mysqli($host,$usua,$pass,$base);

if ($cone->connect_error) {
                   ^^^^^^
   die("Error de Conexion: " . $cone->connect_error);
                                              ^^^^^^
} 

Updated code:

$host="localhost";
$usua="root";
$pass="";
$base="php_practica";

$cone = new mysqli($host,$usua,$pass,$base);

if ($cone->connect_errno) {
   echo "Falló la conexión a MySQL: (" . $cone->connect_errno . ") " . $cone->connect_error;    
} 

Full example tested on localhost:

Registration form:

<form method="POST" action ="procesar.php">     
    <label> Ingrese su nombre </label>
    <input type="text" name="nombre">

    <label> Ingrese su apellido </label>
    <input type="text" name="apellido">

    <label> Ingrese su cedula </label>
    <input type="text" name="cedula">

    <label> Ingrese su rango </label>
    <div><select name="rango">
      <option value="1">First</option>
      <option value="2">Second</option>
      <option value="3">Third</option>
    </select></div>

    <input type="submit" value="enviar">
</form>

proces.php

<?php    
  require_once'conexion.php';
  include'funciones.php';

  bd_agregar($_REQUEST);

  //Cerramos conexión.
  $cone->close();     
?>

functions.php

<?php
  require_once'conexion.php';

  //Creamos función
  function bd_agregar($temp){
    //Especificamos variable global.
    global $cone;

    //Obtenemos datos formulario
    $nombre = $_REQUEST['nombre'];
    $apellido = $_REQUEST['apellido'];
    $cedula = $_REQUEST['cedula'];
    $rango = $_REQUEST['rango'];

    //Insertamos datos
    $cone->query("INSERT INTO personal (nombre,apellido,cedula,rango) VALUES ('$nombre','$apellido','$cedula','$rango')");         
      echo $nombre.$apellido.$cedula.$rango;
  }

  //Comprobamos ejecución sentencia.
  if ($cone===false) {
    printf("Mensaje de error: %s\n", $cone->error);
  } else {
    echo "Los datos se insertaron correctamente";
  }

  //Aqui tienes el error de no insertar tus datos 
  //Warning: mysqli_query() expects parameter 1 to be mysqli, null given in...      
  //$cone->close(); 
?>
    
answered by 17.01.2017 / 14:47
source
2

The problem is due to the scope of the variables in PHP . You are trying to access a global variable from within a function without specifying that it is a global variable, then you look for a local variable of the same name (which does not exist) and you receive the failure.

To fix it and be able to use $cone within your function, try adding this as the first line of the bd_agregar function:

global $cone;

Something like this:

function bd_agregar($temp){
  global $cone;
  $nombre=$_REQUEST["nombre"];
  $apellido=$_REQUEST["apellido"];
  $cedula=$_REQUEST["cedula"];
  $rango=$_REQUEST["rango"];
  mysqli_query($cone,"INSERT INTO personal (nombre,apellido,cedula,rango) VALUES ('$nombre','$apellido','$cedula','$rango')");
}
    
answered by 17.01.2017 в 06:49
1

What I see is that you confuse a bit the concepts of procedural programming and the POO (Object Oriented Programming) . To close the connection you should close it in the following way $mysqli->close(); . Another thing I see is that you include the connection everywhere. You should only include it in the Procesar.php .

In the consultation it should be like this:

$mysqli->query($cone,"INSERT INTO personal
(nombre,apellido,cedula,rango)
VALUES ('$nombre','$apellido','$cedula','$rango')");

... and so that the variable $cone works, or the global beams, or you pass it through the argument of the function.

    
answered by 17.01.2017 в 13:47
0

Hello friend according to Leo the same php tells you exactly where the error is look for the php file:

Functions.php:

<?php
include ("conexion.php");
function bd_agregar($temp){
$nombre=$_REQUEST["nombre"];
$apellido=$_REQUEST["apellido"];
$cedula=$_REQUEST["cedula"];
$rango=$_REQUEST["rango"];
**mysqli_query($cone,"INSERT INTO personal (nombre,apellido,cedula,rango)
VALUES ('$nombre','$apellido','$cedula','$rango')");
}**

according to Leo

  

Notice: Undefined variable: cone in C: \ xampp \ htdocs \ PHP \ System   practice \ functions.php on line 9 --- Warning: mysqli_query () expects   parameter 1 to be mysqli, null given in C: \ xampp \ htdocs \ PHP \ System   practice \ functions.php on line 10

your error is exactly in that file Functions.php: on the line 9 and 10

the new line 9 is telling you that the insertion does not accept NULL values, whereas the 10th is waiting for an X result. It is as if you were missing a line but in reality the table does not allow Nulls values. and by not being inserted, you throw that error.

Example if the insertion you want it to be like this:

ID    nombre  apellido cedula    rango
1     pedro   Alvarez  15600600  teniente 

but in your MySQL scrip you do this:

INSERT INTO personnel (name, surname, certificate, rank) VALUES ('pedro', 'Alvarez', '', 'lieutenant',);

Your Cedula field will remain blank:

ID    nombre  apellido cedula    rango
1     pedro   Alvarez            teniente 

NOTES that the ID field should be filled in only. (For self-filling, the mysql table should have a small key in its design, called Yellow in English. In many cases, it tells you that the field is filled only in other cases. that the design tells you that it allows null values) I mean this

ID valor_de_digitos ejemplo INT **NOT NULL**
nombre valor_de_digitos ejemplo Varchar(250) NULL
apellido valor_de_digitos ejemplo Varchar(250) NULL
cedula valor_de_digitos ejemplo INT NULL
rango valor_de_digitos ejemplo Varchar(250) NULL

The fact that the column tells you NOT NULL means that it does not support NULL values

    
answered by 17.01.2017 в 03:16