?
Solved

How to echo a variable from a function in my library to a different page?

Posted on 2011-04-25
18
Medium Priority
?
284 Views
Last Modified: 2012-05-11
Hi, on my bracelet.php page I am including my library which has this function:

function bracelets() {
	global $conn, $metals, $content;
	$query = "SELECT * FROM bracelets";
	$metal = $metals['name'];
	if(!isset($_GET['$metal'])) { 
		$query .= " WHERE featured = 1";
	}
	$result = mysql_query($query, $conn);
	confirm_query($result);

	$output = "";
	// These loops output the subject names with their corresponding pages underneath them
	while ($bracelets = mysql_fetch_array($result)) {
		$content = $bracelets['content'];
		$output .= "<a href=\"bracelet.php?item=" . urlencode($bracelets["filename"]) . "\">";
		$output .= "<img src=\"bracelets/" . $bracelets["filename"] . ".png\" />";
	}
	return $output;
}

Open in new window


I am trying to echo the content to fill a div:

<div id="info">
<?php echo bracelets($content); ?>
</div><!-- end #info -->

Open in new window


But its not working. Its just a blank.  Anyone know how to do this??
0
Comment
Question by:FairyBusiness
18 Comments
 
LVL 19

Expert Comment

by:Greg Alexander
ID: 35464430
Looks good to me... there may be an issue with the query try the attached and if you get results then it may just be your query:
function bracelets() {
       
        global $conn, $metals, $content;
        $query = "SELECT * FROM bracelets";
        $metal = $metals['name'];
        if(!isset($_GET['$metal'])) { 
                $query .= " WHERE featured = 1";
        }
        $result = mysql_query($query, $conn);
        confirm_query($result);

        $output = "test";
        // These loops output the subject names with their corresponding pages underneath them
        while ($bracelets = mysql_fetch_array($result)) {
                $content = $bracelets['content'];
                $output .= "<a href=\"bracelet.php?item=" . urlencode($bracelets["filename"]) . "\">";
                $output .= "<img src=\"bracelets/" . $bracelets["filename"] . ".png\" />";
        }
        return $output;
}

Open in new window

0
 
LVL 22

Expert Comment

by:Om Prakash
ID: 35464433
Try:
 <div id="info">
<?php echo bracelets(); ?>
</div><!-- end #info -->
0
 

Author Comment

by:FairyBusiness
ID: 35464462
Nope, neither worked.

I used var_dump($content)

and got this returned:  string(0) "" 

Perhaps I need to specify the content according to the filename that is selected??  I will try that.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:FairyBusiness
ID: 35464481
I tried this instead:

function bracelets() {
	global $conn, $metals, $content;
	$query = "SELECT * FROM bracelets";
	$metal = $metals['name'];
	if(!isset($_GET['$metal'])) { 
		$query .= " WHERE featured = 1";
	}
	$result = mysql_query($query, $conn);
	confirm_query($result);

	$output = "";
	// These loops output the subject names with their corresponding pages underneath them
	while ($bracelets = mysql_fetch_array($result)) {
		$output .= "<a href=\"bracelet.php?item=" . urlencode($bracelets["filename"]) . "\">";
		$output .= "<img src=\"bracelets/" . $bracelets["filename"] . ".png\" />";
		//$content = $bracelets['content'];
		
		$sql = "SELECT content FROM bracelets WHERE filename='" . $bracelets["filename"] . "'";
		$info = mysql_query($sql, $conn);
		confirm_query($info);
		$content = $info;
	}
	return $output;
}

Open in new window


But its not working correctly.  It returned this:

resource(28) of type (mysql result)
Resource id #28

I have no idea what that means.  Any suggestions??
0
 
LVL 1

Expert Comment

by:AnuarJamlus
ID: 35464584
How many rows are you expecting to be returned from your select statement?
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 35464756
The function bracelets you use does not take a parameter and you are trying to pass it to the function with <?php echo bracelets($content); ?>
why ?
0
 
LVL 1

Expert Comment

by:pzmatek
ID: 35465666
Hi,

The $content viariable you're passing in the function is local to the function. Inside the function there is another variable $content but global.
Please state a parameter in the function or remove the global $content variable.

Mat
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35466817
You might want to invest in this book.  It cannot make you a pro, but it could help you get some kind of foundation in PHP and MySQL.
http://www.sitepoint.com/books/phpmysql4/

There are a couple of things you can do to start trying to figure this out.  First, add this to the very top of all of your PHP scripts:

ini_set('display_errors', TRUE);
error_reporting(E_ALL);

Next, learn about the PHP online man pages.  All the functions are documented with examples and user-contributed notes!  Example:

$info = mysql_query($sql, $conn);

What might be in $info?  See the page here (hint: there is a return value from the query that may be TRUE, FALSE or Resource).
http://us3.php.net/manual/en/function.mysql-query.php

Some of your issues here may be due to "variable scope" which determines what variables are present in your global space, or your class methods, or functions.  You can learn more about variable scope here.
http://php.net/manual/en/language.variables.php

You already know how to use var_dump() and that is half the battle!  It's better for debugging because echo will simply produce a NULL string, whereas var-dump() will tell you the data type.  What's a data type and what data types are available to the PHP programmer?
http://php.net/manual/en/language.types.php

The code snippet shows how to do some of the basics in PHP and MySQL.  Every line matters, so if you do not completely understand what each line does, please post back with specific questions.  But first, go buy that book and read it from cover to cover.  The time you invest in that learning exercise will pay you back a hundredfold.

Good luck with your project, ~Ray
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// IMPORTANT PAGES FROM THE MANUALS
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES




// ESCAPING A DATA FIELD FOR USE IN MYSQL QUERIES
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATING AND SENDING A SELECT QUERY AND TESTING THE RESULTS
// MAN PAGE:http://php.net/manual/en/function.mysql-query.php
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
$num = mysql_num_rows($res);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/>$sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $num ROWS OF DATA ";
    echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
echo "<pre>\n"; // MAKE IT EASY TO READ
while ($row = mysql_fetch_assoc($res))
{
    // MAN PAGE: http://php.net/manual/en/function.var-dump.php
    var_dump($row);
}

Open in new window

0
 

Author Comment

by:FairyBusiness
ID: 35467213
Yeah, I do have this at the top of my page:

ini_set('display_errors' ,1);
error_reporting(E_ALL);


I made the variable global because then I thought I could access outside of the function.  I just want one thing to be returned and that's the content data from my database table.  I renamed them $info and $sql because I already had $query and $result, and it wasn't working when I used those names again.

Maybe I just have to have another function with a parameter. . .
0
 

Author Comment

by:FairyBusiness
ID: 35467382
Ok, I wrote another function:

function get_data() {
	global $conn;
	$query = "SELECT * FROM bracelets ";
	$result = mysql_query($query, $conn);
	confirm_query($result);
	while ($table = mysql_fetch_row($result)) {
		$query = "SELECT content FROM bracelets WHERE filename='" . $table["filename"] . "'";  // Line 118
		$result = mysql_query($query, $conn);
		confirm_query($result);
	}
	return $result;
}

Open in new window


but I am getting this error message:

Notice: Undefined index: filename in /hermes/web09c/b2950/moo.auroriellacom/includes/library.php on line 118

How can my filename come up undefined when its works perfectly fine in my original function??

function bracelets() {
	global $conn, $metals, $content;
	$query = "SELECT * FROM bracelets";
	$metal = $metals['name'];
	if(!isset($_GET['$metal'])) { 
		$query .= " WHERE featured = 1";
	}
	$result = mysql_query($query, $conn);
	confirm_query($result);

	$output = "";
	// These loops output the subject names with their corresponding pages underneath them
	while ($bracelets = mysql_fetch_array($result)) {
		$output .= "<a href=\"bracelet.php?item=" . urlencode($bracelets["filename"]) . "\">";
		$output .= "<img src=\"bracelets/" . $bracelets["filename"] . ".png\" />";
	}
	return $output;
}

Open in new window

Resource id #22
0
 
LVL 1

Expert Comment

by:AnuarJamlus
ID: 35467469
You still haven't answered my question, how many rows are you expecting to be returned from your SELECT statement. This will determine what code you should be using because at the moment you are returning an array of the result and not the result itself.

Also you should not be reusing the $result variable while in an array that already makes use of the same variable.

In any case why do you need to do a 2nd query on the same table? Would you not be able to get the content field value from your first query?
0
 

Author Comment

by:FairyBusiness
ID: 35467570
Ok, I only want one row.  I got rid of that other stuff. I had modeled this function after another function but after reading what you said I think much of it was not neccessary.

I changed it to this:

function get_data() {
	global $conn;
	if(isset($_GET['item'])) {
		$filename = $_GET['item'];
	}
	$query = "SELECT content FROM bracelets WHERE filename='" . $filename . "'";
	$result = mysql_query($query, $conn);
	confirm_query($result);
	var_dump($result);
	return $result;
}

Open in new window


It didnt work so I used a var_dump and I got this:

resource(13) of type (mysql result) Resource id #13

I can't figure out why its acting like I don't have these things in my database table.  I keep going to look at it in my phpmyadmin to if its really there!
0
 
LVL 1

Accepted Solution

by:
AnuarJamlus earned 2000 total points
ID: 35467689
Try changing it to

function get_data() {
      global $conn;
      if(isset($_GET['item'])) {
            $filename = $_GET['item'];
      }
      $query = "SELECT content FROM bracelets WHERE filename='" . $filename . "'";
      $result = mysql_query($query, $conn);
      confirm_query($result);
      while ($match = mysql_fetch_array($result)){
                  $content = $match['$content'];
        }
      return $content;
}
0
 

Author Comment

by:FairyBusiness
ID: 35467776
Hold on, my server isn't even working right now.  Apparently, I exceeded the 'max_questions' resource (current value: 75000) this morning.  Have no idea how, only been on here for less than an hour lol

I am talking with technical support, once I get that settled I'll post how the results went!
0
 
LVL 1

Expert Comment

by:AnuarJamlus
ID: 35467800
Doing double queries when loading one page can quickly build up :)
0
 

Author Comment

by:FairyBusiness
ID: 35467829
It worked once I took the $ out like this:

  $content = $match['content'];

Thank you so much!!
0
 
LVL 1

Expert Comment

by:AnuarJamlus
ID: 35467970
Haha...  my bad... yes that's the correct way :P
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses
Course of the Month13 days, 14 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question