title: correct way of writing a MySQLi prepared statement in a function?
body: <h1>Prepared Statements</h1>
  
  <p>Okay, I've just started taking a look at MySQLi prepared statements. This was a big step for me as I'm very new to MySQL and PHP anyway, so I have an extremely tenuous grasp on the concept (perhaps about an hours worth), so your answers will have to be phrased similarly, sorry about this. </p>
  
  <p>What I am wanting to know is if I am correctly writing a prepared statement. There's nothing worse than learning a method which is incorrect and getting used to it, therefore coding entire projects inefficiently. </p>
  
  <p>To the point: I have a function which registers a user, and then returns the inserted id, which is therefore the referencing id of the user.</p>
  
  <p>Previously, I was simply querying the database, which I was told had security risks despite the use of <code>mysql_real_escape_string()</code> and similar security measures. </p>
  
  <p>Now, it looks something like this: (assume for the sake of this question that all referenced variables are defined, the bound parameters are strings, and all called functions exist and are working). </p>
  
  <pre><code>function registerUser($username, $fname, $email, $password, $region, $activation) {
      $uniqueSalt = uniqueSalt();
      $password = sha1($uniqueSalt . $password);
  
      $mysqli = mysqli_connect('localhost', 'root', '', 'database');
  
      if ($stmt = $mysqli-&gt;prepare("INSERT INTO `users` VALUES('', ?, ?, ?, ?, '$password', '$uniqueSalt', '$activation')") ) {
          $stmt-&gt;bind_param("ssss", $username, $fname, $email, $region);
          $stmt-&gt;execute();
          $stmt-&gt;close();
      } else {
          echo 'error preparing statement';
      }
  
      return mysqli_insert_id($mysqli);
  }
  </code></pre>
  
  <h2>Questions</h2>
  
  <p>It seems to work, but:</p>
  
  <p>1) Is this correct syntax for executing a prepared statement? </p>
  
  <p>2) I had included the file this function was in (call it function.php) with another file called init.php which previously defined the variable <code>$mysqli</code>. I found if I didn't include</p>
  
  <pre><code>$mysqli = mysqli_connect('localhost', 'root', '', 'database');
  </code></pre>
  
  <p>I would receive an error. Why did I have to redefine it inside the function?</p>
  
  <p>3) When I previously ended the function before I used prepped statements, with <code>return mysql_insert_id()</code> which worked fine, now I've found I have to use <code>mysqli_insert_id($mysqli)</code>.</p>
  
  <p>If I don't include <code>$mysqli</code> inside the parentheses I get the error <code>mysqli_insert_id() expects exactly 1 parameter, 0 given</code>. Why is this and why does it differ from what I had before?</p>
  
  <p>Cheers, 
  Luke. </p>