mysqli_query() expects Parameter 1 to be mysqli, null Given in, how to resolve?

Asked

Viewed 985 times

1

I want to enter the values of the form in the database, but shows the error.

mysqli_query() expects Parameter 1 to be mysqli, null Given in

Php link 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);

}

?>
  • The variable $con does not exist in the context of its function, therefore it is null.

1 answer

2

Cannot (nor desired) access global variables within a function. The function addProdutoVenda() does not see the variable $con, so the error ( invalid connection).

To solve this, pass the connection as argument of the function:

change the signature to:

function addProdutoVenda($con){

And the call should be 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) inside its function is dependent on a form sent by post, the suggestion to eleminate this problem is the same, pass the $_POST as an argument.

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

  • Or, within the scope of the add function global $con;.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.