Page 1 of 1

ONE MORE QUESTION ell0bo, then I am done posting for a while

Posted: Sun Mar 21, 2010 10:24 pm
by scarface222
Hey guys quick question. I have really been struggling trying to mod one function, and was wondering if anyone could point out my error of approach. I am trying to modify a script to use a database, rather than a text file for testing purposes but it is not going well. If anyone could quickly point out what I am doing wrong, I would really appreciate it.

My script

Code: Select all

case 'view':
  $link = connect(HOST, USER, PASSWORD);
$res = getContent($link, 500, 73);
$arr=mysql_fetch_array($res)
    foreach($arr as $row){   
       $aTemp = null;
        list($aTemp['time'], $aTemp['user'], $aTemp['message']) = $row; 
        if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
          $data[] = $aTemp;
    }
     break;
Original Script

Code: Select all

  case 'view':
      $data = array();
      $arr = file('messages.txt');
      if(!$_GET['time'])
        $_GET['time'] = 0;
      foreach($arr as $row) {
        $aTemp = null;
        list($aTemp['time'], $aTemp['nickname'], $aTemp['message']) = explode('|', $row); 
        if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
          $data[] = $aTemp;
      }
 
    break;

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Sun Mar 21, 2010 10:46 pm
by ell0bo
http://us.php.net/manual/en/function.my ... -array.php

Fetch array simply returns the row's result as an array. Not all of the rows in one array.

So your code needs to become...

while( $row = mysql_fetch_array($res) ){
$aTemp = null;
list($aTemp['time'], $aTemp['user'], $aTemp['message']) = $row;
if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
$data[] = $aTemp;
}

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Sun Mar 21, 2010 10:55 pm
by scarface222
I appreciate your response man, but I tried that already haha, for some reason it does not mimic the functionality of the original code because while it shows the right results, it refreshes them like 4 times. That is why I thought somehow I had to integrate a foreach statement to somehow be more precise and control output for each row, but I have no idea how to lol. I thought that mysql_fetch_array fetches the results as an entire array so thanks for pointing out it does not. I think I need a foreach statement to somehow filter the output. I have been struggling trying to solve this for a while now and it is driving me mad!

The output is attached to javascript, in case that helps you understand

Code: Select all

function refresh() {
          $.getJSON(files+"daddy-shoutbox.php?action=view&time="+lastTime, function(json) {
            if(json.length) {
              for(i=0; i < json.length; i++) {
                $('#daddy-shoutbox-list').append(prepare(json[i]));
                $('#list-' + count).fadeIn('slow');
              }
              var j = i-1;
              lastTime = json[j].time;
            }
            //alert(lastTime);
          });
          timeoutID = setTimeout(refresh, 3000);
        }

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Sun Mar 21, 2010 11:02 pm
by ell0bo
Then the problem is most likely in your getContent function. What is the query you're running? If you're getting back four lines when you should only be getting back one, I am going to guess you are joining multiple tables in one query, but not doing it correctly. Most likely one of those tables has 4 rows in it.

If you show me what you have in that function I can help you out a little better.

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Sun Mar 21, 2010 11:05 pm
by scarface222
thanks man, no what I mean is, if you look at my message above (sorry I edited, maybe when you were reading message), the results are right, but if you notice there is an if clause to filter messages that are greater than a set time. When you first enter the page, the data is correct, but then it refreshes the data 3-4 more times before stopping, duplicating the entries, so that is why I thought the foreach was key in the original code. I dont think this would help you but here is my mysql query.

Code: Select all

function getContent($link, $num, $topic_id){
        $res = @mysql_query("SELECT time, user, message FROM shoutbox WHERE td='$td' ORDER BY time DESC LIMIT ".$num, $link);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Mon Mar 22, 2010 8:47 am
by ell0bo
Alright... first you need to make sure... $td => $topic_id. I am going to guess it's just a typo, for for the sake of being thorough I wanted to point it out. Also, you should escape $topic_id ...

$topic_id = mysql_real_escape_string($topic_id, $link);
@mysql_query("SELECT time, user, message FROM shoutbox
WHERE td='$topic_id ORDER BY time DESC LIMIT ".$num, $link)

Just protect yourself from sql injection.

As for dealing with the time, I think you're approaching the problem the wrong way. Easiest thing to do is tell the query to limit the returned data for you, rather then having it return everything and you running an if statement on the data. I am going to presume the date format coming in the GET stream is a timestamp, but is that the case for your date's in the database? You are probably using a timestamp with default CURRENT_TIMESTAMP, right? Then, assuming the time you're passing back via json is '2010-03-22' format, just do a compare via... "WHERE ... time > '$timestamp'"

If that doesn't work, submit back how you're setting the json's time variable you pass back, and also the type of the time column in the database. Most likely that's where your problem is coming from, assuming I'm not understanding you correctly.

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Mon Mar 22, 2010 10:51 am
by scarface222
first, thanks again for your response, I appreciate your help more than you know. The only reason I am trying to mod this script and return the results in such a weird way is because I want to be able to fade in new entries individually rather than just update all data, which is how I did it myself and does not look very nice to the end user. You are making very keen observations, as far as the timestamp goes. They should be the same which is just an 10 digit integer. for example, in my database time entries look like 1269058642 which is what they looked like in the original messages.txt. When I pass my information back, I do it in a chunk like the orginal file, like this.

Code: Select all

 require_once('JSON.php');
  $json = new Services_JSON();
  $out = $json->encode($data);
  print $out;
The thing I do not understand is that, functionality works perfectly in the first script but when you change to mine it goes haywire, so that is why I thought foreach was somehow necessary to go through array results. Can't you use a while statement to get all results, then traverse them using a foreach like this?

Code: Select all

 while($row = mysql_fetch_array( $result )) {
        $new=$row['fieldname'];
        $new_array[] = $new; 
     } 
      
     foreach($new_array as $key => $value) {
        echo $key. " - " . $value . "<br />";
     }
For example, I tried this but it does not work

Code: Select all

    while( $row = mysql_fetch_array($res) ){
$aTemp = null;
list($aTemp['time'], $aTemp['user'], $aTemp['message']) = $row;
$data[] = $aTemp;
}
foreach($aTemp as $value){
     if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
          $data[] = $aTemp;
}
If you want to see the code I am experimenting with, you can find it at http://www.ajaxdaddy.com/demo-jquery-shoutbox.html I just want to figure out this darn query so I can implement this kind of fade in structure with my own previous code, but I need to understand how to fetch the information properly first. I think it may be because mysql_fetch_array returns rows, and in the original file file(message.txt) assigns the entire document to an array, so is it possible to do the same with the mysql data.

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Mon Mar 22, 2010 12:32 pm
by scarface222
ok I just realized the pattern here. with just the while statement like so,

Code: Select all

while($row = mysql_fetch_array($res)){
if($row['message'] AND $row['time'] > $_GET['time'])
$data[] = $row;
}
first there are 6 results so they appear in the box, then 5 of those six are re-added, then 4, then 3,2,1, then it stops. I am not sure if that helps lol.

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Mon Mar 22, 2010 1:10 pm
by ell0bo
Oh dude... you're killing me here, and I'm kicking myself for over looking this in the first place. Alright, look at your query and run it in a browser.

Do you see the order it returns your comments in because you're ordering by date descending?

See, the oldest comment will be on the bottom. The way you wrote the JSON, you parse through it more recent to oldest. So think about it, what date will be be in the i-1 position? That's right, the oldest comment. So you'll go back through and get all comments against except for the very last one, this repeats until all comments have been the last comment. (5,4,3,2,1)

Just set lastTime = json[0].time

I'm going to assume the order of your data file isn't in desc.

Re: mysql_fetch_array, for each, advice EXTREMELY appreciated

Posted: Mon Mar 22, 2010 1:23 pm
by scarface222
did anyone ever tell you, that you are a genius hahahaha? It works perfectly now. I cannot thank you enough for your assistance bro, if you ever need anything from me, I am there lol even though you are more skilled than me. I was staring at this problem for hours lmao and was almost in tears trying to get advice from someone on this and resorting to asking my little brother who knows nothing about php for help haha. It always comes down to some dumb error for me. You have one of the most impressive observation skill levels I have seen on this forum lol. Thanks again, you just made my day and solved hopefully the last headache I will face on this project.

Re: ONE MORE QUESTION ell0bo, then I am done posting for a while

Posted: Mon Mar 22, 2010 10:37 pm
by scarface222
hey man sorry to bother you again, I promise this is my last question but you see where it says

Code: Select all

if($row['message'] AND $row['time'] > $_GET['time'])
$data[] = $row;
I want to change the $row['message'] value that is automatically outputted to one that is been filtered through preg_replace. Instead of $data[]=$row; Is there a way to exchange $row['message'] to a variable $message within that $data array? For example $data[]=($row['time'],$row['user'],$message). //I know that is wrong but just to illustrate.

Re: ONE MORE QUESTION ell0bo, then I am done posting for a while

Posted: Mon Mar 22, 2010 11:17 pm
by ell0bo
Maybe I'm a little slow because it's late, but don't you just want to reset what the row's value is for message? Just set $row['message'] = swap_function($row['message']);

then $data[] = $row as you have.

Re: ONE MORE QUESTION ell0bo, then I am done posting for a while

Posted: Mon Mar 22, 2010 11:27 pm
by scarface222
I think so. Ok right now, the results are getting outputted fine, accept I want $row['message']=$message. So yeah actually, I do want to swap the value but in your swap_function, it looks like you just set $row['message'] to itself. Instead of $row['message'] getting outputted, I want to filter it first, but I am not quite sure how to write it into the data array.

Re: ONE MORE QUESTION ell0bo, then I am done posting for a while

Posted: Mon Mar 22, 2010 11:33 pm
by scarface222
k lol nvm, I did not know you could just do that. I just set row equal to that variable. Thanks once again. I am done on here for a while except for helping lol. You da man ell0bo.