0

I have a prepared statement that will insert an entry into the database. The statement works fine and inserts entries. I wrap the statement in a function, call the function, and it no longer inserts into the database. Is there an issue with calling these statements from a function? Side note...my end goal is to actually put this function in a class as a method. I was attempting that, and began troubleshooting and have determined the error begins when putting in a function. My next step is to move this into a class. Is there anything else in my code that would prevent that from being possible?

<?php

include 'main_connection.php';

function add() {
    $stmt = $mysqli->prepare("INSERT INTO user (name) VALUES (?)");
    $stmt->bind_param('s',$name);
    $name = "test";
    $stmt->execute();
    $stmt->close();

}

add();  

?>
KLee1
  • 6,080
  • 4
  • 30
  • 41
user1613223
  • 75
  • 2
  • 11

2 Answers2

3

You have a variable scope issue. Specifically, add() does not know the variables $mysqli or $name.

There are numerous ways to solve this. A quick suggestion would be to pass parameters to add():

function add($mysqli, $name) {
  // your code
}

add($mysqli, $name);

Or to use the global scope:

function add() {
  global $mysqli, $name;
  // your code
}

Disclaimer: I am not advocating either. Reference the following - PHP global in functions

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1
function add($mysqli, $name) {
    $stmt = $mysqli->prepare("INSERT INTO user (name) VALUES (?)");
    $stmt->bind_param('s',$name);
    $name = "test";
    $stmt->execute();
    $stmt->close();

}

add($mysqli, $name); 
keyboardSmasher
  • 2,661
  • 18
  • 20