Solved

Can't get this PHP-code to work properly

Posted on 2009-04-09
56
429 Views
Last Modified: 2012-05-06
Hey guys. I have a small problem. I have a PHP-file on my homepage. That PHP consists of several items (called "tool"), each with their own priority (called "quantity") to get selected, and their own weight (called "amount"). The script selects 1 "random"(?) item (some items have a higher chance of getting selected than others), and then it checks to see 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.

I have moved my database-array with all the items, and their weight and priorities to a MySQL database. But I can't get the script to work again. It is line 31 to 43 on the new PHP file, that it not working correctly, I think.
Please, could someone take a look at it, and tell me what I am doing wrong?

Everything was working perfectly before on my old script, but I wanted to move to a MySQL database so people, that have signed on on my homepage, will be able to change their own list of items further down the road.

The OLD script I was using is here in this code-snippet. That was working perfectly.

It is line 19 to 28 you would look at here, I think!
0
Comment
Question by:MisterHamper
  • 29
  • 24
  • 3
56 Comments
 

Author Comment

by:MisterHamper
ID: 24109583
The OLD code is here
It is line 19 to 28 you would look at here, I think!:
<?php //old script

error_reporting(E_ALL);

echo "<pre>";
 

// DATA STRUCTURE

$quantity["item one"]  = 50;   $amount["item one"]  = 150;

$quantity["item two"]  = 50;   $amount["item two"]  = 150;

$quantity["item three"]  = 25;   $amount["item three"]  = 80;

$quantity["item four"]  = 15;   $amount["item four"]  = 10;

$quantity["item five"]  = 25;   $amount["item five"]  = 120;

$quantity["item six"]  = 20;   $amount["item six"]  = 90;

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "5000";}else{$number = $_GET['number'];}

 

// ASSIGN MAXIMUM TOTAL amount FOR ITEMS

$max_amount = ($number*5/30)+35;

 

// COMPUTE MINIMUM amount FOR THREE ITEMS - SIMULATE $min_amount = $amount[0] + $amount[1] + $amount[2];

$max_amount = ($number*5/30)-35;

asort($amount);

$kount = 3;

foreach ($amount as $tool => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

// FREQUENCY OF THE toolS ITEMS BASED ON quantity - A LARGE ARRAY

$tools = array();

foreach ($quantity as $tool => $number)

{

   while ($number > 0)

   {

      $number--;

      $tools[] = $tool;

   }

}

 

// RANDOMIZE THE LARGE ARRAY

shuffle($tools);

 

// CHOOSE THE toolS

$my_tools  = array();

$my_amount = 0;

foreach ($tools as $tool)

{

 

// CHOOSE ONLY UNIQUE toolS

   if (in_array($tool, $my_tools)) continue;

 

// NOT MORE THAN MAX amount

   $my_amount = $my_amount + $amount["$tool"];

   if ($my_amount > $max_amount) break;

 

// SELECT THIS tool

   $my_tools["$tool"] = $tool;

}

 

// ITEMIZE THE amountS OF THESE toolS

foreach ($my_tools as $tool => $x)

{

   $my_tools["$tool"] = $amount["$tool"];

}

 

// SHOW THE RESULTS

foreach ($my_tools as $my_tool => $my_amount)

{

   echo "$my_tool - $my_amount<br />";

}
 

}

echo script();
 

?>

Open in new window

0
 

Author Comment

by:MisterHamper
ID: 24109612
And the new code is here:
I think it is line 34 to 43 here, that it is not working properly I think. So something isn't working correctly with that snippet of code.

My MySQL database looks like this (for "items", "deleted_items" looks the same)

Thanks for helping me :-) I don't really know what could be wrong myself. I will gladly elaborate if needed
<?php 
 

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

// 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_numbers(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";

        }

}

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "2000";}else{$number = $_GET['number'];}
 

// ASSIGN MAXIMUM TOTAL priority FOR ITEMS

$max_priority = ($number/2)+35;

 

// COMPUTE MINIMUM priority FOR THREE ITEMS - SIMULATE $min_priority = $priority[0] + $priority[1] + $priority[2];

$min_amount = ($number/2)-35;

asort($amount);

$kount = 3;

foreach ($amount as $item => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

// NEW DATA STRUCTURE

//Pull the data from the table (limited to the max_priority)

$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_priority}");

 

//Loop through each number in the query, and place it in the $items[] array; also checking for unique items

$items = array();

while ($number = mysql_fetch_array($query))

{

        if (!inarray($number, $items)) //Check to see if this is a duplicate

        {$items[] = $number;} //We set the next $items[] array index to an array of the returned numbers from the DB

}

 

 

// RANDOMIZE THE LARGE ARRAY

shuffle($items);

 

// SHOW THE RESULTS

foreach ($items as $number) //This returns $number, which is an array of each number pulled from the database

{

        //Each index in $number is a string of the column name

   echo "{$number['name']} <a href=\"RAY_item.php?delete={$number['id']}\">x</a><br />";

}
 

}

echo RAY_item();

?>

Open in new window

Z-40.jpg
0
 

Author Comment

by:MisterHamper
ID: 24109757
Sorry, I made a mistake before. THIS is the new script I am using.

And this is the error message it is giving me:

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

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

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

Thanks
<?php 
 

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

// 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_numbers(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";

        }

}
 

 

// NEW DATA STRUCTURE

//Pull the data from the table (limited to the max_priority)

$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_priority}");

 

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "2000";}else{$number = $_GET['number'];}
 

// ASSIGN MAXIMUM TOTAL priority FOR ITEMS

$max_priority = ($number/2)+35;

 

// COMPUTE MINIMUM priority FOR THREE ITEMS - SIMULATE $min_priority = $priority[0] + $priority[1] + $priority[2];

$min_amount = ($number/2)-35;

asort($amount);

$kount = 3;

foreach ($amount as $item => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

//Loop through each number in the query, and place it in the $items[] array; also checking for unique items

$items = array();

while ($number = mysql_fetch_array($query))

{

        if (!inarray($number, $items)) //Check to see if this is a duplicate

        {$items[] = $number;} //We set the next $items[] array index to an array of the returned numbers from the DB

}

 

 

// RANDOMIZE THE LARGE ARRAY

shuffle($items);

 

// SHOW THE RESULTS

foreach ($items as $number) //This returns $number, which is an array of each number pulled from the database

{

        //Each index in $number is a string of the column name

   echo "{$number['name']} <a href=\"RAY_item.php?delete={$number['id']}\">x</a><br />";

}
 

}

echo RAY_item();

?>

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24110293
In your new code, I don't see you defining $amount as an array - or populating it as an array like you do in your old code.  The result is that when you are calling asort($amount), at that time $asort isn't an array, just an empty variable with a null value.

Earlier in the code you either need to declare $amount as an array "$amount = array(....code here....)" or make the assignments like you did in your old code:
$amount["item one"]  = 150;  ...etc.
0
 

Author Comment

by:MisterHamper
ID: 24110435
Hello, thanks for the reply synx.
I think I get what you are saying! Could I declare $amount as hmm... my database "items"? - if I explained that correctly? Because I can't make my asignments like I did in my old code, because then the users that sign up won't be able to delete an item if they do not like that particular item (add it to an ignore-list called "deleted_items"). So that's why it had to be in a MySQL database.
I already have a working login-system. But how would I make those lines of script work with my database and the new PHP-script?
If I am not making alot of sense, I can explain further. :-)
0
 
LVL 4

Expert Comment

by:vdelau
ID: 24110484
There is far more wrong. The SQL warning for line 53 is probably caused by an error in the query on line 31. You should check is $query (which actualy is a result resource) is not false.

Then the result of a mysql_fetch_array would be an array. I don't think you want to check is that array is in $items, but an item in the array like $number['id'].
0
 
LVL 4

Expert Comment

by:vdelau
ID: 24110542
There is an error in your query (or die() would have caught that): The AND before LIMIT is out of place.
0
 
LVL 4

Expert Comment

by:vdelau
ID: 24110574
Another one: use MySQL to check for duplicates. You database shouldn't probably have any duplicates and if it does, use SELECT DISTINCT (http://dev.mysql.com/doc/refman/5.0/en/select.html)

0
 

Author Comment

by:MisterHamper
ID: 24110595
I am not sure I get what you mean, vdelau, sorry. This is my first homepage. :) I have learned alot the last weeks, but I am still not the best at MySQL or PHP.
How do I check if $query at line 31 is not false, and how would I go about fixing that? And what should I do with the AND LIMIT in line 31 too? Thank you
0
 
LVL 5

Expert Comment

by:synx
ID: 24110786
If you get rid of that last "AND" right before "LIMIT", it should be fine.
0
 
LVL 5

Expert Comment

by:synx
ID: 24110818
I believe after getting rid of that last "AND", the rest of the query should work.
To test long query statements like that, sometimes I will comment out that line of code and create a new line that hard-codes in values instead of plugging in PHP variables.  That way you can make sure that the query runs successfully first, and then worry about having the values auto-populate.
Even better would be if you have access to run queries directly against your mySQL database.  Then you could very quickly verify that the query structure works, and then use PHP to plug the values in in your code.
0
 

Author Comment

by:MisterHamper
ID: 24110866
I just tried removing the AND before the LIMIT. It still gives me the exact same error message

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

Warning: Invalid argument supplied for foreach() 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 53"

I even tried deleting every AND in the whole file. Still the exact same error message. This is how it looks after removing only the AND before the LIMIT:
$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'])."' LIMIT {$max_priority}");

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24110942
Right - sorry, got mixed up a bit there.  Removing that 'AND' will correct the query, but that is a separate issue from the array.

The issue with the array is still that PHP doesn't know that $amount is an array when it executes the asort() command.
0
 
LVL 5

Expert Comment

by:synx
ID: 24110964
I think maybe a little more should be explained.  When you are sorting the array $amount in the code... what information are you expecting it to contain? Information retrieved from the database, is that correct?
0
 

Author Comment

by:MisterHamper
ID: 24111045
Yes let me explain a little further. You can see a beta example of it all on my homepage here I use for toying around with for the moment
http://alturl.com/mky8
The first iframe ("breakfast") is the one where I tried my new PHP that connects to my database. The third iframe ("Brunch") is the working one, that uses the old working PHP script so that's the one where you can see how it should work.
As you can see, the script gives you a list of items - normally between 2 and 4 - enough items so that it is exactly between the minimum and maximum allowed weight. And you can change the allowed weight with the input-box at the top.

So when I am doing the $amount-array on the old PHP script, it is sorting the items priority (its chance of getting picked) and its weight (so the items is between min. and max. allowed weight).

In one of my first comments there is a picture of my database, that shows which rows it contains. It contains the ID of the item, the name of the item, its quantity (its priority) and its amount (its weight), and then also a page-row (so I can use my RAY_item.php in every frame, and use a $GET_page or something like that)

I hope you understand :-)
0
 

Author Comment

by:MisterHamper
ID: 24111047
You can sign in with username: heyheyhey and password: heyheyhey
:)
0
 
LVL 5

Expert Comment

by:synx
ID: 24111431
I think I follow, but not entirely.  Hopefully enough to get over the hurdle.  Let me ask a few more questions:
1. The goal is to make the new script act exactly like the old script, except this time instead of hard-coding the values like you did in lines 6-11, you want them populated from the database.  Is that correct?
2. Do you still want the $amount array to only contain amounts?

If you are just trying to duplicate the old script, I think it should not be too difficult.  Basically, you would want to replace the code that you previously used to populate the $quantity and $amount arrays (6-11) with new code that populates them from the database.  Once you do that, if the end result is the same (those 2 arrays populated with values) the rest of the code should still work.

Assuming that's the goal, you could replace lines 6-11 with:
//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());
 

$query = "SELECT id, name, quantity, amount, page-row FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

    $quantity[$i] = $row['quantity'];

	$amount[$i] = $row['amount'];

	// if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

	$i++;

} 
 

// By the time you get here, you will have your $quantity and $amount arrays populated with data from the 

// database.  Note that they'll begin at subscript zero (ex: $quantity[0] == "200").

// You can loop through the array and echo the contents if you'd like to see how they are stored:
 

foreach ($quantity as $key => $value)

{

    echo "Key: $key; Value: $value<br />\n";

}

Open in new window

0
 

Author Comment

by:MisterHamper
ID: 24111525
1: Yes the point is to get the new script working exactly like the old one, except for two differences: every item and every items values is in my database. And you should be able to delete an item you don't want (add it to an ignore-list, like "deleted_items"-database (which is included in the script at the moment), but we will see if that is working once I get the first part of the script working)

"2. Do you still want the $amount array to only contain amounts?"
Hmm I am not really sure. I think it only contained the amounts-values before, so that would probably be the case now too.

I just tried replacing this code here
"//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());"

with the one you posted in the other post

But now it gives me this error message:
"Access denied for user 'distende'@'localhost' (using password: NO)"
It didn't give me that one before. Maybe I placed the code snippet the wrong place?
0
 
LVL 5

Expert Comment

by:synx
ID: 24111595
What's in the 'config.php'?  You might want to keep that line.  The code that I included depends on the $dbusername, $dbpassword, etc variables to be set.  My guess is that they are set in 'config.php'.  Is that true?  If not, you'll need to set them before making the database connection.
0
 

Author Comment

by:MisterHamper
ID: 24111616
By the way, RAY_item.php had that error with "Using password: NO" some time ago too, but that was because I replaced $server, $dbusername, $dbpassword with my real MySQL username and password etc, but that went away when I renamed them to the regular $dbusername etc. I think it was because my other login script is already connecting to the database, which it should, and then uses the user that connects (so that user will be able to add to his own individual "deleted_items")
0
 

Author Comment

by:MisterHamper
ID: 24111653
Yes they are already set in the config.php. It was working before (it connected properly it seemed, because there was no "Using Password NO"-error before I replaced it with the new code snippet), so I don't believe the problem is with the user-login system, but I cant know for sure :)
0
 
LVL 5

Expert Comment

by:synx
ID: 24111696
So I'd say leave this in your code:
//include config file
include ('config.php');

and after that, paste the snippet that I sent you.  It might be useful to comment out all of the code after that snippet for now, so you can just focus on getting this first part working.
0
 

Author Comment

by:MisterHamper
ID: 24111875
Ahh that is working now! Or atleast almost :-) The values is the exact ones for the ID, in phpMyAdmin! But what is those errors that is plaguing it?
And I also tried adding
    $name[$i] = $row['name'];
and then
    echo "Name: $name; Key: $key; Value: $value<br />\n";
But then it just showed "Name: Array" for everyone of them, when it should have showed the names I gave them in phpMyAdmin

And there is also still some issues, I can't figure out. But we are getting pretty close now :D

The foreach-echo part should be at the bottom of the script, shouldn't it, in order to get every effect of the script in them (the random, priority, min/max. weight allowed etc)?
In the bottom of my RAY_item.php, there is this line
// SHOW THE RESULTS
foreach ($items as $number) //This returns $number, which is an array of each number pulled from the database
{
        //Each index in $number is a string of the column name
   echo "{$number['name']} <a href=\"RAY_item.php?delete={$number['id']}\">x</a><br />";
}

That is in order to get an "x"-button where you can click and it then adds the items to the deleted_items. Would it be possible to incorporporate it into the other foreach-echo script?
Key: 0; Value: 65

Key: 1; Value: 30

Key: 2; Value: 30

Key: 3; Value: 20

Key: 4; Value: 25
 

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

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

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

Open in new window

0
 

Author Comment

by:MisterHamper
ID: 24111890
That code snippet up there is what the RAY_item iframe is now saying ^

Here is the lines 63 to 74 there was an error message in
asort($amount); //LINE 63!!

$kount = 3;

foreach ($amount as $item => $number)  //LINE 65!!

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

//Loop through each number in the query, and place it in the $items[] array; also checking for unique items

$items = array();

while ($number = mysql_fetch_array($query)) //LINE 74!!

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24111930
Have to leave in a minute, but wanted to say quickly: If you want to loop through the $name array to display the values, you'll have to add a separate loop:

foreach ($name as $key => $value)
{
    echo "Key: $key; Value: $value<br />\n";
}

If you just try to echo the name of the array without looping through it or without specifying a key value to echo, it will just echo "Array", which you just found out  :o)

I will look through your other comments and follow up tomorrow.
0
 
LVL 5

Expert Comment

by:synx
ID: 24111988
The foreach loops that I put in the sample code was just to dump the contents of the array to the screen.  The loop can really go anywhere once the array is populated.  Any action that you wanted performed on each item in the array should be done in a foreach loop.

Also... it looks like asort() still doesn't think it's being passed an array.  You are populating $amount as indicated in the script I sent you?  What displays if you try to loop through $amount like this:
foreach ($amount as $key => $value)
{
    echo "Key: $key; Value: $value<br />\n";
}

Also... what happens if you just try to "echo $amount;"?

Ok, leaving for real now.
0
 

Author Comment

by:MisterHamper
ID: 24111992
Bye bye! Thanks for the help. I will toy around with the new script some more while you are gone, and see if I can learn something. But I will most likely still like your help tomorrow, because that good I am not at PHP
0
 

Author Comment

by:MisterHamper
ID: 24113921
If I delete the rest all the foreach/echo part and just write echo $amount; around line 28 it just says "Array" on my iframe, and then all the error-messages below it.
If I write echo $amount; in the buttom of the script, where my first echo was, it just give me one blank break and then the error-messages below.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 5

Expert Comment

by:synx
ID: 24115375
Disregarding the test that you just did - could you paste your code here in its entirety, along with the error messages that it's generating?  With all the little tweaks that have been made, I think it would help to see it again in one piece.
0
 

Author Comment

by:MisterHamper
ID: 24115457
Hey again, whats up?

Here is the script at the moment with all those changes that have been done

This is what it says in my iFrame:

"Key: 0; Value: 65
Key: 1; Value: 30
Key: 2; Value: 30
Key: 3; Value: 20
Key: 4; Value: 25

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

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

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

The values of the items (their amount - their priority to get selected) is the correct ones for the item's ID (keys).

But it is still not working as it should. But it should select a "random" item based on its priorities, and then check the total current weight of the item and see if it is below the minimum allowed weight, and then if it is, select a new item (again based on its priorities) and check again (described better in a couple coments above)
I think it could have something to do with line 55-70 and also line 85-89. But I don't really know.
<?php 
 

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

$query = "SELECT id, name, quantity, amount FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

    $quantity[$i] = $row['quantity'];

        $amount[$i] = $row['amount'];

        $name[si] = $row['name'];

        // if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

        $i++;

} 

 

// By the time you get here, you will have your $quantity and $amount arrays populated with data from the 

// database.  Note that they'll begin at subscript zero (ex: $quantity[0] == "200").

// You can loop through the array and echo the contents if you'd like to see how they are stored:

 

foreach ($quantity as $key => $value)

{

    echo "Key: $key; Value: $value<br />\n";

}
 

// 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_numbers(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";

        }

}
 

 

// NEW DATA STRUCTURE

//Pull the data from the table (limited to the max_priority)

$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'])."' LIMIT {$max_priority}");

 

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "2000";}else{$number = $_GET['number'];}
 

// ASSIGN MAXIMUM TOTAL priority FOR ITEMS

$max_priority = ($number/2)+35;

 

// COMPUTE MINIMUM priority FOR THREE ITEMS - SIMULATE $min_priority = $priority[0] + $priority[1] + $priority[2];

$min_amount = ($number/2)-35;

asort($amount);

$kount = 3;

foreach ($amount as $item => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

//Loop through each number in the query, and place it in the $items[] array; also checking for unique items

$items = array();

while ($number = mysql_fetch_array($query))

{

        if (!inarray($number, $items)) //Check to see if this is a duplicate

        {$items[] = $number;} //We set the next $items[] array index to an array of the returned numbers from the DB

}

 

  

// RANDOMIZE THE LARGE ARRAY

shuffle($items);

 

// SHOW THE RESULTS

foreach ($items as $number) //This returns $number, which is an array of each number pulled from the database

{

        //Each index in $number is a string of the column name

   echo "{$number['name']} <a href=\"RAY_item.php?delete={$number['id']}\">x</a><br />";

}

 

}

echo RAY_item();

?>

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24116125
Ok - I noticed a couple of things.  First, I see why you're getting that error when you call asort() within your function RAY_item.  Earlier we talked about how asort() needs to be passed an array in order to work properly.  Outside of the function, you are creating the $amount array.  When you are calling RAY_item() you are currently not passing it any values.  That means that it doesn't know what $amount is (or any of the other variables/arrays that you create before defining the function since they aren't declared as global).  So when you refer to $amount within the function, it thinks it's an empty string with a null value because it can't see variables beyond the scope of that function's definition.  Does that make sense?

If you want RAY_item to be able to read and manipulate $amount, you would have to pass it in when you call it, like "RAY_item($amount)".

Also, I don't think calling the function with an echo is the best idea (your last line: echo RAY_item()) - since that function doesn't return a single value that you can echo.  If you don't have a "return" statement within the function, you should probably call by just listing its name, or by assigning a return code, like this:
$retCd = RAY_item()
or something similar.
0
 
LVL 5

Expert Comment

by:synx
ID: 24116247
When I posted the code earlier, I meant for that to be used in your old script, which didn't have the RAY_item function.  Since we're trying to mimic the old script before adding additional functionality.  That being said, what happens if you run this attached code?  It's a copy of your old code, only using the database to fill the arrays instead of hard-coding the values.  The rest of the code is unchanged from what you originally had in the working script:
<?php //old script
 

session_start();

 

//include config file

include ('config.php'); 
 

error_reporting(E_ALL);

echo "<pre>";

 //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());

 

$query = "SELECT id, name, quantity, amount, page-row FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

    $quantity[$i] = $row['quantity'];

	$amount[$i] = $row['amount'];

	$name[$i] = $row['name'];

	// if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

	$i++;

} 

 

// By the time you get here, you will have your $quantity and $amount arrays populated with data from the 

// database.  Note that they'll begin at subscript zero (ex: $quantity[0] == "200").

// You can loop through the array and echo the contents if you'd like to see how they are stored:

 

// DATA STRUCTURE

/*

$quantity["item one"]  = 50;   $amount["item one"]  = 150;

$quantity["item two"]  = 50;   $amount["item two"]  = 150;

$quantity["item three"]  = 25;   $amount["item three"]  = 80;

$quantity["item four"]  = 15;   $amount["item four"]  = 10;

$quantity["item five"]  = 25;   $amount["item five"]  = 120;

$quantity["item six"]  = 20;   $amount["item six"]  = 90;

 */

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "5000";}else{$number = $_GET['number'];}

 

// ASSIGN MAXIMUM TOTAL amount FOR ITEMS

$max_amount = ($number*5/30)+35;

 

// COMPUTE MINIMUM amount FOR THREE ITEMS - SIMULATE $min_amount = $amount[0] + $amount[1] + $amount[2];

$max_amount = ($number*5/30)-35;

asort($amount);

$kount = 3;

foreach ($amount as $tool => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

// FREQUENCY OF THE toolS ITEMS BASED ON quantity - A LARGE ARRAY

$tools = array();

foreach ($quantity as $tool => $number)

{

   while ($number > 0)

   {

      $number--;

      $tools[] = $tool;

   }

}

 

// RANDOMIZE THE LARGE ARRAY

shuffle($tools);

 

// CHOOSE THE toolS

$my_tools  = array();

$my_amount = 0;

foreach ($tools as $tool)

{

 

// CHOOSE ONLY UNIQUE toolS

   if (in_array($tool, $my_tools)) continue;

 

// NOT MORE THAN MAX amount

   $my_amount = $my_amount + $amount["$tool"];

   if ($my_amount > $max_amount) break;

 

// SELECT THIS tool

   $my_tools["$tool"] = $tool;

}

 

// ITEMIZE THE amountS OF THESE toolS

foreach ($my_tools as $tool => $x)

{

   $my_tools["$tool"] = $amount["$tool"];

}

 

// SHOW THE RESULTS

foreach ($my_tools as $my_tool => $my_amount)

{

   echo "$my_tool - $my_amount<br />";

}

 

}

echo script();

 

?>

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24116253
In the code I just pasted, I left your old lines in that filled quantity and amount, but commented them out.  I wanted to keep them visible for reference, but they won't actually execute.
0
 

Author Comment

by:MisterHamper
ID: 24116440
I just tried copying your code-snippet. So when I run that attached code, you just posted, it says only this

"Parse error: syntax error, unexpected '}' in /home6/distende/public_html/autodiet/RAY_item.php on line 100"

So I tried removing that "}" on line 100, and it now says this all this instead:

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

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

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

Notice:  Undefined variable: quantity in /home6/distende/public_html/autodiet/RAY_item.php on line 59

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

Fatal error:  Call to undefined function  script() in /home6/distende/public_html/autodiet/RAY_item.php on line 101"
0
 
LVL 5

Expert Comment

by:synx
ID: 24116579
Where is it calling RAY_item()?  In the code I pasted above, there is no such thing as RAY_item...
0
 

Author Comment

by:MisterHamper
ID: 24116606
Hmm. The file itself is called RAY_item.php - that file is located at /home6/distende/public_html/autodiet/RAY_item.php. But I don't know why it is giving an error.
0
 

Author Comment

by:MisterHamper
ID: 24116636
I think it gives all those errors about RAY_item.php because I deleted that "}" at the bottom of the script. Instead of deleting it, I should probably have just add'ed a new "{" somewhere above it, at the top maybe? But I don't know where or if I'm correct. :)
0
 
LVL 5

Expert Comment

by:synx
ID: 24116659
Oooh ok, I was thinking it was calling that RAY_item function.  I'll look for the missing/extra {...
0
 
LVL 5

Expert Comment

by:synx
ID: 24116706
You were correct to remove that last "}".  That was a problem.

Line 17 is another problem.  If you run the query directly against your database in phpMyAdmin, do you get results?
"SELECT id, name, quantity, amount, page-row FROM items"

0
 

Author Comment

by:MisterHamper
ID: 24116794
Oh :) How should I write that up, you are telling me? Like this, in the code-snippet below? I tried that, but then it says there is an unexpedted "{" on line 18. Tried deleting the "{" (and also the "}" in line 24), and it gives me this error:
"Parse error: syntax error, unexpected T_VARIABLE in /home6/distende/public_html/autodiet/RAY_item.php on line 18"
Dont know what that means.

I saw that "SELECT id, name, quantity, amount, page-row FROM items" with a $query in front of it is already written before (line 14 in RAY_item), so I tried just deleting line 17 and write nothing instead. I don't think that was right, Because then I got this error here. So we can probably just scrap that list thing I just did :P

"Notice:  Undefined variable: row in /home6/distende/public_html/autodiet/RAY_item.php on line 18

Notice:  Undefined variable: row in /home6/distende/public_html/autodiet/RAY_item.php on line 19

Notice:  Undefined variable: row in /home6/distende/public_html/autodiet/RAY_item.php on line 20

Notice:  Undefined variable: min_amount in /home6/distende/public_html/autodiet/RAY_item.php on line 52

Fatal error:  Call to undefined function  script() in /home6/distende/public_html/autodiet/RAY_item.php on line 100"
$query = "SELECT id, name, quantity, amount, page-row FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

{

    $quantity[$i] = $row['quantity'];

	$amount[$i] = $row['amount'];

	$name[$i] = $row['name'];

	// if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

	$i++;

} 

Open in new window

0
 

Author Comment

by:MisterHamper
ID: 24116808
Oops, this was how I tried writing it the first time:

The one below is how tried writing it for the second time.
$query = "SELECT id, name, quantity, amount, page-row FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

"SELECT id, name, quantity, amount, page-row FROM items"

{

    $quantity[$i] = $row['quantity'];

	$amount[$i] = $row['amount'];

	$name[$i] = $row['name'];

	// if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

	$i++;

} 

Open in new window

0
 
LVL 5

Accepted Solution

by:
synx earned 500 total points
ID: 24116927
You definitely need row 17.  The only "}" that should be there is the one that was in line 100.  I'll correct those 2 things (and get rid of the reference to "script()" and paste the new script below.

Regarding the "SELECT id, name, quantity, amount, page-row FROM items" statement.  What I meant by just running that statement was not in the code... but if you copy it (without quotes) and run it directly against the database in phpMyAdmin, does it return results?  We need to make sure it's a valid SQL statement before we try to have the script run it (like, are the row names and table name correct?...)  SO I'd say:

1.  Replace your script with what I have pasted below.
2.  Go into phpMyAdmin and try to just run the SQL statement: SELECT id, name, quantity, amount, page-row FROM items       and see if it returns the rows.
<?php //old script

 

session_start();

 

//include config file

include ('config.php'); 

 

error_reporting(E_ALL);

echo "<pre>";

 //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());

 

$query = "SELECT id, name, quantity, amount, page-row FROM items"; //Modify this accordingly to only select the rows you want

$result = mysql_query($query);

$i = 0;

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

    $quantity[$i] = $row['quantity'];

	$amount[$i] = $row['amount'];

	$name[$i] = $row['name'];

	// if you want, you can also populate arrays for $row['id'], and the other fields returned by the query

	$i++;

} 

 

// By the time you get here, you will have your $quantity and $amount arrays populated with data from the 

// database.  Note that they'll begin at subscript zero (ex: $quantity[0] == "200").

// You can loop through the array and echo the contents if you'd like to see how they are stored:

 

// DATA STRUCTURE

/*

$quantity["item one"]  = 50;   $amount["item one"]  = 150;

$quantity["item two"]  = 50;   $amount["item two"]  = 150;

$quantity["item three"]  = 25;   $amount["item three"]  = 80;

$quantity["item four"]  = 15;   $amount["item four"]  = 10;

$quantity["item five"]  = 25;   $amount["item five"]  = 120;

$quantity["item six"]  = 20;   $amount["item six"]  = 90;

 */

 

// SUBMIT POST

if(!isset($_GET['number'])){$number = "5000";}else{$number = $_GET['number'];}

 

// ASSIGN MAXIMUM TOTAL amount FOR ITEMS

$max_amount = ($number*5/30)+35;

 

// COMPUTE MINIMUM amount FOR THREE ITEMS - SIMULATE $min_amount = $amount[0] + $amount[1] + $amount[2];

$max_amount = ($number*5/30)-35;

asort($amount);

$kount = 3;

foreach ($amount as $tool => $number)

{

   $kount--;

   $min_amount = $min_amount + $number;

   if (!$kount) break;

}

 

// FREQUENCY OF THE toolS ITEMS BASED ON quantity - A LARGE ARRAY

$tools = array();

foreach ($quantity as $tool => $number)

{

   while ($number > 0)

   {

      $number--;

      $tools[] = $tool;

   }

}

 

// RANDOMIZE THE LARGE ARRAY

shuffle($tools);

 

// CHOOSE THE toolS

$my_tools  = array();

$my_amount = 0;

foreach ($tools as $tool)

{

 

// CHOOSE ONLY UNIQUE toolS

   if (in_array($tool, $my_tools)) continue;

 

// NOT MORE THAN MAX amount

   $my_amount = $my_amount + $amount["$tool"];

   if ($my_amount > $max_amount) break;

 

// SELECT THIS tool

   $my_tools["$tool"] = $tool;

}

 

// ITEMIZE THE amountS OF THESE toolS

foreach ($my_tools as $tool => $x)

{

   $my_tools["$tool"] = $amount["$tool"];

}

 

// SHOW THE RESULTS

foreach ($my_tools as $my_tool => $my_amount)

{

   echo "$my_tool - $my_amount<br />";

}
 

 

?>

Open in new window

0
 
LVL 5

Expert Comment

by:synx
ID: 24117029
By the way - and please don't take this the wrong way, but you mentioned that you are pretty new to PHP and MySQL.  If want to get serious about PHP/MySQL and continue to use them to develop beyond this project, I would highly recommend this book:

http://www.amazon.com/Sams-Teach-Yourself-MySQL-Apache/dp/067232976X/ref=sr_1_1?ie=UTF8&s=books&qid=1239381756&sr=1-1

I have it myself and used it to learn PHP.  It's a good one!
0
 

Author Comment

by:MisterHamper
ID: 24117056
Ohh that was what you meant! Silly me.
Well, I just tried running
"SELECT id, name, quantity, amount, page-row FROM items"
and it gave me this error:
"SELECT id, name, quantity, amount, page -
ROW FROM items
LIMIT 0 , 30

MySQL said: Documentation
#1054 - Unknown column 'row' in 'field list'"

I think it's because the "page"-row is just called "page" and not "page-row", so I tried with this:

"SELECT id, name, quantity, amount, page FROM items"
And then there was no errors at all, and it wrote this
" SELECT id, name, quantity, amount, page
FROM items
LIMIT 0 , 30"



I tried pasting your script and then replace "page-row" with just "page"
IT IS ALMOST WORKING NOW!! :D
my iFrame now gives me this:

"

Notice:  Undefined variable: min_amount in /home6/distende/public_html/autodiet/RAY_item.php on line 53

0 - 150
4 - 110
2 - 130
3 - 105
1 - 100"

(Each key is the correct amount (weight), and they are randomly spawning. So sometimes number 3 is at the top, and other times it is at the bottom)

But there is no minimum weight (the min_amount) or at least it isn't working... what could be the problem there?
0
 

Author Comment

by:MisterHamper
ID: 24117071
Thanks for the book recommendation. I will consider it, if I have to be more serious later on. I have only read the 17 articles, "PHP for beginners 101" on Zend's homepage but I was almost getting a brain-overload. :)
0
 
LVL 5

Expert Comment

by:synx
ID: 24117133
Ok - let's fix that error first.  I think we need to initialize $min_amount before the foreach loop on line 50.  Right after line 49 where you assign $kount, before the foreach loop, try adding a line to init $min_amount:

$min_amount = 0;
0
 

Author Comment

by:MisterHamper
ID: 24117266
There was a typo in the script, so there was two "$max_amount" when there should have been only one of each. I fixed that, and it is now working! Everything in the script is working, priority, weight etc

THANKS alot for all your help :D
0
 

Author Comment

by:MisterHamper
ID: 24117283
There is one last thing by the way, I hope you can help me with. :-) That is a very small thing, won't take long, I think.

On my MySQL there is the row called "page" too. How do I make it so that iframe #1 is only taking items from page=1? Because then I could add every item to my database, and just give each item a page-number and then have my 5 iframes just take items from each page. So iframe 2 will take items from page 2 etc.
0
 

Author Comment

by:MisterHamper
ID: 24117329
The last thing: it is showing the results name as a number (its ID i pressume) instead of its name.
So it is sadly showing it like this
"2 - 130
1 - 100"
instead of this fx
"watta - 130
gyn - 100"

I looked through the bottom of the script, but I couldn't find where it is
0
 

Author Comment

by:MisterHamper
ID: 24117464
But I can also just create an individual RAY_item for each page, that will be no problem! :-)
It is mostly just the name-part that is important for me.
0
 
LVL 5

Expert Comment

by:synx
ID: 24117589
Where are "watta" and "gyn" and the others stored?  Are they in the database?  My guess is that those are in the "name" field.  Is that correct?  If it is... replace lines 16-24 with what I have in the snipped below.  Note: lines 16 - 24 should currently be this, correct?
$i = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $quantity[$i] = $row['quantity'];
      $amount[$i] = $row['amount'];
      $name[$i] = $row['name'];
      // if you want, you can also populate arrays for $row['id'], and the other fields returned by the query
      $i++;
}
Replace that block with:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $name = $row['name'];
    $quantity[$name] = $row['quantity'];
      $amount[$name] = $row['amount'];
      // if you want, you can also populate arrays for $row['id'], and the other fields returned by the query
}
0
 
LVL 5

Expert Comment

by:synx
ID: 24117600
Above, the main changes are to get rid of $i, and changing what is done with $name.
If my assumption that "watta" and "gyn" are stored in the "name" field in the database, then please ignore my previous post and let me know where those are defined!
0
 
LVL 5

Expert Comment

by:synx
ID: 24117614
P.S.  AWESOME that the script is working!!  I did a happy dance on your behalf.  Hopefully we can clear up the name issue, which I think will not be difficult.

0
 

Author Comment

by:MisterHamper
ID: 24117622
Ahh that was it :D thanks, it's all working perfectly now!! Here is your points! Thanks again
0
 

Author Closing Comment

by:MisterHamper
ID: 31568643
Very helpful fella!
0
 
LVL 5

Expert Comment

by:synx
ID: 24117698
Thanks MisterHamper.  Glad we got that working  :o)  Take care.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

708 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now