Reg Exp and a SQl code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xudzh
Forum Commoner
Posts: 48
Joined: Sat Feb 19, 2005 6:22 pm

Reg Exp and a SQl code

Post by xudzh »

Below is a message script.

1.

Code: Select all

їphp]$tomsg=$_POSTї'outmsg'];//get receive data;
$regї0]='';//check if msg contains nothing more than spaces
$pattern='^\s*$';
$regcheck=ereg($pattern,$tomsg,$reg);
if ($regcheck) {header("Location: index.php");
	      die();
	     }ї/php]
I want to check if $_POST['outmsg'] contains nothing more than spaces. And if it does, exit. But $regcheck never returns true.

2.

Code: Select all

їphp]
$query=mysql_query("select * from dk_insmsg where receiver='$userrowїusername]'") or die(mysql_error());
$from=$userrowї'charname'];//sender variable

$to=$to1ї'username'];//receiver variable
$date=time();//now
if (mysql_num_rows($query)>4) {//if too much msgs
	$query2=mysql_query("select id from dk_insmsg where receiver='$userrowїusername]' ORDER BY timesent LIMIT 1") or die(mysql_query());
	$query3=mysql_fetch_array($query2);//oldest msg
	$q3id=$query3ї'id'];//get its id
	$query4=mysql_query("replace into dk_insmsg (id,sender,receiver,msg,timesent) values ($q3id,'$from','$to','$tomsg',$date)") or die('cannot replace old msg');//replace old msg
header("Location: index.php");die();//exit
			      }
else { 
	$thequery=mysql_query("insert into dk_insmsg (sender,receiver,msg,timesent) values ('$from','$to','$tomsg',$date)") or die('cannot sent msg');//duh
header("Location: index.php");die();//exit
	}
if (mysql_num_rows($query)>4) means that if there are more than 4 messages for a user, replace the oldest message with a new one. But the oldest message was never replaced even when there are 8 messages for a user.

Can anyone help me solve there 2 problems? Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

1.

Code: Select all

if(strlen(trim($_POSTї'outmsg'])) == 0)
2. you may have an error in your replace query syntax.
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

I am too lazy to read all that, but here is a couple of tips:

1.
Never use ereg, it wastes resources, if you need the power of regex use preg!

2.
Never use regex unless you really need to. Functions like str_replace, strstr, strpos can do a lot without spending too many resources.

-

Your pattern in that first piece of code does not make sense...
If you just want to test if something is an empty string, do something like this:

Code: Select all

<?php
  if (isset($_POST['blah']) && trim($_POST['blah']))
  {
      // It contains something
  }
  else
  {
      // It is not set, an empty string, or int 0 or string "0"
  }
?>
edit/add: I have no idea why that php block dont work, BBCode is on, doing such worked fine in the past...
Last edited by Stoker on Sun Feb 20, 2005 1:43 pm, edited 3 times in total.
User avatar
smpdawg
Forum Contributor
Posts: 292
Joined: Thu Jan 27, 2005 3:10 pm
Location: Houston, TX
Contact:

Post by smpdawg »

First. Why not just use trim() and look at the result rather that doing a regex?

Second. Does the ID field have a primary key or unique index? Without it, you cannot do a replace.
xudzh
Forum Commoner
Posts: 48
Joined: Sat Feb 19, 2005 6:22 pm

Post by xudzh »

Yes, trim();

---
New to php, didn't know that function before.
User avatar
smpdawg
Forum Contributor
Posts: 292
Joined: Thu Jan 27, 2005 3:10 pm
Location: Houston, TX
Contact:

Post by smpdawg »

Did you answer the second question? Do you have a unique index on the ID field that you are trying to replace?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

btw, i've experienced that regex _is_ faster than is_numeric tests etc...

so if you care about optimization, please do your own benchmarking :)
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

is_numeric may be slower than regex, I never used that function, in general I use typecasting for such instead, but stuff like finding a simple word or phrase or replacing single words or phrases is definetely quicker with the native PHP functions..
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

actually, I started thinking about this, not that it really matters, but I threw together a loop-test of doing close to the same as is_numeric with a preg, and my test concluded that my php-4 on a Linux P4-2.4 50K tests took .28s with regex and .19s with is_numeric..

I am guessing that perhaps you had a simpler regex in your test?

Here's the code I threw together:

Code: Select all

<?php

   class test_regex_isnumeric extends sau_profiling
   &#123;

     var $testwith;
     var $count;
     var $regex_positive = 0;
     var $regex_negative = 0;
     var $isnum_positive = 0;
     var $isnum_negative = 0;

     function test_regex_isnumeric($testcount = 50000, $testwith = '1.2345')
     &#123;
        $this->logtime ('Object instatinated');
        $this->testwith = $testwith;
        $this->count = $testcount;
     &#125;

     function test_regex ()
     &#123;
        $this->logtime ('Starting test_regex');
        for ($i=$this->count; $i>0; $i--)
        &#123;
          if (preg_match('/^&#1111;0-9]*(\.&#1111;0-9]+)?$/',(string) $this->testwith))
             $this->regex_positive++;
          else
             $this->regex_negative++;
        &#125;
        $this->logtime ('Ended test_regex, pos: '.$this->regex_positive. ' neg: '.$this->regex_negative);
     &#125;

     function test_isnum ()
     &#123;
        $this->logtime ('Starting test_isnum');
        for ($i=$this->count; $i>0; $i--)
        &#123;
          if (is_numeric($this->testwith))
             $this->isnum_positive++;
          else
             $this->isnum_negative++;

        &#125;
        $this->logtime ('Ended test_isnum, pos: '.$this->isnum_positive. ' neg: '.$this->isnum_negative);
     &#125;

   &#125;

   // Abstract
   class sau_profiling
   &#123;

      var $timelog = array();

      function logtime ($logtext)
      &#123;
         $this->timelog&#1111;] = array ((float) array_sum(explode(' ',microtime())), $logtext);
      &#125;

      function getlog ()
      &#123;
         $return = '';
         $last = 0.00;
         foreach ($this->timelog as $t)
         &#123;
            $return .= $t&#1111;0]."\t".($last ? ('+'.sprintf('%01.2f',$t&#1111;0]-$last)) : '0.00' )."\t".$t&#1111;1]."\n";
            $last = $t&#1111;0];

         &#125;
         return $return;
      &#125;

   &#125;


   $t = new test_regex_isnumeric (50000, '1.2345');

   $t->test_regex();
   $t->test_isnum();
   echo $t->getlog();

?>
xudzh
Forum Commoner
Posts: 48
Joined: Sat Feb 19, 2005 6:22 pm

Post by xudzh »

For my 2nd question what i wanted to do is that I want to limit the messages for each user to 4. When they reach 5, replace the oldest message with the new one. id is the primary key.

I did experiment with it, and find out that for some reason

Code: Select all

if (mysql_num_rows($query)>4)
never returned true.

Here is the whole script:

Code: Select all

<?php
function insmsgpeople() &#123;
if (!($_POST&#1111;'outmsg']&&$_POST&#1111;'tousers'])) &#123;header("Location: index.php");//exit
die();&#125; // if msg or receiver not set, then exit
global $userrow;
if (!isset($userrow)) &#123;header("Location: index.php");//exit
die();&#125;
$tomsg=$_POST&#1111;'outmsg'];//get receive data;
if(strlen(trim($_POST&#1111;'outmsg'])) == 0)&#123;header("Location: index.php");
	      die();
	     &#125;
$tomsg=addslashes($tomsg);//escaping char in Javascript
if (!get_magic_quotes_gpc()) &#123;//if  magic quotes is off
	$tomsg=addslashes($tomsg); //slashes for security
			     &#125; 
if (strlen($tomsg)>249) &#123;//too long
      	$tosmg=substr($tomsg,0,245)."...";//get rid some
			&#125;//tomsg purify complete
	

$receiver=$_POST&#1111;'tousers']+0;//get receiver and turn into number.
if (!settype($receiver,"integer")) &#123;quitme('index.php');&#125; //if not number then go to index
$wholine=mysql_query("SELECT * FROM dk_users WHERE (UNIX_TIMESTAMP(onlinetime) >= '".(time()-600)."') AND (id=$receiver) ORDER BY charname") or die(mysql_error());//see if receiver is online

$to1=mysql_fetch_array($wholine);
if (!$to1) &#123;//if not
header("Location: index.php");//exit
die();
		&#125;
$time=time()-300;//5 min ealier
$query=mysql_query("delete from dk_insmsg where (receiver='$userrow&#1111;username]') and (timesent<$time)") or die('cannot delete old msgs');//duh
$query=mysql_query("select * from dk_insmsg where receiver='$userrow&#1111;username]'") or die(mysql_error());
$from=$userrow&#1111;'charname'];//sender variable

$to=$to1&#1111;'username'];//receiver variable
$date=time();//now
if (mysql_num_rows($query)>4) &#123;//if too much msgs
	die("too much old messages");
	$query2=mysql_query("select id from dk_insmsg where receiver='$userrow&#1111;username]' ORDER BY timesent LIMIT 1") or die(mysql_query());
	$query3=mysql_fetch_array($query2);//oldest msg
	$q3id=$query3&#1111;'id'];//get its id
	$query4=mysql_query("replace into dk_insmsg (id,sender,receiver,msg,timesent) values ($q3id,'$from','$to','$tomsg',$date)") or die('cannot replace old msg');//replace old msg
header("Location: index.php");die();//exit
			      &#125;
else &#123; 
	$thequery=mysql_query("insert into dk_insmsg (sender,receiver,msg,timesent) values ('$from','$to','$tomsg',$date)") or die('cannot sent msg');//duh
header("Location: index.php");die();//exit
	&#125;			
				&#125;


?>
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

you can limit the rows in a resultset, by using the LIMIT clause... read the mysql manual if you don't know how that clause works... :)


and you want probably pass $result to mysql_num_rows instead of the $query.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

i found the thread in comp.lang.php :)


http://groups.google.be/groups?hl=nl&lr ... 6rnum%3D17

Code: Select all

<?php
error_reporting(E_ALL);

function test1($string, $needed) &#123;
  $found = '';
  $index = 0;

  while (strlen($found) < $needed && $index < strlen($string)) &#123;
    if (is_numeric($string&#123;$index&#125;)) &#123;
      $found .= $string&#123;$index&#125;;
    &#125; ++$index;
  &#125; return $found;
&#125;

function test2($string) &#123;
  $dig = substr(preg_replace("/\D/",'',$string),0,2);
  return $dig;
&#125;


$strings = array(
  '12sqdmfksdjflmqsdfjlm',
  'sdfsqdf3mkjmklj4',
  'a56qsdfmqsdfkj',
  'sdf7dqfdsf8dqfdf',
  'a    20adiidkk4kidid39399399dkkdkkkdk'
);

$start = microtime(true);
foreach($strings as $string) &#123;
  test1($string,2);
&#125;
$end = microtime(true);
echo '<br>total: ' . ($t1 = $end - $start);

$start = microtime(true);
foreach($strings as $string) &#123;
  test2($string);
&#125;
$end = microtime(true);
echo '<br>total: ' . ($t2 = $end - $start);
echo '<br> t1/t2 = ' . round($t1/$t2, 4) . 'x';

?>
User avatar
smpdawg
Forum Contributor
Posts: 292
Joined: Thu Jan 27, 2005 3:10 pm
Location: Houston, TX
Contact:

Post by smpdawg »

As an experiment, try changing this

Code: Select all

$query=mysql_query("select * from dk_insmsg where receiver='$userrow&#1111;username]'") or die(mysql_error());
to this

Code: Select all

$query=mysql_query("select * from dk_insmsg where receiver='" . $userrow&#1111;'username'] . "'") or die(mysql_error());
or this

Code: Select all

$query=mysql_query("select * from dk_insmsg where receiver='&#123;$userrow&#1111;username]&#125;'") or die(mysql_error());
Those are curly braces in there, not parentheses. On my system it is hard to see the difference but it is important.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

or as how i would write it :)

Code: Select all

$query=mysql_query("select * from dk_insmsg where receiver='&#123;$userrow&#1111;'username']&#125;'") or die(mysql_error());
User avatar
smpdawg
Forum Contributor
Posts: 292
Joined: Thu Jan 27, 2005 3:10 pm
Location: Houston, TX
Contact:

Post by smpdawg »

I see we have a smart ass here. :D I might just go to your site and post some comments wooohahahaha... :lol:
Post Reply