Re: [PHP] Fast search

2006-05-17 Thread Evan Priestley
You can make a pretty effective time/memory tradeoff -- particularly  
if your array of patterns is relatively fixed -- but unless you re- 
implement this in C, it will probably be slower than a brute force  
approach with the str* functions unless you are searching for a  
fairly huge number of needles.


Below, I build a tree of pattern matches, which you navigate branch- 
by-branch by using successive letters of the pattern. So, after the  
tree is built, the index $tree[ 'h' ][ 'a' ][ 't' ] exists and has  
the value `true'. To search the string, you push cursors onto a  
stack, advance them as you advance through the string, and destroy  
them when they hit a dead end.


This has a worst case of O( N^2 ) (on the length of the string),  
which happens when you search for patterns like a  
and b in the string h. The  
average case for random or typical strings should be very close to O 
( N ). Critically, search time is a function only of the length of  
the string, not of the number of patterns. Memory usage is also only  
a function of the size of the character set and the length of the  
longest pattern, not of the total number of patterns.


This particular implementation has some nice side-effects; uncomment  
the var_dump() line and note how 'pirate' and 'firm' have been  
optimized out of the tree in favor of 'pir' and 'fir'.


Evan

?php

$pattern = array(
 'hat'
,'hut'
,'blue dog'
,'blue cat'
,'pirate'
,'pir'
,'fir'
,'firm'
);

$tree = array( );
foreach( $pattern as $str ) {
$len = strlen( $str );
$cursor = $tree;
for( $ii = 0; $ii  $len; $ii++ ) {
if( !isset( $cursor[ $str[ $ii ] ] ) ) {
$cursor[ $str[ $ii ] ] = array( );
}
$cursor = $cursor[ $str[ $ii ] ];
if( $cursor === true ) break;
}
$cursor = true;
}

/*  var_dump 
( $tree );  */


$corpus = 'lorem ipsum dolor sur amet pi blue do he hi h fipir  
slog';

$clen   = strlen( $corpus );

$stack  = array( );
for( $ii = 0; $ii  $clen; $ii++ ) {
$c = $corpus[ $ii ];
foreach( $stack as $k = $_ ) {
if( isset( $stack[ $k ][ $c ] ) ) {
if( $stack[ $k ][ $c ] === true ) {
die( 'Matched at position '.$ii );
}
$stack[ $k ] = $stack[ $k ][ $c ];
}
else {
unset( $stack[ $k ] );
}
}
if( isset( $tree[ $c ] ) ) {
$stack[] = $tree[ $c ];
}
}
die( 'Did not find a match.' );

?



On May 17, 2006, at 12:37 PM, René Fournier wrote:

Looking for suggestions on the most compute-efficient way to search  
variable-length strings (~200 characters) for the occurrence of one  
of about 100 possible needles. In other words:




$needles = array ( 1 = Hello Jim , 2 = Yellow Banana , 3 =  
Red Car, ... etc  (100 elements)


$haystack = Once upon a time there was a programming language that  
everyone loved. Its name was PHP, and the people that worked with  
it also liked Yellow Bananas. One day...;




Now perhaps I'm blind, but I can't see an obvious string or array  
function that simply allows you to use an array as a needle while  
searching a string haystack. What I'm really looking for is  
something like the reverse of in_array.


The obvious thing would be to loop through the needles and run  
substr_count on the haystack... But is there a faster way?


...Rene

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Filter out MS Word 'quotes' for RSS

2006-04-26 Thread Evan Priestley


On Apr 26, 2006, at 5:45 AM, Kevin Davies wrote:

Obviously I need to convert these on entry, or on output into RSS.  
Does
anyone know of an easy way to do this, or is it a case of  
identifying each

unusual character individually?


These high-ascii characters have ord() values greater than 126. If  
you're rendering to HTML, you can go through your string converting  
them into '#ord_value;', where `ord_value' is the return from ord()  
(so your result looks like #210;), which will fix the primary  
problem (things breaking) and should at least limit the damage on the  
secondary problem (loss of information). In my experience, however,  
this will clobber some entities pretty badly. Alternatively, you can  
just zap them (into * or ~ or some other printable character),  
which will work better for text rendering.


You can also mix the two, by identifying individually those  
characters that you are concerned with preserving and zapping the  
others, e.g.


?php

/**
* Validate a string as being gremlin-free text. Characters with  
ordinal value

* greater than 126 will be converted into the best equivalent.
*
* @param any Something which might be a string.
*
* @returns array|bool True (valid), false (not valid), or an array of
*  unconverted exception ordinal values (valid but dirty).
*/
function validate_text( $text ) {

static $conversions = array(
 // Windows  Word
 133= 'hellip;'
,145= 'lsquo;'
,146= 'rsquo;'
,147= 'ldquo;'
,148= 'rdquo;'
,149= 'bull;'
,150= 'ndash;'
,151= 'mdash;'

 // Mac
,165= 'bull;'
,208= 'ndash;'
,209= 'mdash;'
,210= 'ldquo;'
,211= 'rdquo;'
,212= 'lsquo;'
,213= 'rsquo;'
);

if( is_scalar( $text ) || is_null( $text ) ) {

$corpus = str_replace(
 array_map( 'chr', array_keys( $conversions ) )
,$conversions
,$text
);

$gremlins = array( );

for( $ii = 0; $ii  strlen( $corpus ); $ii++ ) {
if( ($ordv = ord( $corpus[ $ii ]) )  126 ) {
$gremlins[ $ii ] = $ordv;
$corpus[ $ii ] = '*';
}
}

$text = $corpus;

if( count( $gremlins ) ) {
return $gremlins;
}

return true;
}

return false;
}

?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] New Help with Javascript Navigation

2006-04-26 Thread Evan Priestley
Tell you what: write file_get_contents() in Javascript, and I'll  
write the rest of it.


Evan

On Apr 26, 2006, at 4:36 PM, Warren Vail wrote:

This brings up a reoccurring issue for me and I'd be interested if  
anyone

else has given it any thought.

PHP appears to me to be incomplete unless it can provide a way to  
provide
client (browser) side executables in a consistent language, namely  
PHP.

Developers get all excited about the elegence of the PHP language, and
somewhere along the way they discover they have been sandbagged  
(they have

to learn Javascipt too, if they want responsive GUI's).

One solution would be to develop a PHP Plugin and support that for  
all the
browsers out there, but another just occurred to me.  What if there  
was a
function that accepted PHP code as input and tranlated it to  
Javascript,

returning the resulting text ready for imbedding in html?

Any creative masochists out there?  Has it already been attempted?

Warren Vail

-Original Message-
From: Jay Blanchard [mailto:[EMAIL PROTECTED]
Sent: Wednesday, April 26, 2006 1:07 PM
To: Pub; php-general@lists.php.net
Subject: RE: [PHP] New Help with Javascript Navigation

Pub,

Thank you for subscribing to and participating in the PHP users  
list, a
place where your PHP questions can be answered. Unfortunately your  
last post

contained several problems;

a. It was to long.
2. it was a JavaScript question.

Thank you,

Jay

--
PHP General Mailing List (http://www.php.net/) To unsubscribe, visit:
http://www.php.net/unsub.php

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] New Help with Javascript Navigation

2006-04-26 Thread Evan Priestley
No, I'm saying that Javascript can't read or write files on the  
client's machine, and that this is only one of a large number of  
basic limitations in the language's capabilities. It would be  
possible to write a script which took $a = 3 and converted it into  
var a = 3, but a huge number of PHP functions either can't be  
implemented in Javascript (file_get_contents) or are fundamentally  
unsafe to implement in Javascript (mysql_query), so you'd end up with  
a language you couldn't do anything with.


Evan

On Apr 26, 2006, at 5:07 PM, Warren Vail wrote:


Evan,

Are you proposing something like AJAX does? My understanding is  
limited
here, so bear with me.  A control like a hidden imbedded frame  
(IFRAME) is
acted upon by Javascript to cause it to dynamically request loading  
a page
into the frame, and when loaded, the javascript processes the  
contents of

the frame without necessarily displaying it directly?

And then do the translation on the client?

Could work, but I was thinking more of doing the tranlation in a  
function in

PHP, but that may be because PHP is my perspective.  Something like;

--- snip --
Html stuff
?php echo scripttranslate(
Php code follows here Careful with quotes); ?
More html stuff
--- snip --

Or

--- snip --
Echo html stuff here
.scripttranslate(php stuff here...
. again carefull with quotes)
.more html stuff here); // end of echo statement
--- snip --

Warren

-Original Message-
From: Evan Priestley [mailto:[EMAIL PROTECTED]
Sent: Wednesday, April 26, 2006 1:47 PM
To: Warren Vail
Cc: PHP General List
Subject: Re: [PHP] New Help with Javascript Navigation

Tell you what: write file_get_contents() in Javascript, and I'll  
write the

rest of it.

Evan

On Apr 26, 2006, at 4:36 PM, Warren Vail wrote:


This brings up a reoccurring issue for me and I'd be interested if
anyone else has given it any thought.

PHP appears to me to be incomplete unless it can provide a way to
provide client (browser) side executables in a consistent language,
namely PHP.
Developers get all excited about the elegence of the PHP language,  
and

somewhere along the way they discover they have been sandbagged (they
have to learn Javascipt too, if they want responsive GUI's).

One solution would be to develop a PHP Plugin and support that for  
all

the browsers out there, but another just occurred to me.  What if
there was a function that accepted PHP code as input and tranlated it
to Javascript, returning the resulting text ready for imbedding in
html?

Any creative masochists out there?  Has it already been attempted?

Warren Vail

-Original Message-
From: Jay Blanchard [mailto:[EMAIL PROTECTED]
Sent: Wednesday, April 26, 2006 1:07 PM
To: Pub; php-general@lists.php.net
Subject: RE: [PHP] New Help with Javascript Navigation

Pub,

Thank you for subscribing to and participating in the PHP users list,
a place where your PHP questions can be answered. Unfortunately your
last post contained several problems;

a. It was to long.
2. it was a JavaScript question.

Thank you,

Jay

--
PHP General Mailing List (http://www.php.net/) To unsubscribe, visit:
http://www.php.net/unsub.php

--
PHP General Mailing List (http://www.php.net/) To unsubscribe, visit:
http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/) To unsubscribe, visit:
http://www.php.net/unsub.php






--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] newbie question

2006-04-05 Thread Evan Priestley


On Apr 5, 2006, at 11:41 AM, Jay Blanchard wrote:


p?php echo n12br($row_Recordset1['Writings_Text']); ?/p

 ^

Not sure if this is just a transcription error, but that should be an  
'l' (ell), not a '1' (one) in nl2br.


Evan

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] protecting passwords when SSL is not available

2006-03-28 Thread Evan Priestley

This looks good, as far as I can tell. Good luck with implementation.

Evan

On Mar 28, 2006, at 2:51 AM, Satyam wrote:


You are absolutely right!  I love this list!

I didn't realize that I was sending the session_id. Let's see if  
this works.


On first serving the login page I create a session and also a  
unique_id via uniqid().   I store the unique_id in the session and  
send it as a challenge to the client along the login form.  This  
unique_id is the nonce. Upon receiving the login data and checking  
it for good, I delete the unique_id from the session.  If I receive  
a made up session_id, the password data won't match the unique_id  
stored in the session (probably there will be none).  The nonce  
stored in the session will be a new one, even for the same session,  
each time the login screen is requested.  If the login fails, upon  
retry a new unique_id will be generated and sent for the retry.   
Thus, session_ids and unique_ids combinations (almost) never get  
repeated.  Thus, is you knew the answer to one, it won't help you  
with any other because even if you can make up a session_id, you  
cannot change the unique_id the server made and, since unique_ids  
don't repeat, there is no chance that you have ever sniffed the  
password hashed with that unique_id.



Satyam


- Original Message - From: Evan Priestley [EMAIL PROTECTED]
To: Satyam [EMAIL PROTECTED]
Cc: php-general@lists.php.net
Sent: Monday, March 27, 2006 11:58 PM
Subject: Re: [PHP] protecting passwords when SSL is not available


The client cannot and does not send the session_id() used to  
hash  the password back to the server, it does not need to, the  
client  got it from the server.


It does send the session ID back though, because that's how the  
user maintains their session across requests.


For simplicity, let the totally made up word noncehash represent  
hash(hash(password)+nonce) -- that is, the hash of 'the nonce   
appended to the hash of the password'.


Generally, if the client ONLY sends (a) a user name and (b) a   
noncehash, then the server has no way to tell which nonce was   
originally issued. Therefor, the client has to send (a) a user  
name,  (b) a noncehash, and (c) some key which can identify which  
nonce was  sent. This key might be the session ID, the nonce  
itself, or  something else[1].


If the key is the nonce itself and the only server-side validation  
is that the response noncehash is correct for the supplied nonce,   
attacker Bob can observe ANY valid nonce/noncehash combination  
Alice  submits and replay it to gain access[2].


If the key is the session ID, and the only server-side validation  
is still that the response noncehash is correct for the given  
session  ID, attacker Bob can STILL observe ANY valid session ID /  
noncehash combination Alice submits (she _is_ submitting the  
session ID -- the nonce, here -- because every request always  
includes the session ID  when sessions are being used) and replay  
it immediately to gain  access. This is session hijacking, and  
it works because PHP will  let Bob into Alice's session as long as  
he knows her session ID[3].


Instead, suppose the server-side validation is a little stronger:  
it checks that the response noncehash is correct for the given  
session  ID, but ALSO checks to make sure that this session ID  
hasn't logged  in yet. Now Bob can't replay the response  
immediately. He can still  just hijack the logged-in session,  
though, and he might be able to  replay the attack after Alice's  
session has expired, because the flag  that says this session has  
already logged in will also have  expired. I'm not sure if PHP  
will create an expired session ID for  you; presumably it won't,  
but if you're writing your own session  handler or implementing  
nonced password transmission in some other  programming language,  
this might be a viable attack vector.


Evan

[1] It could even be the username, if the login process went like   
this: client sends server username, server generates a nonce and   
stores it in the user table, server sends generated nonce to  
client,  client sends hash(hash(password)+nonce) to server -- but  
then an  attacker can perform a DOS attack by repeatedly sending  
the server a  username so that it regenerates nonces more quickly  
than the real  user can log in. In any case, (a), (b) and (c) do  
not necessarily  need to be three separate pieces of information,  
since one piece of  information can serve multiple roles.
[2] Unless nonces are stored in a database and flagged as used  
afterward. You can also, e.g., generate nonces in the form  
timestamp,hash(timestamp+secret); google for more on this.
[3] Unless you're e.g. restricting sessions by IP, but this is  
potentially a whole different can of worms.





It is the server that challenges the client with a session_id()  
(or  any other random) sent clear and the client has to take the   
challenge and combine

Re: [PHP] protecting passwords when SSL is not available

2006-03-27 Thread Evan Priestley
This is called a nonce[1], and the method you've described will  
give you marginally less awful security than submitting a plaintext  
password or an unadulterated hash of the password, but, obviously, is  
in no way a substitute for real SSL. For instance, if this password  
puts the session in a logged in state, an attacker with the  
capacity to sniff the password can also sniff the logged in session  
ID after authentication. You can potentially bind the login to IP,  
but will prevent users behind rotating proxies from using your  
service and may not protect users behind non-rotating proxies, and  
the source IP for a request can be spoofed. Alternatively, you can  
require the password for any action requiring authorization (and  
never put the user in a logged in state), but this will impose  
substantial constraints on your design. And, of course, an attacker  
can still observe any other data you transmit.


If you implement nonced password transmission, absolutely ensure that  
an attacker can not alter the provided nonce. For instance, if Bob  
sees Alice log in under nonce abc123 (her PHP session ID), what  
happens if Bob later executes a replay attack by mimicking her form  
submission (username: alice, password_hash: def456, session_id:  
abc123)? If he can gain access via replay attack at any time after  
Alice's first login ([a] while her session is valid or [b] after it  
has expired presumably being the critical periods), the system offers  
no security over non-nonced password transmission.


Evan

[1] http://en.wikipedia.org/wiki/Nonce

On Mar 27, 2006, at 8:30 AM, Satyam wrote:

I know the answer to a secure site is SSL, but what if you are on a  
shared host, SSL is unavailable and you still want some sort of  
security?


This is what I came by and I would appreciate any advice as to  
possible security holes in it.  There is a big hole I know, which  
is the screen to change the password, I find no way to secure that  
one.  But lets go to what I do have.


I found at http://pajhome.org.uk/crypt/md5/md5src.html a Javascript  
version of the MD5 algorithm.

I checked it against the PHP md5() function:

htmlheadtitleMD5 test/title
script language=JavaScript src=includes/md5.js/script
script
function enOnLoad() {
 document.getElementById('prueba').innerHTML = md5_vm_test(); // 
test provided by the library

 ?php
  $valor = rand();
 ?
 document.getElementById('p2').innerHTML = hex_md5('?=$valor?');
}
/script
/headbody onLoad=enOnLoad();
div id=prueba/div
div id=p2/div
div?=md5($valor)?/div
/body/html

And the results of the Javascript and the PHP md5() functions are  
the same (the JS source has a couple of parameters to play with,  
but the defaults proved good enough)


So, my idea is that in the login script, PHP will send a random  
number along with the login form. That random might actually be the  
session_id() but if not, the random value sent has to be stored in  
a session variable. (I really don't see any reason not to use the  
session_id()).


On clicking on submit to send the login form, the password field  
would be replaced by the result of


a) calculate the MD5() of the password, trimmed of whitespace.   
This should be the same value stored in the user table of the  
database.
b) concatenate this value with the random number (or session_id())  
provided by the server.

c) calculate the MD5() of this
d) replace it into the original password field and let the submit  
proceed.


On the server side, when the login data is received:

a) retrieve the password field from the user table on the  
database.  This should actually be the MD5-encripted of the actual  
password.
b) concatenate this value with the session_id() or whatever random  
you generated before

c) calculate the MD5() of this
d) compare with received value.  If they match, they come from the  
same password.


Would it work?

Satyam

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] protecting passwords when SSL is not available

2006-03-27 Thread Evan Priestley
The client cannot and does not send the session_id() used to hash  
the password back to the server, it does not need to, the client  
got it from the server.


It does send the session ID back though, because that's how the user  
maintains their session across requests.


For simplicity, let the totally made up word noncehash represent  
hash(hash(password)+nonce) -- that is, the hash of 'the nonce  
appended to the hash of the password'.


Generally, if the client ONLY sends (a) a user name and (b) a  
noncehash, then the server has no way to tell which nonce was  
originally issued. Therefor, the client has to send (a) a user name,  
(b) a noncehash, and (c) some key which can identify which nonce was  
sent. This key might be the session ID, the nonce itself, or  
something else[1].


If the key is the nonce itself and the only server-side validation is  
that the response noncehash is correct for the supplied nonce,  
attacker Bob can observe ANY valid nonce/noncehash combination Alice  
submits and replay it to gain access[2].


If the key is the session ID, and the only server-side validation is  
still that the response noncehash is correct for the given session  
ID, attacker Bob can STILL observe ANY valid session ID / noncehash  
combination Alice submits (she _is_ submitting the session ID -- the  
nonce, here -- because every request always includes the session ID  
when sessions are being used) and replay it immediately to gain  
access. This is session hijacking, and it works because PHP will  
let Bob into Alice's session as long as he knows her session ID[3].


Instead, suppose the server-side validation is a little stronger: it  
checks that the response noncehash is correct for the given session  
ID, but ALSO checks to make sure that this session ID hasn't logged  
in yet. Now Bob can't replay the response immediately. He can still  
just hijack the logged-in session, though, and he might be able to  
replay the attack after Alice's session has expired, because the flag  
that says this session has already logged in will also have  
expired. I'm not sure if PHP will create an expired session ID for  
you; presumably it won't, but if you're writing your own session  
handler or implementing nonced password transmission in some other  
programming language, this might be a viable attack vector.


Evan

[1] It could even be the username, if the login process went like  
this: client sends server username, server generates a nonce and  
stores it in the user table, server sends generated nonce to client,  
client sends hash(hash(password)+nonce) to server -- but then an  
attacker can perform a DOS attack by repeatedly sending the server a  
username so that it regenerates nonces more quickly than the real  
user can log in. In any case, (a), (b) and (c) do not necessarily  
need to be three separate pieces of information, since one piece of  
information can serve multiple roles.
[2] Unless nonces are stored in a database and flagged as used  
afterward. You can also, e.g., generate nonces in the form  
timestamp,hash(timestamp+secret); google for more on this.
[3] Unless you're e.g. restricting sessions by IP, but this is  
potentially a whole different can of worms.





It is the server that challenges the client with a session_id() (or  
any other random) sent clear and the client has to take the  
challenge and combine it with the password (which is not  
transmitted clear).  Thus the client cannot tell the server, 'this  
is user xxx, with password  hashed under session_id '.   It  
is the server that challenges the client with the session_id.  The  
attacker might collect enough samples so if a challenge repeats, he  
can have the answer ready, but that is unlikely with long enough  
challenges (and session_ids are long).


As for sending the session_id() from the server to the client in  
clear (not encrypted) it seems to me it doesn't make any sense to  
alter it in any way since, after all, you are also sending the  
algorithm in Javascript to the client, which is clear for anyone to  
see, so there would be no point in trying to hide the session_id in  
any way, and I don't think it would help the overall security.


My bank does use SSL, of course, and it still requires confirmation  
to do critical processes so, that might be a partial solution to  
spoofing.


Anyway, this is a poor man replacement for SSL, with limitations,  
but it is good to know what are those limitations.


Thanks for your help

Satyam



- Original Message - From: Evan Priestley [EMAIL PROTECTED]
To: Satyam [EMAIL PROTECTED]
Cc: php-general@lists.php.net
Sent: Monday, March 27, 2006 5:41 PM
Subject: Re: [PHP] protecting passwords when SSL is not available


This is called a nonce[1], and the method you've described will   
give you marginally less awful security than submitting a  
plaintext  password or an unadulterated hash of the password, but,  
obviously, is  in no way

Re: [PHP] Letters in Loops

2006-03-23 Thread Evan Priestley

?php
for( $ii = ord( 'A' ); ii = ord( 'Z' ); $ii++ ) {
echo chr( $ii );
}
?


On Mar 23, 2006, at 10:08 AM, Ben Miller wrote:


In trying to make an alpha list, using the following:

for($i=A;$i=Z;$i++) {
echo $i;
}

Produces:
A
B
C...
X
Y
Z
AA
AB
AC...
AX
AY
AZ... all the way to YZ.


What am I doing wrong that it's not stopping at just plain old Z,  
without

moving on to AA and continuing?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] gettting last assigned key in an array

2006-02-10 Thread Evan Priestley

function get_last_key( $array ) {
// end( $array ); return key( $array );
return array_search(
 reset( array_reverse( array_values( array_flip( $array ) ) ) )
,array_reverse( array_values( array_flip( $array ) ) )
,true
);
}


On Feb 10, 2006, at 2:39 PM, jonathan wrote:



im mapping some data from a sql select into a custom object that  
will have a couple associative arrays. I have some code that I  
think looks a little ugly such as:


$x=0;
if($row['slot']=2)
{
$this-menu_item[$x]['item_id']=$row['item_id'];
$this-menu_item[$x]['name']=$row['name'];
$this-menu_item[$x]['item_price']=$row['item_price'];
$x++;
}

I'd rather do something like this:
if($row['slot']=2)
{
$this-menu_item[]['item_id']=$row['item_id'];
$y=get_last_key();
$this-menu_item[$y]['name']=$row['name'];
$this-menu_item[$y]['item_price']=$row['item_price'];
}

but don't know if php has a built in for the get_last_key(); any  
thoughts would be appreciated (including whether you think the  
original code snippet is fine.


-jonathan

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Need help with for loop, pulling MySQL data, completely lost

2005-08-21 Thread Evan Priestley

Dan,

When you run the second query ($query1), its results overwrite the  
results of your first query ($query0). `mysql_fetch_assoc()'  
returns results from the _most recent_ query, so after the first  
iteration, the call to `mysql_fetch_assoc()' is returning results  
from `query1', not from `query0'.


To solve this, retrieve all data from `query0' before iterating over  
it. Sample code in /painstakingly exact/ PHP which I have tested  
extensively:


?php

run query0

while( rows exist )
$rows[] = get next row

foreach $rows
for i = 0; i = 0; i-- {
   build query1
   run query1
   }
?

Excellent description of your problem, by the way; this one's tricky  
and definitely had me for a while when I first ran into it.


Evan

On Aug 21, 2005, at 7:24 AM, Dan Trainor wrote:


Hello, all -

As a pet project of mine, I've decided to write a bit of code.   
This is what I have, and it's not working as expected:


if ($action == prepareforupdate) {
@unlink(UPDATES/.$id./9.jpg);
$query0= SELECT * FROM updates WHERE id=.$id.;
if (!$dbdata = mysql_query($query0)) {
echo Can't run query:  .mysql_error();
die;
};

for ($i = 9; $i = 0; $i--) {
$j = $i - 1;

echo Getting ready to rename UPDATES/$id/$j.jpg to
  UPDATES/$id/$i.jpg || nbsp;nbsp;nbsp;nbsp;br /;

@rename(UPDATES/$id/$j.jpg,UPDATES/$id/$i.jpg);

$returned = mysql_fetch_assoc($dbdata);

$query1 = UPDATE updates SET  . $i . d = '
  .$returned[$j.d]. ' WHERE id=' . $id . ';

if (!mysql_query($query1)) {
echo MySQL Error:  .mysql_error();
};

}
}


I have a database in the following format.  Let's say that d  
stands for date, and t stands for times, and I have ten days'  
worth of archives going on:


|id|1d|1t|2d|2t|3d|3t|...|8d|8t|9d|9t|

I'm trying to move the contents of the previous field to the  
logical next field, so the value of field 8d becomes 9d, the  
value of 7t becomes the value of 8t, and so on.


The problem that I'm having here is that only the first iteration  
of the for loop work properly.  Everything after that, is not being  
pulled up properly, I suspect.  This is what MySQL shows:


174 Query   SELECT * FROM updates WHERE id=5
174 Query   UPDATE updates SET 9d = '2005-08-21' WHERE id='5'
174 Query   UPDATE updates SET 8d = '' WHERE id='5'

174 Query   UPDATE updates SET 1d = '' WHERE id='5'
174 Query   UPDATE updates SET 0d = '' WHERE id='5'

So all in all, I think I might be a bit out of my league here, but  
I am eager to learn.  I think of this as more of a dynamic approach  
to a situation that I'm trying to adapt to.


As always, any feedback, or flames for that matter, would be  
greatly appreciated.


Thanks
-dant

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php