Link to home
Start Free TrialLog in
Avatar of MisterHamper
MisterHamperFlag for Denmark

asked on

Remove item from PHP with button from my site?

Hey. I have here an early version of my PHP-script. When it runs, it gives me a couple random items. Like this
"gyn
taby
watta
part"

I have worked alot on it the last couple days, but now I am struck and don't know how to continue. What I would like to do, is add a button (could be just the letter X) to each of the items, that when pressed will delete that file from the php file

In my mind it would probably look something like this:
foreach ($my_items as $my_item => $my_amount)
{
   echo "X(if pressed:Delete $priority["$my_item"], delete $amount["$my_item"]) $my_item<br />";
}

How should I go about doing that? Thanks alot for your help! :D
Avatar of MisterHamper
MisterHamper
Flag of Denmark image

ASKER

Here is the early code. Its the DATA STRUCTURE and SHOW THE RESULTS i am talking about, i guess :-)
<?php // RAY_item.php
error_reporting(E_ALL);
echo "<pre>";
 
// NEW DATA STRUCTURE
$priority["gyn"]   = 60;   $amount["gyn"]   = 50;
$priority["hels"]  = 30;   $amount["hels"]  = 20;
$priority["mice"]  = 15;   $amount["mice"]  = 50;
$priority["part"]  = 18;   $amount["part"]  = 30;
$priority["taby"]  = 23;   $amount["taby"]  = 40;
$priority["boom"]  = 24;   $amount["boom"]  = 20;
$priority["watta"] = 35;   $amount["watta"] = 30;
$priority["hessa"] = 20;   $amount["hessa"] = 30;
 
 
// ASSIGN MAXIMUM TOTAL amount FOR ITEMS
$max_amount = 100;
 
 
// FREQUENCY OF THE itemS ITEMS BASED ON PRIORITY - A LARGE ARRAY
$items = array();
foreach ($priority as $item => $number)
{
   while ($number > 0)
   {
      $number--;
      $items[] = $item;
   }
}
 
// RANDOMIZE THE LARGE ARRAY
shuffle($items);
 
// CHOOSE THE itemS
$my_items  = array();
$my_amount = 0;
foreach ($items as $item)
{
 
// CHOOSE ONLY UNIQUE itemS
   if (in_array($item, $my_items)) continue;
 
// NOT MORE THAN MAX amount
   $my_amount = $my_amount + $amount["$item"];
   if ($my_amount > $max_amount) break;
 
// SELECT THIS item
   $my_items["$item"] = $item;
}
 
// ITEMIZE THE amountS OF THESE itemS
foreach ($my_items as $item => $x)
{
   $my_items["$item"] = $amount["$item"];
}
 
// SHOW THE RESULTS
foreach ($my_items as $my_item => $my_amount)
{
   echo "$my_item<br />";
}
 
}
echo item();
?>

Open in new window

ajax will help u out with that.

or u can have somthing like :
// SHOW THE RESULTS
foreach ($my_items as $my_item => $my_amount)
{
    echo "<a href=\"delete.php?recordID=$ID\"><img src=\"delete.gif\" border=\"0\"></a>";
    echo "$my_item<br />";
}

Open in new window

Yes, if you want it so that as soon as you click on the x, it'll delete it without reloading the page, you can look into using ajax (or even a framework that sets up the ajax for you, such as prototype, or my favourite, jquery).

However, this depends on what you want to do with the page. Is this data that needs to be manipulated and saved? If so, I would recomend using a database, or storing these arrays in a seperate file, as editing a php file with functions and stuff in it, can become disasterous. (You have to specify what line to delete to delete that array value from the file, and if you add just one line to the top of the file, that delete could wreck the script).
If, however, you're just sorting the array and displaying it, and then every time you want to reload the page, it regenerates the list with the same content, it would be a simple javascript DOM manipulation. Would you mind giving us a quick explenation of how this code is going to be used, so we can give a more customized aproach to do this?
He's a quick example of what I mean about the DOM manipulation. Basically we encase the display in a <span> with an ID, and then we make an <a> with an onclick() set to make the span invisible:

//Starting at line 57 of your code:
 
// SHOW THE RESULTS
$i = 0;
foreach ($my_items as $my_item => $my_amount)
{
   echo "<span id=\"{$i}\">$my_item <a href=\"#\" onclick=\"document.getElementById('{$i}').style.display='none'; return false;\"> X </a><br /></span>";
   $i ++;
}

Open in new window

Hey, thanks for the answer! I appreciate it
Let me explain further, what it is I want to do: Well, I have an user management system stored on my MySQL (its called "Login - Redirect 1.31"). So storing the files in a database would be nice, for the individual user. It is meant for an user, that is signed on, that he can remove an item from the script if he is not satisfied with that item or hates the item :-) So it will be gone forever, also the next time he signs on. The php script doesn't have to reload right after he have removed the item, if it is gone the next time he reloads the page, that's fine too!

And then each individual user can have their own list of items, that have been removed from the default script. :)
I am sorry to respond, Vee_Mod, but I probably have to clarify a little more.

I have this homepage here.
http://distended-stomach.com/autodiet/
It randomly generates some items. And I want to add an X infront of each item, so when you click on that X for that item, it will remove that item from the script so it won't ever be able to generate that. And in order to remember that file have been removed, it should be stored on the users "settings" (or how it works, so some users might choose to remove item A, some will want to remove both item A+D+E and some won't remove anything)
I hope you understand.
I don't really know where to start coding it from here.
Okay, so is the code that you are currently using (where you put the information in arrays, rather than pulling from the database) just for testing?
If so, we can do something like what gawai said, where when you click on the button, it "reloads" the page (actually it's a link, and it takes you to the same page), and deletes when it "reloads". This can be done in ajax without "reloading" the page, but it's a bit more work, so if you need to know how it's done, I can help you, but this method is more common, and less likely to suffer from the javascript differences between browsers.

So let's assume that instead of using those two arrays, we have a mysql table called "items", with five columns: id (a unique ID to select the row in the table), name, priority, number, and userid (the ID of row in the "users" table that your login script uses, of the user whose list is currently being viewed).

Let's also assume that you're using a session variable called $_SESSION['userid'] with the userid of the person currently logged in.

The page will pull the information from the table, sort it, and display it, with an "x" beside the item. When the "x" is clicked, it loads the page again with a $_GET variable (called "delete") set to the ID of the row to delete.
At the top of the same page, PHP will check if the "delete" variable is set, and if it is, then it will [permenantly] delete the item from the database (then it will go on to pull the data from the table). Here's a modified version of your code (I commented out a lot of it, rather than simply deleting it, so you may find it helpful to use an editor with colour-coding for comments):
<?php // RAY_item.php
 
 
 
/*
* This From here down to line 19 is where the file is deleted from the database.
* You should skip down to line 26 before reading this, to see how the data is pulled and displayed. 
* Check this once you've finished this part
*/
if (isset($_GET['delete']) && is_numeric($_GET['delete']))
{
	//Some simple security to check that the user deleting is the user who owns the file. Otherwise anyone could typing in www.domain.com/RAY_item.php?delete=[any user's file ID]
	if (mysql_num_rows(mysql_query("SELECT id FROM items WHERE id='".mysql_real_escape_string($_GET['delete'])."' AND userid='".mysql_real_escape_string($_SESSION['userid'])."' LIMIT 1")) > 0)
	{
		mysql_query("DELETE FROM items WHERE id='".mysql_real_escape_string($_GET['delete'])."' LIMIT 1"); //Delete from the database
		//If you need to delete a physical file from the server or something, that can go in here as well.
		print "File has been deleted";
	}
}
 
 
 
 
 
 
error_reporting(E_ALL);
echo "<pre>";
 
// ASSIGN MAXIMUM TOTAL amount FOR ITEMS
$max_amount = 100;
 
// NEW DATA STRUCTURE
//Pull the data from the table (limited to the max_amount)
$query = mysql_query("SELECT * FROM items WHERE user='".mysql_real_escape_string($_SESSION['userid'])."' LIMIT {$max_amount}");
 
//Loop through each row in the query, and place it in the $items[] array; also checking for unique items
$items = array();
while ($row = mysql_fetch_array($query))
{
	if (!inarray($row, $items)) //Check to see if this is a duplicate
	{$items[] = $row;} //We set the next $items[] array index to an array of the returned rows from the DB
}
 
/*
	I've commented these out, because we no longer need it, as the above line puts everything in an array,
	and I moved shuffle($items) lower
	// FREQUENCY OF THE itemS ITEMS BASED ON PRIORITY - A LARGE ARRAY
	$items = array();
	foreach ($priority as $item => $number)
	{
		 while ($number > 0)
		 {
				$number--;
				$items[] = $item;
		 }
	}
 
	// CHOOSE THE itemS
	$my_items  = array();
	$my_amount = 0;
	foreach ($items as $item)
	{
	 
	// CHOOSE ONLY UNIQUE itemS
	//This is done when the $items array is created
		 if (in_array($item, $my_items)) continue;
	 
	// NOT MORE THAN MAX amount
	//This is done in the query to pull the items
		 $my_amount = $my_amount + $amount["$item"];
		 if ($my_amount > $max_amount) break;
	 
	// SELECT THIS item
		 $my_items["$item"] = $item;
	}
	 
	// ITEMIZE THE amountS OF THESE itemS
	foreach ($my_items as $item => $x)
	{
		 $my_items["$item"] = $amount["$item"];
	}
*/
 
// RANDOMIZE THE LARGE ARRAY
shuffle($items);
 
// SHOW THE RESULTS
//foreach ($my_items as $my_item => $my_amount) // I commented this out, in favour of using the original items array
foreach ($items as $row) //This returns $row, which is an array of each row pulled from the database
{
	//Each index in $row is a string of the column name
   echo "{$row['name']} <a href=\"RAY_item.php?delete={$row['id']}\">x</a><br />";
}
 
}
echo item();
?>

Open in new window

I'm sorry, I started writing my comment before your comment, so the code I provided assumes that a user creates (and adds to) their own list, rather than you create the list and the user removes from that list.
If you'd like, I can re-write it to allow for that instead (the technique is a little bit different, but the same basic concept).  If so, are you planning to have the default items in a database eventually, rather than a hard-coded array? That would make things easier for you in the future, and make the code a lot simpler to work with.
Oh my thank you so much for helping out here! :D
I have read it through it carefully now. What I understand, is that I should create a new MySQL database and call it items and let it have 5 rows (id, name, priority, number (is that the previously "amount"?), and userid) and then write all my items in that MySQL database?
While I also still keep my old database with my users, with their userid, password and e-mail?
Fx with gyn it would look like this: "ID 9 | Gyn | 50 | 150 | Userid(?)"?
How do I write (or get?) the userID? How does that work?
I hope you can help me out here a little more, with my questions!
And shouldn't the script have some sort of line where it logs into the MySQL?

Cheers! Thanks you again
I also wrote my comment before reading your other comment. :)

Yes I would like that alot, because I do indeed think that is how it is going to work. I was thinking it would be pretty neat to have all the items in a database-array actually too! Please, will you do that? :-)
In the MySQL I have for the users now, there is 3 fields:
ID (       mediumint(9) - null=no, extra=auto_increment)
username (varchar(60) - null=yes)
password (varchar(60) - null=yes)

If you need that information!
There is by the way around 5 of those "random" PHP-scripts (frame1.php, frame2.php etc) on my site, each with sligthly different items. I don't know if that would complicate it. But I appreciate all your help!
Hi, sorry it took so long to reply. Here's what I would recomend doing:
Create a table for items, and a table for ignored_items.

items will have five columns: id, name, quantity, amount (I'm not sure why I wrote this as "number" last time) and page
The first four as the same values as before, but the "page" is what page to display the items on (frame1, frame2, etc). What I like to do is have this page as a number (rather than a string with the file name), and just have one page (frame.php), and then have a GET variable for what page it is (frame.php?page=1). It's up to you if you want it as a string of $_SERVER['PHP_SELF'], or even keep the database as a number, but in each page, manually set the query to load "WHERE page='1'", etc.

The ignored_items would be the table where it stores what the user ignores, with the columns:
id, item (id of the item in the items table that you doesn't want to display), and userid (id of the row of the user in your users table)

Now I'll modify the code I already gave you. The only real difference is that the query to pull the data to be displayed, it only pulls the items that aren't in the ignore_items table for the current user. Then, when $_GET['delete'] is set, it adds a row to ignored_items for the user, rather than delete it from the items table.

This time I'll clean up the code, so instead of commenting out your old code, I'll just write it out nicely.  Also, when deleting, there's not a whole lot of security required, because the query adds a row that is defined for the user that is currently logged in.
<?php // RAY_item.php
/*
* Not really deleting an item, but adding it to the table of ignored items
*/
if (isset($_GET['delete']) && is_numeric($_GET['delete']))
{
	//Check if this item is already ignored (in case the user refreshed, or visited this link from the history or bookmark or something)
	if (mysql_num_rows(mysql_query("SELECT id FROM ignored_items WHERE item='".mysql_real_escape_string($_GET['delete'])."' AND userid='".mysql_real_escape_string($_SESSION['userid'])."' LIMIT 1")) > 0)
	{
		mysql_query("INSERT INTO ignored_items (item, userid) VALUES (id='".mysql_real_escape_string($_GET['delete'])."', '".mysql_real_escape_string($_SESSION['userid']."'"); //Add to the ignore table
		//If you need to delete a physical file from the server or something, that can go in here as well.
		print "File has been deleted";
	}
}
 
 
 
 
 
 
error_reporting(E_ALL);
echo "<pre>";
 
// ASSIGN MAXIMUM TOTAL amount FOR ITEMS
$max_amount = 100;
 
// NEW DATA STRUCTURE
//Pull the data from the table (limited to the max_amount)
$query = mysql_query("SELECT * FROM items WHERE NOT EXISTS (SELECT id FROM ignored_items WHERE userid='".mysql_real_escape_string($_SESSION['userid'])."' AND item=items.id) AND page='".mysql_real_escape_string($_GET['page'])."' AND  LIMIT {$max_amount}");
 
//Loop through each row in the query, and place it in the $items[] array; also checking for unique items
$items = array();
while ($row = mysql_fetch_array($query))
{
	if (!inarray($row, $items)) //Check to see if this is a duplicate
	{$items[] = $row;} //We set the next $items[] array index to an array of the returned rows from the DB
}
 
 
// RANDOMIZE THE LARGE ARRAY
shuffle($items);
 
// SHOW THE RESULTS
foreach ($items as $row) //This returns $row, which is an array of each row pulled from the database
{
	//Each index in $row is a string of the column name
   echo "{$row['name']} <a href=\"RAY_item.php?delete={$row['id']}\">x</a><br />";
}
 
}
echo item();
?>

Open in new window

Thank you alot for that! That looks pretty neat, will really help my homepage become better.
Is "quantity" the same as the previous "priority"?

I hope you can help me with those two small things too. :-)
How do the RAY_items.php know which database to connect to? All the PHP files that connects to MySQL I have seen, have a text for DB_name, server, DBusername and DBuserpassword, but this doesn't seem to have that.

This MySQL is still pretty new for me. I have created those in MySQL, for "items" (the uploaded picture). Does this look right? How do I add my items and their weight to those rows then? I have tried every button in there :( I would think one of them would bring up a table like this or something, where I would be able to write everything in, but I can't find anything in there:

| id | name | quantity | amount | page |
| ... | ........ | ............. | ............ | ........ |
| ... | ........ | ............. | ............ | ........ |
| ... | ........ | ............. | ............ | ........ |
Z-29.jpg
I just looked at the script some more again. I still have not figured out how to do this in MySQL, but there is some more that is confusing me too.

"have a GET variable for what page it is (frame.php?page=1). It's up to you if you want it as a string of $_SERVER['PHP_SELF'], or even keep the database as a number, but in each page, manually set the query to load "WHERE page='1'", etc."

What is "$_SERVER['PHP_SELF']" and how would it change things?
How would I make a PHP script with a GET variable for what page it is?
Do the script know automatically what user is signed on? Or should I edit some code in my "login.php" script or some of the other PHP-files from the user management system?

Thanks you will get some points soon either way, FirestormX for your help before :-)
Hi, sorry for the late reply again.
1) Before I forget, the ID column should be NOT NULL and AUTO_INCREMENT; that way mysql automatically increments it without you having to do it yourself.

2) "quantity" is the same a "priority". I'm sorry I always get the names of your columns mixed up. You can name the columns whatever you want them to be.

3) The script should have a login to the DB area; sorry I didn't answer that question (I know you asked it earlier). It would probably be the same DB that you connect to with the user script. I would put the items table in the same database as the users table.  If you put the items table in the same databsae as your users table, you can use the same DB connect code that you used for your login php file.

4) To enter an item into the table, you can either use the "insert" button in phpmyadmin, or a SQL query (if you want to make your own back-end) like this:
INSERT INTO items (name, quatity, amount, page) VALUES ('test', '13', '37', '1')

5) $_SERVER['PHP_SELF'] is a variable that PHP defines as the name of the current php script. I suggested this if you have to use frame1.php, frame2.php, etc (with the different file names), rather than simply having one php script (frame.php) with a GET variable to define the page (like frame.php?page=1). This would change the way the script works, because in the code I wrote out, the "page" is defined as an integer, and uses the $_GET['page'] variable. However, if you were to use $_SERVER['PHP_SELF'], it would return "frame1.php", rather than $_GET['page'] returning "1". That means that your "page" column would hae to say "frame1.php", rather than "1". Using numbers just makes things much more flexible.

6) The script kind of automatically knows if you're logged in; it uses $_SESSION['userid'] to tell the ID of the user, from your "users" table.  In your login.php page, when the user succesfully logs in, just have it set $_SESSION['userid'] to the ID of the user's row. If you need help about that, go ahead and post your login.php script and I'll help point out where to set it.
Thank you for the answer!
I have now been able to add some of my items to my row "items", and have created "deleted_items" with the same names and values as "items". They are all in the same database as my login.
But there is now a problem. There was some problems with the script with missing curlets and braces, but I think I figured that out. But now the problem is that it gives me this error message when I have signed on and am in my Members Area (and the exact same message when I am not signed on and am just trying the demo version of my site):

"Warning:  asort() expects parameter 1 to be array, null given in /home6/distende/public_html/autodiet/RAY_item.php on line 33

Warning:  Invalid argument supplied for foreach() in /home6/distende/public_html/autodiet/RAY_item.php on line 35

Notice:  Undefined variable: _SESSION in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'distende'@'localhost' (using password: NO) in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Notice:  Undefined index:  page in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'distende'@'localhost' (using password: NO) in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_query() [function.mysql-query]: Access denied for user 'distende'@'localhost' (using password: NO) in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home6/distende/public_html/autodiet/RAY_item.php on line 44

Warning:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home6/distende/public_html/autodiet/RAY_item.php on line 48"


For the error on line 33 and 35, It is because of this script I used before and need to use again.

"// ASSIGN MAXIMUM TOTAL quantity FOR ITEMS
$max_quantity = 5000;
 
// COMPUTE MINIMUM quantity FOR THREE ITEMS - SIMULATE $min_quantity = $quantity[0] + $quantity[1] + $quantity[2];
$min_quantity = 4500;
asort($quantity); //LINE 33 HERE
$kount = 3;
foreach ($quantity as $item => $number) //LINE 35 HERE
{
   $kount--;
   $min_quantity = $min_quantity + $number;
   if (!$kount) break;
}


Before with my script, there was the value "number" infront of each item. I am thinking that it should be the new "id" from MySQL, but replacing "number" with "id" still gives the exact same error message. Any ideas? And what about the other error messages? It seems like it can't figure out where it should loign or something, I am not really sure.

I have no login.php. The login-system I use, uses a HTML-input box on my front page, and then after having entered details, it goes to redirect.php which then check to see if it was correct login, and then redirects user to another page (fx index2.php). If the login is faulty, or you try to go to index2.php without having signed in, it automatically transports you to no_access.html where you can login with the HTML-input box. So I am not really sure which php file you need from your answer to question #6. :-(
(the loginform: "<FORM METHOD="POST" ACTION="redirect.php">")

---But there is a log_login.php script, it does this "This is a server-side page that records the login information to the log_login table." Maybe that is the one you would need to look at.

Sorry my comment got a little long. I hope you can help with my troubles :-)
<? //loglogin.php
 
session_start();
 
//include config file
include ('config.php');
 
//sets date and time variables
$last = gmdate("Y-m-d");
$time = gmdate("H:i", time() + $zone);
 
$viewer = $HTTP_USER_AGENT;
 
//checks to see if the browser the user is using is determinable
$browser = "unknown";
if (preg_match("/Netscape/", $viewer))
{
	$browser = "Netscape";
}
else if (preg_match("/Opera/", $viewer))
{
	$browser = "Opera";
}else if (preg_match("/Firefox/", $viewer))
{
	$browser = "FireFox";
}else if (preg_match("/MSIE/", $viewer))
{
	$browser = "Internet Explorer";
}
 
//checks to see if the OS the user is using is determinable
$platform = "unknown";
if (preg_match("/Windows NT/", $viewer))
{
	$platform = "Windows";
}
else if (preg_match("/Windows CE/", $viewer))
{
	$platform = "Windows PPC";
}
else if (preg_match("/Linux/", $viewer))
{
	$platform = "Linux";
}
else if (preg_match("/Mac/", $viewer))
{
	$platform = "MAC";
}
 
//make the connection to the database
$connection = @mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = @mysql_select_db($db_name,$connection)or die(mysql_error());
		
//build and issue the query
$sql ="INSERT INTO log_login VALUES
	('$_SESSION[user_name]', '$last', '$time', '$REMOTE_ADDR', '$platform', '$browser')";
$result = @mysql_query($sql,$connection) or die(mysql_error());
 
 
?>

Open in new window

This is the complete RAY_item.php I used, so you can see each line and where the errors was.

Thanks again :-)
<?php // RAY_item.php
function RAY_item() {
/*
* Not really deleting an item, but adding it to the table of ignored items
*/
if (isset($_GET['delete']) && is_numeric($_GET['delete']))
{
        //Check if this item is already ignored (in case the user refreshed, or visited this link from the history or bookmark or something)
        if (mysql_num_rows(mysql_query("SELECT id FROM ignored_items WHERE item='".mysql_real_escape_string($_GET['delete'])."' AND userid='".mysql_real_escape_string($_SESSION['userid'])."' LIMIT 1")) > 0)
        {
                mysql_query("INSERT INTO ignored_items (item, userid) VALUES (id='").mysql_real_escape_string($_GET['delete'])."', '".mysql_real_escape_string($_SESSION['userid']."'"); //Add to the ignore table
                //If you need to delete a physical file from the server or something, that can go in here as well.
                print "File has been deleted";
        }
}
 
 
 
 
 
 
error_reporting(E_ALL);
echo "<pre>";
 
// SUBMIT POST
if(!isset($_GET['weight'])){$weight = "2000";}else{$weight = $_GET['weight'];}
 
// ASSIGN MAXIMUM TOTAL quantity FOR ITEMS
$max_quantity = ($weight/2)+35;
 
// COMPUTE MINIMUM quantity FOR THREE ITEMS - SIMULATE $min_quantity = $quantity[0] + $quantity[1] + $quantity[2];
$min_quantity = ($weight/2)-35;
asort($quantity);
$kount = 3;
foreach ($quantity as $item => $number)
{
   $kount--;
   $min_quantity = $min_quantity + $number;
   if (!$kount) break;
}
 
// NEW DATA STRUCTURE
//Pull the data from the table (limited to the max_quantity)
$query = mysql_query("SELECT * FROM items WHERE NOT EXISTS (SELECT id FROM ignored_items WHERE userid='".mysql_real_escape_string($_SESSION['userid'])."' AND item=items.id) AND page='".mysql_real_escape_string($_GET['page'])."' AND  LIMIT {$max_quantity}");
 
//Loop through each row in the query, and place it in the $items[] array; also checking for unique items
$items = array();
while ($row = mysql_fetch_array($query))
{
        if (!inarray($row, $items)) //Check to see if this is a duplicate
        {$items[] = $row;} //We set the next $items[] array index to an array of the returned rows from the DB
}
 
 
// RANDOMIZE THE LARGE ARRAY
shuffle($items);
 
// SHOW THE RESULTS
foreach ($items as $row) //This returns $row, which is an array of each row pulled from the database
{
        //Each index in $row is a string of the column name
   echo "{$row['name']} <a href=\"RAY_item.php?delete={$row['id']}\">x</a><br />";
}
 
}
echo RAY_item();
?>

Open in new window

Is the code you posted the complete ray_item.php? Or is there more being processed here? (For example, is there an index.php, and the index include()s this file?) For example, I don't see a part for the database connection part of this code.
Most of the errors that you are getting, refer to an inability to connect to the database.
You also need to have session_start() at the very top of the document. session_start() is what allows the global $_SESSION[] array to be used in the page.  Also, the login.php I was refering to would be your redirect.php. If you are unsure of where to set $_SESSION['userid'], you could post your redirect.php, and I could take a look at it.

From the looks of it, your loglogin.php script has the session_start() and the session_start() in it. If you look at line 3 of loglogin.php, you'll see that you can put session_start() at the very top, and then 6 include()s the config.php file, which I assume has your DB login info, then down on line 51 and 52, you can see that it connects to the database.
You can copy and past these four lines (3, 6, 51, 52) into the top of your ray_item script, and it should clear up most of your errors.

So let's take a look at the errors:
The first error is regarding the asort($quantity) on line 33. It doesn't look like $quantity gets defined anywhere before doing the asort(), so therefore, asort() doesn't have anything to work with. Is $quantity a $_GET[] variable? If so, you will need to define it as $_GET['quantity'], rather than $quantity.
The second error about the foreach() on line 35 is the same problem; $quantity is not defined, so foreach() cannot work with it.

The third error, about the undefined variable $_SESSION, is due to session_start() not being called at the begining of the script. This will go away once session_start() is called.

All the rest of the errors, from error 4 down, should be fixed once you connect to the database.

So add this code into the very top of your ray_item.php script, and then define $quantity (I'm not sure what data you want to put into $quantity; is it from $_GET, or something you wanted to pull from your database?), and the errors should go away:
session_start();
 
//include config file
include ('config.php');
 
//make the connection to the database
$connection = @mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = @mysql_select_db($db_name,$connection)or die(mysql_error());

Open in new window

Hello again. That is how the RAY_item.php looks, i copy-pasted it all. But yes, on my site there is an index.php that have several iframes with RAY_item.php inside them. The $_GET is an input-box on my index.php where you enter an amount and it then reloads the scripts with that value (it was working fine before, so I assume it will still be working)

I have added this to the top of my RAY_item.php

"<?php

session_start();
 
//include config file
include ('config.php');
 
//make the connection to the database
$connection = @mysql_connect($distende_automateddiet, $distende_automat, $my password here) or die(mysql_error());
$db = @mysql_select_db($db_name,$connection)or die(mysql_error());

// RAY_item.php
function RAY_item() {"

Does that look right? There is now no other error messages except this one

"Access denied for user 'distende'@'localhost' (using password: NO)"

Why is that? I am sure I have written the right password and username and databasename

(Oh, and what should I write here: ($db_name,$connection)?)

About $quantity, that is how the script was working before. (see Code Snippet). It is working something like this before:
it takes 1 "random"(?) item (some items have a higher chance of getting selected than others), and then it checks to see how if the current weight is between minimum and maximum weight. If it is below minimum weight, it takes a new item, and checks if those two items is now between minimum and maximum weight. If it is, it stops the script and displays the result. If it is not, it takes a new item and checks again. And so on.

Thanks for your help!
// DATA STRUCTURE
$priority["item one"]  = 50;   $weight["item one"]  = 150;
$priority["item two"]  = 50;   $weight["item two"]  = 150;
$priority["item three"]  = 25;   $weight["item three"]  = 80;
$priority["item four"]  = 15;   $weight["item four"]  = 10;
$priority["item five"]  = 25;   $weight["item five"]  = 120;
$priority["item six"]  = 20;   $weight["item six"]  = 90;
 
// SUBMIT POST
if(!isset($_GET['amount'])){$amount = "2000";}else{$amount = $_GET['amount'];}
 
// ASSIGN MAXIMUM TOTAL WEIGHT FOR ITEMS
$max_weight = ($amount*5/30)+35;
 
// COMPUTE MINIMUM WEIGHT FOR THREE ITEMS - SIMULATE $min_weight = $weight[0] + $weight[1] + $weight[2];
$min_weight = ($amount*5/30)-35;
asort($weight);
$kount = 3;
foreach ($weight as $item => $number)
{
   $kount--;
   $min_weight = $min_weight + $number;
   if (!$kount) break;
}

Open in new window

Oh and this is the redirect.php
I haven't toyed with that one before
<? //redirect.php
 
//prevents caching
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter();
 
session_start();
 
//clear session variables
session_unset();
 
 
//require the functions file
require ("config.php");
require ("functions.php");
 
//check to see if cookies are already set, remember me
if ((!$lr_user) || (!$lr_pass))
{
 
$username = $_POST[username];
$password = $_POST[password];
 
}else{
 
$username = $lr_user;
$password = $lr_pass;
 
}
 
//if username or password is blank, send to errorlogin.html
if ((!$username) || (!$password)) 
{
 
	header("Location:$base_dir/errorlogin.html");
	exit;
}
 
//sets cookies to remember this computer if the user asks to
if ($_POST[remember] == "Yes")
{
setcookie("lr_user", $username, $duration, "/", $domain);
setcookie("lr_pass", $password, $duration, "/", $domain);
}
 
if ($_POST[activate] == "Yes")
{
		//make the connection to the database
		$connection = @mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
		$db = @mysql_select_db($db_name,$connection)or die(mysql_error());
				
		//build and issue the query
		$sql ="UPDATE $table_name SET verified = '1' WHERE username = '$_POST[username]'";
		$result = @mysql_query($sql,$connection) or die(mysql_error());
}
 
//sets session variables
sess_vars($base_dir, $server, $dbusername, $dbpassword, $db_name, $table_name, $username, $password);
 
//check to see if the user has to change their password
if ($_SESSION[pchange] == "1")
{
	$_SESSION[redirect] = "$base_dir/pass_change.html";
}
 
//check to see if the user has activated the account
if ($_SESSION[verified] == "0")
{
	$_SESSION[redirect] = "$base_dir/not_activated.html";
}
 
//make the connection to the database
$connection = @mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());
$db = @mysql_select_db($db_name,$connection)or die(mysql_error());
		
//build and issue the query
$sql ="SELECT * FROM banned";
$result = @mysql_query($sql,$connection) or die(mysql_error());
 
while ($sql = mysql_fetch_object($result)) 
	{
	$banned = $sql -> no_access;
	if ($username == $banned || $REMOTE_ADDR == $banned)
		{
			include ('banned.html');
			exit;
		}
	}
 
$last_log = last_login();
 
//updates table with last log as now
$sql = "UPDATE $table_name SET last_login = '$last_log' WHERE username = '$_SESSION[user_name]'";
$result = @mysql_query($sql,$connection) or die(mysql_error());
 
if (($_SESSION[redirect] != "$base_dir/errorlogin.html") && ($log_login == "1"))
{
	include('loglogin.php');
}
 
//redirects the user	
header("Location:dex.php");
 
?>
 
<head><title>Redirect</title></head>

Open in new window

EDIT: This could probably be more the one you are looking for. This piece of code is at the very top of my site (on dex.php), the site requires a login (and that contains those RAY_item iframes)
<?php
 
//prevents caching
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter();
session_start();
 
require('/home6/distende/public_html/autodiet/config.php');
 
require('/home6/distende/public_html/autodiet/functions.php');
 
//this is group name or username of the group or person that you wish to allow access to
// - please be advise that the Administrators Groups has access to all pages.
if (allow_access(Users) != "yes")
{
include ('/home6/distende/public_html/autodiet/no_access.html');
exit;
}
?>
 
<html>
<head>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of FirestormX
FirestormX
Flag of Canada image

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
Thank you alot for all your help :-) Here is your points!!
Thanks alot, very thoughtfull answers and patience