Link to home
Start Free TrialLog in
Avatar of FairyBusiness
FairyBusinessFlag for United States of America

asked on

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

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??
Avatar of Greg Alexander
Greg Alexander
Flag of United States of America image

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

Try:
 <div id="info">
<?php echo bracelets(); ?>
</div><!-- end #info -->
Avatar of FairyBusiness

ASKER

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.
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??
Avatar of AnuarJamlus
AnuarJamlus

How many rows are you expecting to be returned from your select statement?
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 ?
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
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

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. . .
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
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?
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!
ASKER CERTIFIED SOLUTION
Avatar of AnuarJamlus
AnuarJamlus

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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!
Doing double queries when loading one page can quickly build up :)
It worked once I took the $ out like this:

  $content = $match['content'];

Thank you so much!!
Haha...  my bad... yes that's the correct way :P