Jump to content

Function Issue


Kidrandom

Recommended Posts

Hi,

 

I have just started learning php and mysql and have been doing a few exercises.

 

I made a function to get all the information out of a table in a mysql database based on the id of a selected table item.

 

I'm having a bizarre issue when trying to use the function within an if statement. 

 

It works fine when I use it and assign to a variable in my page. Like so:

 

 

<?php

$table = get_table_by_id ($_GET ["subj"]); 
echo $table ["menu_name"];

?>

 

This gives me the menu name out of the table.

 

However when the same function is used within an if statement like so:

 

if (isset($_GET ["subj"])) {

	$sel_table = get_table_by_id ($_GET ["subj"]);

}
	else {
		$sel_table = NULL;
	}

 

I get the following error:

 

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in....

 

Which translates to:

 

No database selected

 

Here is the code used for the function:

 

function get_table_by_id ($name) {


	$query = "SELECT * " ;
	$query .= "FROM pages ";
	$query .= "WHERE id=" . $name . " ";
	$query .= "LIMIT 1";

		$result_set = mysql_query ($query);

		if (!$result_set) {
			die ("query failed " . mysql_error());

		}

		$array = mysql_fetch_array($result_set);


		return $array;

 

Why is this happening?

 

 

Link to comment
https://forums.phpfreaks.com/topic/228492-function-issue/
Share on other sites

I'm new to PHP so dont quote me on this but I would say that you can simplify this part:

 

$query = "SELECT * " ;		$query .= "FROM pages ";		$query .= "WHERE id=" . $name . " ";		$query .= "LIMIT 1";			

 

Down to something like:

 

$query = "SELECT * FROM productfeed WHERE name like '%$name%' LIMIT 0, 1";

 

So basically its in one line.

 

Try and build it up stages and resave each attempt.  Sometimes I had 16 files of the slightly different variations before I could move on.

Link to comment
https://forums.phpfreaks.com/topic/228492-function-issue/#findComment-1178173
Share on other sites

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.