-2

Here is code:

$connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if($connect->connect_errno) {
   printf("Connect failed: %s\n", $connect->connect_error);
   exit();
}

function send($username="", $password="") {
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
 }
$connect->close();

Notice: Undefined variable: connect in C:\xampp\htdocs\playground01\build\components\includes\root.php on line 44

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\playground01\build\components\includes\root.php on line 44

Where is a problem?

chris85
  • 23,846
  • 7
  • 34
  • 51
Stack Over
  • 37
  • 1
  • 6
  • 1
    Possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Jonathan Jun 17 '16 at 23:59
  • If this resolves your issue please mark the answer as accepted. http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – chris85 Jun 18 '16 at 16:07

2 Answers2

1

This is because of variable scope in PHP. $connect is defined outside send so it is inaccessible. Either pass it as a parameter, define it in the function, or use global.

a)

function send($username="", $password="", $connect) {
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
 }
$connect->close();

Then in the send call pass the $connect.

b)

function send($username="", $password="", $connect) {
    $connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if($connect->connect_errno) {
   printf("Connect failed: %s\n", $connect->connect_error);
   exit();
}
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
 }
$connect->close();

c)

function send($username="", $password="") {
    global $connect;
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
 }
$connect->close();

Additional you should be using parameterized queries with prepared statements.

A third note, passwords should not be stored in plaintext, http://security.blogoverflow.com/2011/11/why-passwords-should-be-hashed/.

chris85
  • 23,846
  • 7
  • 34
  • 51
0

You have to declare which global variables you are going to use in the function if you want to do so:

function send($username="", $password="") {
    global $connect;
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}

Or even better, make the connection a function parameter:

function send($connect, $username="", $password="") {
    $connect->query("INSERT INTO table1 (username, password) VALUES ('$username', '$password')");
}
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94