0

I'm creating simple registration script with function that checks if the username and e-mail are already taken. I import php file which creates mysqli connection to DB and saves it to $mysqli variable. Now the question - why I can't see the $mysqli variable in my function? I have to pass it as parameter so I can work with it. Here is the code

<?php
require_once "./incl/db.php";
require_once "./Logger.class.php";
$logger = new Logger("register.php.log");

function isTaken($username, $email, $mysqli){
  $ret = 0;
  if($stmt = $mysqli->prepare("SELECT email,nick FROM users WHERE email = ? OR nick = ? LIMIT 1")){
    $stmt->bind_param("ss", $email, $username);
    if($stmt->execute()){
      $stmt->store_result();
      if($stmt->num_rows === 0){
        $stmt->free_result();
        return $ret;
      }else{
        $stmt->bind_result($dbEmail, $dbNick);
         while($stmt->fetch()){
          if(strcmp(strtolower($dbEmail), strtolower($email)) == 0)
            $ret+= 1;
          if(strcmp(strtolower($dbNick), strtolower($username)) == 0)
            $ret+= 2;
          return $ret;
         }
      }
    }else{
      $logger->logError("Error executing stmt(isTaken)! ".$mysqli->error.$logger->newLine.$stmt->error);
      die("stmt error");
    }
  }else{
    $logger->logError("Error preparing stmt(isTaken)! ".$mysqli->error.$logger->newLine.$stmt->error);
    die("Error preparing stmt!");
  }
}

session_start();
ob_start();

header ('HTTP/1.1 302 Found');
if(isset($_POST["registrovat"]) && !empty($_POST["mail"])
  && !empty($_POST["password"]) && !empty($_POST["username"])){
    $email = trim($_POST["mail"]);
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);

    for($i = 0; $i < 10; $i++){
      $password = hash("sha256", $password);
    }

    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
      //echo "E-mail valid";
      $isTaken = isTaken($username, $email, $mysqli);
      if($isTaken === 0){
        if($stmt = $mysqli->prepare("INSERT INTO users (id, nick, password, email, rights) VALUES(NULL, ?, ?, ?, 0)")){
          if($stmt->bind_param("sss", $username, $password, $email)){
            if($stmt->execute()){
              $id = $stmt->insert_id;
              header('Location: http://'.$_SERVER["SERVER_NAME"].'/profil/'.$id);
            }else{
              $logger->logError("Error executing stmt! ".$mysqli->error.$logger->newLine.$stmt->error);
              die("Error executing stmt");
            }
          }else{
            $logger->logError("Error binding params(reg): ".$mysqli->error.$logger->newLine.$stmt->error);
            die("error");
          }
          $stmt->close();
        }else{
          $logger->logError("Error preparing stmt(reg)! ".$mysqli->error.$logger->newLine.$stmt->error);
          die("error stmt!");
        }
      }else{
        $text;
        switch($isTaken){
          case 1: $text = "E-mail already exists"; break;   
          case 2: $text = "Username already exists"; break;         
          case 3: $text = "E-mail and username already exists"; break;
          default: $text = "default"; break;
        }
        die($text);
      }
    }else{
      $logger->logError("E-mail not valid: ".$email);
      $logger->logInfo(var_export($_POST, true));
      die("E-mail not valid");
    }
}else{
  $logger->logError("Fields empty.");
  $logger->logInfo(var_export($_POST, true));
  die("Fields empty!");

}
ob_end_flush();
?>
3
  • Ok stop! First nobody can read this code with all these if/else.. Second, don't tell users what is in your database. E-mail already exists is nice if I would like to know what e-mail addresses are in your database. Commented Jul 16, 2013 at 9:48
  • @Bondye do you have better solution? Just tell me how(some links or keywords for google will be enough) to improve it :) Commented Jul 16, 2013 at 9:52
  • 2
    Simply, the keyword is return. Return stops the current function and returns. So when you have function test() { if(true) {return;} echo 'hi'; } and I execute test() it won't echo hi. Here an example test 1 test 2 Commented Jul 16, 2013 at 10:00

3 Answers 3

2

If you want to access a global variable without passing it as a parameter, you must use the global declaration:

function isTaken($username, $email){
    global $mysqli;
Sign up to request clarification or add additional context in comments.

1 Comment

.. or use $GLOBALS['mysqli'] - but some people seem to have some dislike for $GLOBALS
1

Because unless you import it or declare it global, then it is outside the scope of the function.

Each function is an encapsulated block of code that only knows about itself and you can only see variables set within the function or super globals like $_POST unless you pas them into the function or declare

global $mysqli;

inside the function to tell it to use the variable from outside

Comments

1

The variable is outside of the scope of the function. You can do it like this, or make it a global variable like Barmar said:

function isTaken($username, $email){
    require_once "./incl/db.php";
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.