Page 1 of 1
Reg Exp and a SQl code
Posted: Sun Feb 20, 2005 1:25 pm
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
Posted: Sun Feb 20, 2005 1:33 pm
by feyd
1.
Code: Select all
if(strlen(trim($_POSTї'outmsg'])) == 0)
2. you may have an error in your replace query syntax.
Posted: Sun Feb 20, 2005 1:37 pm
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...
Posted: Sun Feb 20, 2005 1:38 pm
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.
Posted: Sun Feb 20, 2005 2:58 pm
by xudzh
Yes, trim();
---
New to php, didn't know that function before.
Posted: Sun Feb 20, 2005 3:06 pm
by smpdawg
Did you answer the second question? Do you have a unique index on the ID field that you are trying to replace?
Posted: Sun Feb 20, 2005 4:04 pm
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

Posted: Sun Feb 20, 2005 4:18 pm
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..
Posted: Sun Feb 20, 2005 5:41 pm
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
{
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')
{
$this->logtime ('Object instatinated');
$this->testwith = $testwith;
$this->count = $testcount;
}
function test_regex ()
{
$this->logtime ('Starting test_regex');
for ($i=$this->count; $i>0; $i--)
{
if (preg_match('/^ї0-9]*(\.ї0-9]+)?$/',(string) $this->testwith))
$this->regex_positive++;
else
$this->regex_negative++;
}
$this->logtime ('Ended test_regex, pos: '.$this->regex_positive. ' neg: '.$this->regex_negative);
}
function test_isnum ()
{
$this->logtime ('Starting test_isnum');
for ($i=$this->count; $i>0; $i--)
{
if (is_numeric($this->testwith))
$this->isnum_positive++;
else
$this->isnum_negative++;
}
$this->logtime ('Ended test_isnum, pos: '.$this->isnum_positive. ' neg: '.$this->isnum_negative);
}
}
// Abstract
class sau_profiling
{
var $timelog = array();
function logtime ($logtext)
{
$this->timelogї] = array ((float) array_sum(explode(' ',microtime())), $logtext);
}
function getlog ()
{
$return = '';
$last = 0.00;
foreach ($this->timelog as $t)
{
$return .= $tї0]."\t".($last ? ('+'.sprintf('%01.2f',$tї0]-$last)) : '0.00' )."\t".$tї1]."\n";
$last = $tї0];
}
return $return;
}
}
$t = new test_regex_isnumeric (50000, '1.2345');
$t->test_regex();
$t->test_isnum();
echo $t->getlog();
?>
Posted: Sun Feb 20, 2005 5:51 pm
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
never returned true.
Here is the whole script:
Code: Select all
<?php
function insmsgpeople() {
if (!($_POSTї'outmsg']&&$_POSTї'tousers'])) {header("Location: index.php");//exit
die();} // if msg or receiver not set, then exit
global $userrow;
if (!isset($userrow)) {header("Location: index.php");//exit
die();}
$tomsg=$_POSTї'outmsg'];//get receive data;
if(strlen(trim($_POSTї'outmsg'])) == 0){header("Location: index.php");
die();
}
$tomsg=addslashes($tomsg);//escaping char in Javascript
if (!get_magic_quotes_gpc()) {//if magic quotes is off
$tomsg=addslashes($tomsg); //slashes for security
}
if (strlen($tomsg)>249) {//too long
$tosmg=substr($tomsg,0,245)."...";//get rid some
}//tomsg purify complete
$receiver=$_POSTї'tousers']+0;//get receiver and turn into number.
if (!settype($receiver,"integer")) {quitme('index.php');} //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) {//if not
header("Location: index.php");//exit
die();
}
$time=time()-300;//5 min ealier
$query=mysql_query("delete from dk_insmsg where (receiver='$userrowїusername]') and (timesent<$time)") or die('cannot delete old msgs');//duh
$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
die("too much old messages");
$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
}
}
?>
Posted: Sun Feb 20, 2005 6:16 pm
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.
Posted: Sun Feb 20, 2005 6:22 pm
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) {
$found = '';
$index = 0;
while (strlen($found) < $needed && $index < strlen($string)) {
if (is_numeric($string{$index})) {
$found .= $string{$index};
} ++$index;
} return $found;
}
function test2($string) {
$dig = substr(preg_replace("/\D/",'',$string),0,2);
return $dig;
}
$strings = array(
'12sqdmfksdjflmqsdfjlm',
'sdfsqdf3mkjmklj4',
'a56qsdfmqsdfkj',
'sdf7dqfdsf8dqfdf',
'a 20adiidkk4kidid39399399dkkdkkkdk'
);
$start = microtime(true);
foreach($strings as $string) {
test1($string,2);
}
$end = microtime(true);
echo '<br>total: ' . ($t1 = $end - $start);
$start = microtime(true);
foreach($strings as $string) {
test2($string);
}
$end = microtime(true);
echo '<br>total: ' . ($t2 = $end - $start);
echo '<br> t1/t2 = ' . round($t1/$t2, 4) . 'x';
?>
Posted: Sun Feb 20, 2005 7:31 pm
by smpdawg
As an experiment, try changing this
Code: Select all
$query=mysql_query("select * from dk_insmsg where receiver='$userrowїusername]'") or die(mysql_error());
to this
Code: Select all
$query=mysql_query("select * from dk_insmsg where receiver='" . $userrowї'username'] . "'") or die(mysql_error());
or this
Code: Select all
$query=mysql_query("select * from dk_insmsg where receiver='{$userrowїusername]}'") 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.
Posted: Sun Feb 20, 2005 9:29 pm
by timvw
or as how i would write it
Code: Select all
$query=mysql_query("select * from dk_insmsg where receiver='{$userrowї'username']}'") or die(mysql_error());
Posted: Sun Feb 20, 2005 9:32 pm
by smpdawg
I see we have a smart ass here.

I might just go to your site and post some comments wooohahahaha...
