Joseph
Joseph

Reputation: 733

Undefined variable: mysqli

I have function which is open a connection to DB and an insert function as below

function.php

$mysqli = new mysqli('localhost', 'root', 'password', 'db');

if($mysqli->connect_errno > 0){
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
}

function dbRowInsert($table_name, $form_data)
{
    $fields = array_keys($form_data);
    $sql = "INSERT INTO ".$table_name." (`".implode('`,`', $fields)."`) VALUES('".implode("','", $form_data)."')";
    return $mysqli->query($sql);
}
?> `

But when i used the function in another file, it gave an error on line return $mysqli->query($sql); with error message Undefined variable: mysqli, how come it undefined?

save.php

<?php

require_once '../config/db.php';

$postdata = file_get_contents('php://input');
$request = json_decode($postdata);

$table_name = $request->tablename;
$form_data_head = (array)$request->form_data_head;

//var_dump((array)$request->form_data_head);

dbRowInsert($table_name,$form_data_head);

?>`

Upvotes: 1

Views: 12503

Answers (1)

elixenide
elixenide

Reputation: 44833

You're using a global variable in a local (function) scope. You need to use a global statement or pass a parameter (the better option).

With global:

function dbRowInsert($table_name, $form_data)
{
    global $mysqli; // add this
    $fields = array_keys($form_data);
    $sql = "INSERT INTO ".$table_name." (`".implode('`,`', $fields)."`) VALUES('".implode("','", $form_data)."')";
    return $mysqli->query($sql);
}

With $mysqli as a parameter (the better way)

I've added a parameter in this example, which is better for lots of reasons, especially testing. Doing it this way obviously means you need to adjust how you call the function.

function dbRowInsert($mysqli, $table_name, $form_data)
{
    $fields = array_keys($form_data);
    $sql = "INSERT INTO ".$table_name." (`".implode('`,`', $fields)."`) VALUES('".implode("','", $form_data)."')";
    return $mysqli->query($sql);
}

Upvotes: 4

Related Questions