Jump to content
Nematode128

Prepared Statements in Query

Recommended Posts

I'm trying to use a prepared statement inside a function and it's giving me some trouble. I have an RPG game I'm working on an want a function to include on pages that tells a user to collect their egg from the professor if they haven't already received it yet. When I try to call the function on the page these are the errors I get:

Notice: Undefined variable: link in /home/evoarena/public_html/Dev/functions.php on line 23

Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/evoarena/public_html/Dev/functions.php:23 Stack trace: #0 /home/evoarena/public_html/Dev/login.php(59): egg_received() #1 {main} thrown in /home/evoarena/public_html/Dev/functions.php on line 23

$link is defined in a db config file and on the page I'm trying to call the function I have the files required like this so I'm wondering why it still thinks link is an undefined variable 

require "config.php";
require "functions.php";

Function Code:

function egg_received () {

  if (isset($_SESSION['username'])) {
     
    $username = $_SESSION['username'];
    $query = "SELECT egg_received FROM users WHERE username=?";
    if ($stmt = $link->prepare($query)) {
    
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $egg = $result->fetch_array();
    
    if ($egg['egg_received'] == '0') {
    
      echo "<div class='alert alert-primary' role='alert'>
      Oh well hello there! It appears the professor is looking for you today!<br><a href='../world/professor.php'>Visit the Professor</a>
      </div>";
      
      require "footer.php";
      exit;
      
    }

} else {
    
     $error = $link->errno . ' ' . $link->error;
    echo $error;
}
}
}

 

Share this post


Link to post
Share on other sites

Variables defined outside of functions are not available inside of functions.

Pass $link as a function argument.

Share this post


Link to post
Share on other sites
35 minutes ago, requinix said:

Variables defined outside of functions are not available inside of functions.

Pass $link as a function argument.

So I'd just want this?

function egg_received($link) {
//contents
}

or would I need to add more code inside the actual function

Share this post


Link to post
Share on other sites

Since your code is already written to assume there is a $link variable it can use, and since the name of the parameter there is also "link", you don't need to do anything else.

At least not anything inside the function. Since it requires an argument, you do have to pass that value into it when you call the function. Which happens to be a variable also named $link.
Note that's two different variables: the one on the outside is separate from the one on the inside, and they just happen to be named the same thing. Just like with people.

Share this post


Link to post
Share on other sites
5 hours ago, requinix said:

Since your code is already written to assume there is a $link variable it can use, and since the name of the parameter there is also "link", you don't need to do anything else.

At least not anything inside the function. Since it requires an argument, you do have to pass that value into it when you call the function. Which happens to be a variable also named $link.
Note that's two different variables: the one on the outside is separate from the one on the inside, and they just happen to be named the same thing. Just like with people.

Gotcha, that makes sense. Thank you. I'm having trouble using fetch array in this other function though. This function will be to show the user notifications however fetch array is giving me this error: "Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_array() in /home/evoarena/public_html/Dev/functions.php:69 Stack trace: #0 /home/evoarena/public_html/Dev/index.php(5): notifications(Object(mysqli)) #1 {main} thrown in /home/evoarena/public_html/Dev/functions.php on line 69" where line 69 is 

      $news_user = $news_stmt->fetch_array();

 

The functions are basically copy and pasted with variables and th query changed as needed so why does this function provide me with a fetch array error?

 

function notifications($link) {

  if (isset($_SESSION['username'])) {
  

    $news_query = "SELECT news_read FROM users WHERE username=?";
    
    if ($news_stmt = $link->prepare($news_query)) {
    
      $username = $_SESSION['username'];
      $news_stmt->bind_param("s", $username);
      $news_stmt->execute();
      $news_result = $news_stmt->get_result();
      $news_user = $news_stmt->fetch_array();
      
      if ($news_user['news_read'] == '0') {
      
          echo "<div class='alert alert-primary alert-dismissible' role='alert'>
        <center><button type='button' class='close' data-dismiss='alert'>&times;</button>There is a new post on the <a href='http://www.pereia.net/Dev/news/index.php'>Updates</a> page
        </center></div>";
      
      }
      
    } else {
    
       $error = $link->errno . ' ' . $link->error;
       echo $error;

    }

  }
}

 

Share this post


Link to post
Share on other sites

Your result set was retrieved from the statement object.  You fetch rows from the result, not the statement.

 

      $news_result = $news_stmt->get_result();
      $news_user = $news_result->fetch_array();

 

Share this post


Link to post
Share on other sites
1 hour ago, gizmola said:

You fetch rows from the result, not the statement.

That is one of the prime reasons why many developers prefer PDO to mysqli.

With PDO it doesn't matter whether you use query() or prepare(). The resulting objects in both cases have exactly the same methods.

With mysqli there are two distinct sets of methods that you must use to process results depending on whether you used query (which gives a result object) or prepare (which gives a statement object).

Share this post


Link to post
Share on other sites
3 hours ago, Nematode128 said:

The functions are basically copy and pasted with variables and th query changed as needed

except that you didn't need to change the variable names and when you did, you mixed them up.

within the scope of the function code, you have a SELECT sql query statement, you are preparing it, executing it, and fetching a row of data from it. why not use $query, $stmt, $result, and $row for variable names for this operation regardless of the meaning of the data that is being queried for and save the time and trouble, since there's a mistake now, it took you to push a bunch of keys on a keyboard?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.