Script php, insert data in mysql

1

I have this PHP script where I make an insert query in a mysql DB, what I do is declare a mysqli object globally and then from a function make the insert, but since the insert function gives me an error, it tells me that recognizes the $ mysqli object

$servidor = "localhost";
$usuario = "root";
$password ="xxxx";
$basededatos = "xxxx";

$mysqli = new mysqli($servidor, $usuario, $password, $basededatos);
if ($mysqli->connect_errno) {
    echo "Falló la conexión con MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}


function insertar($name,$dni) {
$cadena = "update users set xxxxx";
$mysqli->query($cadena);
}
    
asked by ilernet 16.05.2018 в 17:58
source

1 answer

5

Inside the function "insert" there is no variable $ mysqli, you can send it as a parameter or add it to the function as global, thus achieving that object exists in the function.

function insertar($mysqli, $name, $dni){
 $cadena = "update users set xxxxx";
 $mysqli->query($cadena);
}

or else ...

function insertar($name, $dni){
  global $mysqli;
  $cadena = "update users set xxxxx";
  $mysqli->query($cadena);
}

Source: link

    
answered by 16.05.2018 / 18:14
source