Jump to content

recognizing outside variables in functions


V

Recommended Posts

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.  :wtf:

 

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  :-\

 

 

 

 

 

<?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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.