Page 1 of 2

Why is this undefined?..I FIXED IT YES!!!

Posted: Wed Jun 24, 2009 1:30 am
by scarface222
For some reason I am not sure of the highlighted line/variable is undefined $id...Any ideas?

***** Please use the

Code: Select all

tag when posting PHP code *****[/color]
 
[code=php]function getContent($link, $num){
    $id=$_POST['id'];
    $res = @mysql_query("SELECT date, user, message FROM top WHERE id='$id' ORDER BY date DESC LIMIT ".$num, $link);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}

Re: Why is this undefined?..help appreciated

Posted: Wed Jun 24, 2009 1:35 am
by Christopher

Code: Select all

function getContent($link, $num){
  if (isset($_POST['id']) && $_POST['id']) {
    $id = intval($_POST['id']);     // filter your unsafe vars from user!
    $res = @mysql_query("SELECT date, user, message FROM top WHERE id='$id' ORDER BY date DESC LIMIT ".$num, $link);
    if(!$res) {
        die("Error: ".mysql_error());
    } else {
        return $res;
    }
  } else {
    // error here
  }
}

Re: Why is this undefined?..help appreciated

Posted: Wed Jun 24, 2009 8:58 pm
by scarface222
Thank you for your response, however when I use your technique I receive the message Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource on the highlighted line? any ideas?

Code: Select all

<?php
else{
    $link = connect(HOST, USER, PASSWORD);
    switch($_POST['action']){
        case "update":
            $res = getContent($link, 500);
            $result="";
            [color=#BF0000]while($row = mysql_fetch_array($res)){[/color]
                $result .= "<li><strong>".$row['user']."</strong><img src=\"sh/css/images/bullet.gif\" alt=\"-\" />".$row['message']." <span class=\"date\">".$row['date']."</span></li>";
            }
            echo $result;
            break;
        case "insert":
            echo insertMessage($_POST['user'], $_POST['message']);
            break;
    }
?>

Re: Why is this undefined?..help appreciated

Posted: Thu Jun 25, 2009 4:45 pm
by scarface222
arborint going once?

Re: Why is this undefined?..help appreciated

Posted: Thu Jun 25, 2009 5:06 pm
by Christopher
Going twice? GONE! :)

The problem is, you need to decide whether you want to call the variable $link or $res. Use one or the other. ;)

Re: Why is this undefined?..help appreciated

Posted: Thu Jun 25, 2009 6:46 pm
by scarface222
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


You will have to excuse my noobishness but how can the script function without one? Here is the whole script including your suggestion. Could you maybe break it down and maybe suggest how to improve it? How can I use only one and achieve the same result? Thanks alot for your help by the way. I really appreciate your time.

Code: Select all

<?php
 
/************************
    CONSTANTS
/************************/
define("HOST", "ab");
define("USER", "c");
define("PASSWORD", "d");
define("DB", "efg");
 
/************************
    FUNCTIONS
/************************/
function connect($db, $user, $password){
    $link = @mysql_connect($db, $user, $password);
    if (!$link)
        die("Could not connect: ".mysql_error());
    else{
        $db = mysql_select_db(DB);
        if(!$db)
            die("Could not select database: ".mysql_error());
        else return $link;
    }
}
function getContent($link, $num){
   if (isset($_POST['id']) && $_POST['id']) {
   $id = intval($_POST['id']);     // filter your unsafe vars from user!
   $res = @mysql_query("SELECT date, user, message FROM top WHERE id='$id' ORDER BY date DESC LIMIT ".$num, $link);
   if(!$res) {
            die("Error: ".mysql_error());
        } else {
            return $res;
        }
    } else {
       // error here
     }
   }
function insertMessage($user, $message, $id){
    $id=$_POST['id'];
    $query = sprintf("INSERT INTO abf(user, message, id) VALUES('%s', '%s', '$id');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message)));
    $res = @mysql_query($query);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}
 
/******************************
    MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
    
    header ("Location: index.html"); 
}
else{
    $link = connect(HOST, USER, PASSWORD);
    switch($_POST['action']){
        case "update":
            $res = getContent($link, 500);
            $result="";
            while($row = mysql_fetch_array($res)){
                $result .= "<li><strong>".$row['user']."</strong><img src=\"abc/css/images/bullet.gif\" alt=\"-\" />".$row['message']." <span class=\"date\">".$row['date']."</span></li>";
            }
            echo $result;
            break;
        case "insert":
            echo insertMessage($_POST['user'], $_POST['message']);
            break;
    }
    mysql_close($link);
}
 
 
?>

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Why is this undefined?..help appreciated

Posted: Fri Jun 26, 2009 4:11 pm
by scarface222
Do we have an Arborint present? Anybody? And sorry for tags I will do so from now on.

Re: Why is this undefined?..help appreciated

Posted: Fri Jun 26, 2009 4:29 pm
by Reviresco
Where are you getting the value for $id? It seems like it's not getting passed. Try something like:

Code: Select all

echo '<p>Value of id: ' . $id . '</p>';
to see if you even have a value for it.

Also, what are the expected values for $num and $link? It looks odd to see

Code: Select all

LIMIT ".$num, $link);
because LIMIT needs an integer -- it's to limit the number of results to a certain number, like "LIMIT 20" or something. Having two variables doesn't seem right there unless you're adding them together, multiplying them, etc.

Re: Why is this undefined?..help appreciated

Posted: Fri Jun 26, 2009 10:33 pm
by scarface222
Thanks for the response. I am positive the variable got passed but I am confused because it only works for one of the functions but not another. If I post it in the insertmessage function it works and the variable is defined but not in the getcontent function where I use the mysql so that doesnt make sense to me. As for $link and $num I am not completely sure because I was helped with this script on some parts.

Re: Why is this undefined?..help appreciated

Posted: Fri Jun 26, 2009 10:45 pm
by califdon
Reviresco wrote:because LIMIT needs an integer -- it's to limit the number of results to a certain number, like "LIMIT 20" or something. Having two variables doesn't seem right there unless you're adding them together, multiplying them, etc.
The LIMIT clause can take either 1 or 2 arguments. For example, ...LIMIT 20, 10 means return 10 rows, beginning with the 20th row (that is, rows 20 through 29). See http://www.devx.com/tips/Tip/37647.

Re: Why is this undefined?..help appreciated

Posted: Fri Jun 26, 2009 11:13 pm
by scarface222
Thanks for the response. So is limit the reason I am getting an undefined index aka $id? Even if I remove or modify it I still get an undefined index so I do not think that is the problem. Does anyone know what airborint meant when he said that I could only use $link or $res?

Re: Why is this undefined?..help appreciated

Posted: Sat Jun 27, 2009 11:20 am
by califdon
Sorry I didn't have time to really look at your original question before. I was really responding to the person who mentioned the LIMIT clause. Now that I read your original question more carefully, it appears that $link is your database connection handle. In any case, the meaning of the message: "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource" is that your query did not produce a valid resource (in other words, the query failed). Since you indicated earlier that you were receiving an error about $id being undefined, that would explain why the query failed, wouldn't it? So your task is to figure out why $id hasn't been defined. The most obvious possibility is that there is no value in the $_POST array for 'id'. This is what ~arborint was referring to in one of his responses, it is critical for you to validate input received from an external source before you try to use it in your processing. First, to determine if it is present, then to "sanitize" it to prevent someone from including harmful characters that might compromise your system. I recommend that you test all your $_POST variables and apply the mysql_real_escape_string() function to them at the very beginning of your main script. Then you can use them later in your script with confidence that they have values assigned and that they are "clean" and won't cause "SQL injection" disasters.

Re: Why is this undefined?..help appreciated

Posted: Sat Jun 27, 2009 12:38 pm
by scarface222
Thanks a lot for your response. I will be sure to fix that but on the note of mysql failure, I am sure it is due to the undefined variable but I am unsure why. If you look at the Insert Message function when I posted my last full code you will notice I used $_POST $id as well and that works ok and from that I can tell the variable is getting passed however when I try to use $_POST in the GetContent function it is undefined. This doesn't make sense to me. It is like a glitch. Is there any way I can modify the code to make this function work? This is impeding my progress badly haha. By the way thanks everyone for your useful contributions so far, you have all been a good help in trying to solve this.

Code: Select all

<?php
function getContent($link, $num){
$topic_id=$_POST['topic_id'];
    $res = @mysql_query("SELECT date, user, message FROM shoutbox WHERE topic_id='$topic_id' ORDER BY date DESC LIMIT ".$num, $link);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}
function insertMessage($user, $message, $topic_id){
$topic_id=$_POST['topic_id'];
    $query = sprintf("INSERT INTO shoutbox(user, message, topic_id) VALUES('%s', '%s', '$topic_id');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message)));
    $res = @mysql_query($query);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}
?>

Re: Why is this undefined?..help appreciated

Posted: Sat Jun 27, 2009 1:10 pm
by califdon
What's the one thing that's different between the two functions? The fact that insert_message() requires that the topic_id is passed as an argument. You also extract it from the $_POST array in that function, which is a bad practice, because it overwrites the value passed in the function call, for no reason, but my point is that the 2 functions are thus not comparable. In general, you should pass variables needed in a function through the arguments, so if it were me, I would do that, and not extract them from the $_POST array from inside the functions.

As a more general comment, for debugging, you need to echo out the value of $topic_id inside the function, or better yet, echo the value of the entire SQL string. Since it is this value that is clearly causing your problem, it's vital that you really know what the variable contains at the point where it seems to be missing. Insert a line, temporarily, to echo at least $topic_id. A better practice is to form a string, as you did in the insert_message() function, which you can then echo for confirmation that it is a valid query.

Re: Why is this undefined?..help appreciated

Posted: Sat Jun 27, 2009 6:28 pm
by scarface222
Thanks for the suggestion. I echoed the mysql statement and received resource id#3 and as for passing a variable through the argument what exactly do you mean. Do you mean writing the post statement within the function brackets?