mysqli_query () expects parameter 1 to be mysqli, null given in, how to solve?

1

I want to insert the values of the form into the database, but it presents the error.

  

mysqli_query () expects parameter 1 to be mysqli, null given in

Linking php code:

<?php
    include_once('_php/conn.php');
    if (isset($_POST['addProdutoVenda'])){
        addProdutoVenda();
    }
?>

Código do formulário:
<form class="formVenda"  method="post">
    <h3>NOVA VENDA</h3>
    <label>Codigo: </label>
    <input required="yes" type="search" name="codigo" list="listaCodigoProduto" placeholder="00000"><br><br>

    <label>Descrição: </label>
    <input required="yes" type="search" name="descricao" list="listaNomeProduto" placeholder="Camisa Rosa V"><br><br>

    <label>QTD: </label>
    <input required="yes" type="number" name="quantidade" placeholder="6">

    <input type="submit" name="addProdutoVenda" name="">
</form>

PHP file connection and insertion:

<?php

$con = mysqli_connect('localhost','root','','nik') or die(mysqli_error());

function addProdutoVenda(){

$cod = $_POST['codigo'];
$desc = $_POST['descricao'];
$qtd = $_POST['quantidade'];

$sql = "INSERT INTO produtos VALUES";
$sql.= "('$cod', '$desc','$qtd')";

$query = mysqli_query($con, $sql);

}

?>
    
asked by anonymous 29.12.2016 / 18:16

1 answer

2

It is not possible (nor desirable) to access global variables within a function. The function addProdutoVenda() does not see the variable $con , so the error (connection invalid).

To solve this, pass the connection as an argument to the function:

change your subscription to:

function addProdutoVenda($con){

And the call should look like this:

$con = mysqli_connect('localhost','root','','nik') or die(mysqli_connect_error());
addProdutoVenda($con);

The idea of creating functions is to have code blocks that can be reused in various situations, when using external elements ( $_POST ) within your function is dependent on a form sent by post, the suggestion to eliminate this problem is the same, pass $_POST as argument.

The function does not return any value or treat the error, so it is not possible to know if the operation was successful or not.

    
29.12.2016 / 18:25