Error inserting MySQL data with PHP

0

Can someone help me solve this error? the error that throws me is the following:

  

"Warning: mysqli_query () expects parameter 1 to be mysqli, null given   in ... "

<?php 

include 'odbc.php';
/*datos personales*/

$nombre = $_POST['nom']; 
$rut = $_POST['rut']; 
$fono = $_POST['fono']; 
$email=$_POST['email']; 
//conectar();
$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES('$rut','$nombre','$fono','$email')";
//ejecutar insert

$ejecutar= mysqli_query($con,$insertarv);
if(!$ejecutar){
    echo mysql_error()."Error !!";
}else{
    echo "El vendedor de registro exitosamente en la BD";
}
?>

In the odbc class:

<?php
function conectar(){
$user="xxxx";
$pass="xxxx";
$server="localhost";
$db="vende";
$con=mysql_connect($server,$user,$pass);
if(!$con){
    echo("Error al conectar a la base de datos odbc".mysql_error());
}

mysql_select_db($db,$con) or die ("Error al conectar a la base de datos odbc".mysql_error());

return $con;
}
?>
    
asked by Johann Sebastian Painevil Len 09.12.2017 в 07:05
source

4 answers

0

It is not advisable that you mix two styles, that is, the procedural style with the object-oriented style or in your case the extension mysql with mysqli , in fact the mysql* extension was declared obsolete in PHP 5.5.0 and deleted in PHP 7.0.0. .


I give you some examples how to use each style, even so I advise you to use the last mysqli::prepare , the query and the data are sent to the server separated from each other, and therefore there is no possibility that they interfere.

mysqli

Object-oriented style

connection:

<?php
  $con = new mysqli("localhost", "user", "password", "vende");

  /* comprobar la conexión */
  if ($con->connect_errno) {
      printf("Falló la conexión: %s\n", $con->connect_error);
      exit();
  }

  //Caracteres UTF-8 para MySQL.
  if (!$con->set_charset("utf8")) {
    printf("Error cargando el conjunto de caracteres utf8: %s\n", $con->error);
    exit();
  }
?>

Your insert statement:

$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$rut','$nom','$fono','$email')";

//ejecutar insert
$ejecutar = $con->query($insertarv);

if(!$ejecutar){
    printf("Error en ejecución: %s\n", $con->error);
}else{
    echo "El vendedor de registro exitosamente en la BD";
}


Procedural style (The one you were using)

$con = mysqli_connect("localhost", "user", "password", "vende");

/* comprobar la conexión */
if (mysqli_connect_errno()) {
    printf("Falló la conexión: %s\n", mysqli_connect_error());
    exit();
}

/* cambiar el conjunto de caracteres a utf8 */
if (!mysqli_set_charset($con, "utf8")) {
    printf("Error cargando el conjunto de caracteres utf8: %s\n", mysqli_error($con));
    exit();
} 

Your insert statement:

$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$rut','$nom','$fono','$email')";

//ejecutar insert
$ejecutar= mysqli_query($con,$insertarv);

if(!$ejecutar){
    printf("Error en ejecución: %s\n", mysqli_error($con));
}else{
    echo "El vendedor de registro exitosamente en la BD";
}


mysqli::prepare

Sentences prepared in object-oriented style

connection:

<?php
  $con = new mysqli("localhost", "user", "password", "vende");

  /* comprobar la conexión */
  if ($con->connect_errno) {
      printf("Falló la conexión: %s\n", $con->connect_error);
      exit();
  }

  //Caracteres UTF-8 para MySQL.
  if (!$con->set_charset("utf8")) {
    printf("Error cargando el conjunto de caracteres utf8: %s\n", $con->error);
    exit();
  }
?>

Your insert statement:

$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES (?,?,?,?)";

//Sentencia preparada
$ejecutar = $con->prepare($insertarv);
/* ligar parámetros para marcadores */
$ejecutar->bind_param("isss",$rut,$nom,$fono,$email);
//Ejecutar sentencia.
$rc = $ejecutar->execute();
//Comprobacion de ejecución
if(false===$rc){
    printf("Error en ejecución: %s\n", $ejecutar->error);
}else{
    echo "El vendedor de registro exitosamente en la BD";
}

mysqli::prepare mysqli_stmt::bind_param


  

Note: If idVendedor is auto_increment and it's also your primary key you do not need to add it.

It might look like this:

"INSERT INTO vendedor (nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$nom','$fono','$email')";

Now if $rut = $_POST['rut']; is a different data to your idVendedor then you should add that column to your sentence, it is important that you add your columns according to the order in how you created it in your phpMyAdmin .

It might look like this:

"INSERT INTO vendedor (columna_ruta,nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$rut','$nom','$fono','$email')";

    
answered by 10.12.2017 / 06:04
source
3

You are obtaining the following data:

$nombre = $_POST['nom']; 
$rut = $_POST['rut']; 
$fono = $_POST['fono']; 
$email=$_POST['email']; 

Now in the INSERT you're trying to insert the information you get in the next POST $rut = $_POST['rut']; to the column of id of the seller.

You must change this idVendedor for the column that really corresponds to $rut = $_POST['rut'];

$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES('$rut','$nombre','$fono','$email')";
  

I am completely convinced that it is necessary to add a new column in the data table to insert this value or data that you receive $rut = $_POST['rut']; I do not believe that this $rut is the id of the seller, you are forcing to insert data in a column int corresponding to idVendedor therefore shows the error.

Try to insert only the 3 data, then you will give me the reason, to which I refer.

Replace the previous code, for this:

<?php 

  include 'odbc.php';
  /*datos personales*/

  $nombre = $_POST['nom']; 
  $rut = $_POST['rut']; 
  $fono = $_POST['fono']; 
  $email=$_POST['email']; 

  $insertarv="INSERT INTO vendedor(nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$nom','$fono','$email')";
  //ejecutar insert
  $ejecutar= mysqli_query($con,$insertarv);
  if(!$ejecutar){
    echo "Error al ingresar los datos del vendedor ".mysqli_error($con);
  }else{
    echo "El vendedor de registro exitosamente en la BD";
  }
?> 

On the other hand, in the connection to the database you are mixing both extensions MySQL and MySQLi

Change the connection to the database because of this:

<?php

  $con = mysqli_connect('localhost','','','demo'); 

  // Si la conexión falla, aparece el error 
  if($con === false) { 
    echo 'Ha habido un error <br>'.mysqli_connect_error(); 
  } else {
    echo 'Conectado a la base de datos';
  }
?>

Or object-oriented style connection

<?php
  //Configuración.
  $ServerName = "Localhost";
  $Username = "root";
  $PassWord = "";
  $DataBase = "demo";    

  //Creamos conexión.
  $con = new mysqli($ServerName, $Username, $PassWord, $DataBase);

  //Comprobamos conexión.
  if ($con->connect_error) {
    exit("Error de conexión: " . $con->connect_error);
  }

  //Caracteres UTF-8 para MySQL.
  if (!$con->set_charset("utf8")) {
    printf("Error cargando el conjunto de caracteres utf8: %s\n", $con->error);
    exit();
  }
?>

It is not advisable to use prepared statements to avoid possible SQL injections, possible system vulnerabilities among others.

More information on the subject, read the following sources:

answered by 09.12.2017 в 07:14
1

The possible error is because you are using two extensions, in your connection and the selection of the database uses MySQL that is declared obsolete and should stop using and in mysqli_query MySQLi which is incorrect.

mysqli_query expects the result of mysqli_connect is this function that you should use for the connection, remember that you can pass the name of the bd as the fourth parameter. (the example option is procedural style, if you want style oriented objects I also leave the way to do it, but you would have to restructure everything to object oriented )

//procedimientos
$con=mysqli_connect($server,$user,$pass,$db);
//estilo orientado  a objetos
$con= new mysqli($server,$user,$pass,$db);
    
answered by 09.12.2017 в 07:11
0

so I leave my code after your suggestions

<!doctype html>
<html>
<head>
<title>Vende easy car </title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


</head>
<body>
<div class="header">	
  <div class="wrap"> 
	<div class="header-top">
		 <div class="logo">
			 <a href="index.html"><img src="images/logo.png" alt=""></a>
		 </div>
		 <div class="menu">
			<div id="cssmenu">
				<ul>
				   <li><a href="index.html"><span> Home </span></a></li>
				   <li class="active"><a href="vender.html"><span> Vender </span></a></li>
                    <li><a href="contacto.html"><span> Contacto </span></a></li>
				</ul>
            </div>
		  </div>	
		  <div class="clear"></div> 
	   </div>
   </div>	
</div>
<div class="main">
		<div class="content-top">
		  <div class="wrap">
				<div class="title3">
	

<?php 

include 'odbc.php';
/*datos personales*/

$nombre = $_POST['nom']; 
$rut = $_POST['rut']; 
$fono = $_POST['fono']; 
$email=$_POST['email']; 

$insertarv="INSERT INTO vendedor(idVendedor,nombreVendedor,fonoVendedor,emailVendedor) VALUES ('$rut','$nom','$fono','$email')";
//ejecutar insert
$ejecutar= mysqli_query($con,$insertarv);
if(!$ejecutar){
	echo "Error al ingresar los datos del vendedor ".mysql_error();
}else{
	echo "El vendedor de registro exitosamente en la BD";
}
?> 

</div>
		</div >
		  </div>
		</div>	
        
            </body>
</html>

And the other class

<?php
function conectar(){
$server="localhost";
$user="xxxx";
$pass="xxxx";
$db="vende";


//$con= new mysqli($server,$user,$pass,$db);
$con=mysqli_connect($server,$user,$pass,$db);

  //Comprobamos conexión.

if($con->connect_error){
exit("Error de conecxion conexión: ".$con->connect_error);
} 
 //Caracteres UTF-8 para MySQL.
  if (!$con->set_charset("utf8")) {
    printf("Error cargando el conjunto de caracteres utf8: %s\n", $con->error);
    exit();
  }
  return $con;
}
?>

    
answered by 10.12.2017 в 04:26