V Posted July 8, 2010 Share Posted July 8, 2010 I know that variables should be in the scope of a function and I think that can be achived with globals but I also know that using globals is a security treat. I've been reluctant to use functions for this reason but my coding is getting too dense and I need to make evrything more compact. So I attempted to make a fucntion but I get " Undefined variable" errors. For example I want to show all the posts that belong to a category. I wrote this function. function show_posts(){ $posts = array(); $sql = "SELECT * FROM posts WHERE category_id = '$category' ORDER BY post_date DESC"; $result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $posts_result2->fetch_assoc()) { $posts[$row->post_id] = $row->post_title; } return $posts; } and I tried to use it like this $post = (int)$_GET['post']; $category = (int)$_GET['category']; $posts = show_posts(); foreach ($posts as $key => $value){ echo $key; echo $value; echo "<br />"; } I get Undefined variable: connection in.. functions.php Call to a member function query() on a non-object in.. functions.php I have the DB connection and variables on my page but the function isn't picking them up. Do I have to write the DB connection and vars in every function I make? That just seems like a hassle :-\ Link to comment https://forums.phpfreaks.com/topic/207148-recognizing-outside-variables-in-functions/ Share on other sites More sharing options...
Mchl Posted July 8, 2010 Share Posted July 8, 2010 <?php function show_posts(MySQLi $connection, $category){ $posts = array(); $sql = "SELECT * FROM posts WHERE category_id = '$category' ORDER BY post_date DESC"; $result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $result->fetch_object()) { $posts[$row->post_id] = $row->post_title; } return $posts; } and use it like this: <?php $posts = show_posts($connection, $category); Link to comment https://forums.phpfreaks.com/topic/207148-recognizing-outside-variables-in-functions/#findComment-1083129 Share on other sites More sharing options...
V Posted July 8, 2010 Author Share Posted July 8, 2010 Mchl that's awesome! So I have to pass the vars in the function's parameters Thank you! Link to comment https://forums.phpfreaks.com/topic/207148-recognizing-outside-variables-in-functions/#findComment-1083143 Share on other sites More sharing options...
Mchl Posted July 8, 2010 Share Posted July 8, 2010 That's how it works, yes. Link to comment https://forums.phpfreaks.com/topic/207148-recognizing-outside-variables-in-functions/#findComment-1083146 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.