php-general Digest 22 Feb 2011 16:40:17 -0000 Issue 7195

Topics (messages 311504 through 311526):

mysql_num_rows()
        311504 by: Gary
        311505 by: Deva
        311506 by: Daniel Molina Wegener
        311510 by: Andre Polykanine
        311511 by: Pete Ford
        311514 by: Gary
        311515 by: Gary
        311517 by: Gary
        311521 by: Pete Ford
        311524 by: Gary

How to write code: how wrong am I?
        311507 by: Dotan Cohen
        311508 by: Jay Blanchard
        311509 by: Marc Guay
        311512 by: Robert Cummings
        311513 by: Andy McKenzie
        311516 by: Dotan Cohen
        311518 by: Dotan Cohen
        311519 by: Dotan Cohen
        311520 by: Dotan Cohen
        311522 by: Robert Cummings
        311523 by: Robert Cummings
        311526 by: Dotan Cohen

Re: Regex pattern for preg_match_all
        311525 by: Yann Milin

Administrivia:

To subscribe to the digest, e-mail:
        [email protected]

To unsubscribe from the digest, e-mail:
        [email protected]

To post to the list, e-mail:
        [email protected]


----------------------------------------------------------------------
--- Begin Message ---
Can someone tell me why this is not working?  I do not get an error message, 
the results are called and echo'd to screen, the count does not work, I get 
a 0 for a result...



$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") or 
die(mysql_error());

if ( isset($_POST['submit']) ) {
for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county$i"] ) ) {
echo "You have chosen ". $_POST["county$i"]." <br/>";
        }
    }
}

$county_total=mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{$i++;
    echo $row['name'];
}
$county_total=mysql_num_rows($result);
echo "$county_total";

echo 'You Have '  .  "$county_total"  .  ' Counties ';

?>
-- 
Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5894 (20110221) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
I tried your script locally. Its working for me.

On Tue, Feb 22, 2011 at 11:10 AM, Gary <[email protected]> wrote:

> Can someone tell me why this is not working?  I do not get an error
> message,
> the results are called and echo'd to screen, the count does not work, I get
> a 0 for a result...
>
>
>
> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") or
> die(mysql_error());
>
> if ( isset($_POST['submit']) ) {
> for($i=1; $i<=$_POST['counties']; $i++) {
> if ( isset($_POST["county$i"] ) ) {
> echo "You have chosen ". $_POST["county$i"]." <br/>";
>        }
>    }
> }
>
> $county_total=mysql_num_rows($result);
>
> while($row = mysql_fetch_array($result))
> {$i++;
>    echo $row['name'];
> }
> $county_total=mysql_num_rows($result);
> echo "$county_total";
>
> echo 'You Have '  .  "$county_total"  .  ' Counties ';
>
> ?>
> --
> Gary
>
>
>
> __________ Information from ESET Smart Security, version of virus signature
> database 5894 (20110221) __________
>
> The message was checked by ESET Smart Security.
>
> http://www.eset.com
>
>
>
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


-- 
:DJ

--- End Message ---
--- Begin Message ---
On Tuesday 22 February 2011,
"Gary" <[email protected]> wrote:

> Can someone tell me why this is not working?  I do not get an error
> message, the results are called and echo'd to screen, the count does not
> work, I get a 0 for a result...

  Are you sure that the table is called `counties` and not `countries`?

  :)

> 
> 
> 
> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
> or die(mysql_error());
> 
> if ( isset($_POST['submit']) ) {
> for($i=1; $i<=$_POST['counties']; $i++) {
> if ( isset($_POST["county$i"] ) ) {
> echo "You have chosen ". $_POST["county$i"]." <br/>";
>         }
>     }
> }
> 
> $county_total=mysql_num_rows($result);
> 
> while($row = mysql_fetch_array($result))
> {$i++;
>     echo $row['name'];
> }
> $county_total=mysql_num_rows($result);
> echo "$county_total";
> 
> echo 'You Have '  .  "$county_total"  .  ' Counties ';
> 
> ?>

Best regards,
-- 
Daniel Molina Wegener <dmw [at] coder [dot] cl>
System Programmer & Web Developer
Phone: +56 (2) 979-0277 | Blog: http://coder.cl/

--- End Message ---
--- Begin Message ---
Hello Gary,

Please wrap $i in braces in your variable variable:

if ( isset($_POST["county{$i}"] ) ) {
echo "You have chosen ". $_POST["county{$i}"]." <br/>";

-- 
With best regards from Ukraine,
Andre
Skype: Francophile
My blog: http://oire.org/menelion (mostly in Russian)
Twitter: http://twitter.com/m_elensule
Facebook: http://facebook.com/menelion

------------ Original message ------------
From: Gary <[email protected]>
To: [email protected]
Date created: , 7:40:48 AM
Subject: [PHP] mysql_num_rows()


      Can someone tell me why this is not working?  I do not get an error 
message, 
the results are called and echo'd to screen, the count does not work, I get 
a 0 for a result...



$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") or 
die(mysql_error());

if ( isset($_POST['submit']) ) {
for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county$i"] ) ) {
echo "You have chosen ". $_POST["county$i"]." <br/>";
        }
    }
}

$county_total=mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{$i++;
    echo $row['name'];
}
$county_total=mysql_num_rows($result);
echo "$county_total";

echo 'You Have '  .  "$county_total"  .  ' Counties ';

?>
-- 
Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5894 (20110221) __________

The message was checked by ESET Smart Security.

http://www.eset.com





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


--- End Message ---
--- Begin Message ---
On 22/02/11 05:40, Gary wrote:
Can someone tell me why this is not working?  I do not get an error message,
the results are called and echo'd to screen, the count does not work, I get
a 0 for a result...



$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") or
die(mysql_error());

if ( isset($_POST['submit']) ) {
for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county$i"] ) ) {
echo "You have chosen ". $_POST["county$i"]."<br/>";
         }
     }
}

$county_total=mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{$i++;
     echo $row['name'];
}
$county_total=mysql_num_rows($result);
echo "$county_total";

echo 'You Have '  .  "$county_total"  .  ' Counties ';

?>

The first thing I see is that you do
  $county_total=mysql_num_rows($result)
twice. Now I'm not to sure, but it is possible that looping over mysql_fetch_array($result) moves an array pointer so the count is not valid after the operation... that's a long shot.

But since you are looping over the database records anyway, why not just count them as you go? Isn't $i the number of counties after all the looping?


--
Peter Ford, Developer                 phone: 01580 893333 fax: 01580 893399
Justcroft International Ltd.                              www.justcroft.com
Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United Kingdom
Registered in England and Wales: 2297906
Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XS

--- End Message ---
--- Begin Message ---
Thanks for your reply
"Deva" <[email protected]> wrote in message 
news:[email protected]...
>I tried your script locally. Its working for me.
>
> On Tue, Feb 22, 2011 at 11:10 AM, Gary <[email protected]> wrote:
>
>> Can someone tell me why this is not working?  I do not get an error
>> message,
>> the results are called and echo'd to screen, the count does not work, I 
>> get
>> a 0 for a result...
>>
>>
>>
>> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") 
>> or
>> die(mysql_error());
>>
>> if ( isset($_POST['submit']) ) {
>> for($i=1; $i<=$_POST['counties']; $i++) {
>> if ( isset($_POST["county$i"] ) ) {
>> echo "You have chosen ". $_POST["county$i"]." <br/>";
>>        }
>>    }
>> }
>>
>> $county_total=mysql_num_rows($result);
>>
>> while($row = mysql_fetch_array($result))
>> {$i++;
>>    echo $row['name'];
>> }
>> $county_total=mysql_num_rows($result);
>> echo "$county_total";
>>
>> echo 'You Have '  .  "$county_total"  .  ' Counties ';
>>
>> ?>
>> --
>> Gary



Thanks for your reply.

I'm curious, how did you try it locally without a database?

I am still getting either a 0 or a 1 for a result.

Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5895 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
"Daniel Molina Wegener" <[email protected]> wrote in message 
news:[email protected]...
> On Tuesday 22 February 2011,
> "Gary" <[email protected]> wrote:
>
>> Can someone tell me why this is not working?  I do not get an error
>> message, the results are called and echo'd to screen, the count does not
>> work, I get a 0 for a result...
>
>  Are you sure that the table is called `counties` and not `countries`?
>
>  :)
>
>>
>>
>>
>> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
>> or die(mysql_error());
>>
>> if ( isset($_POST['submit']) ) {
>> for($i=1; $i<=$_POST['counties']; $i++) {
>> if ( isset($_POST["county$i"] ) ) {
>> echo "You have chosen ". $_POST["county$i"]." <br/>";
>>         }
>>     }
>> }
>>
>> $county_total=mysql_num_rows($result);
>>
>> while($row = mysql_fetch_array($result))
>> {$i++;
>>     echo $row['name'];
>> }
>> $county_total=mysql_num_rows($result);
>> echo "$county_total";
>>
>> echo 'You Have '  .  "$county_total"  .  ' Counties ';
>>
>> ?>
>
> Best regards,
> -- 
> Daniel Molina Wegener <dmw [at] coder [dot] cl>
> System Programmer & Web Developer
> Phone: +56 (2) 979-0277 | Blog: http://coder.cl/


Daniel

Thank you for your reply, yes the database is named counties, working and 
returning results.

Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5895 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
"Pete Ford" <[email protected]> wrote in message 
news:[email protected]...
> On 22/02/11 05:40, Gary wrote:
>> Can someone tell me why this is not working?  I do not get an error 
>> message,
>> the results are called and echo'd to screen, the count does not work, I 
>> get
>> a 0 for a result...
>>
>>
>>
>> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'") 
>> or
>> die(mysql_error());
>>
>> if ( isset($_POST['submit']) ) {
>> for($i=1; $i<=$_POST['counties']; $i++) {
>> if ( isset($_POST["county$i"] ) ) {
>> echo "You have chosen ". $_POST["county$i"]."<br/>";
>>          }
>>      }
>> }
>>
>> $county_total=mysql_num_rows($result);
>>
>> while($row = mysql_fetch_array($result))
>> {$i++;
>>      echo $row['name'];
>> }
>> $county_total=mysql_num_rows($result);
>> echo "$county_total";
>>
>> echo 'You Have '  .  "$county_total"  .  ' Counties ';
>>
>> ?>
>
> The first thing I see is that you do
>   $county_total=mysql_num_rows($result)
> twice. Now I'm not to sure, but it is possible that looping over 
> mysql_fetch_array($result) moves an array pointer so the count is not 
> valid after the operation... that's a long shot.
>
> But since you are looping over the database records anyway, why not just 
> count them as you go? Isn't $i the number of counties after all the 
> looping?
>
>
> -- 
> Peter Ford, Developer                 phone: 01580 893333 fax: 01580 
> 893399
> Justcroft International Ltd. 
> www.justcroft.com
> Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United 
> Kingdom
> Registered in England and Wales: 2297906
> Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 
> 1XS


Peter

Thank you for your reply.

I did notice that I had the $county_total=mysql_num_rows($result) twice.  I 
had moved and removed it, always getting either a 0 or 1 result.

I put up another test page with

$result = mysql_query("SELECT * FROM `counties` ") or die(mysql_error());

$tot=mysql_num_rows($result);
echo "$tot";

?>

And it worked fine.

I have tried count() as well as mysql_num_rows() but am getting the same 
result.

Could you explain what you mean by count them as I go?

Again, Thank you for your reply.

Gary



__________ Information from ESET Smart Security, version of virus signature 
database 5895 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
On 22/02/11 13:59, Gary wrote:
"Pete Ford"<[email protected]>  wrote in message
news:[email protected]...
On 22/02/11 05:40, Gary wrote:
Can someone tell me why this is not working?  I do not get an error
message,
the results are called and echo'd to screen, the count does not work, I
get
a 0 for a result...



$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
or
die(mysql_error());

if ( isset($_POST['submit']) ) {
for($i=1; $i<=$_POST['counties']; $i++) {
if ( isset($_POST["county$i"] ) ) {
echo "You have chosen ". $_POST["county$i"]."<br/>";
          }
      }
}

$county_total=mysql_num_rows($result);

while($row = mysql_fetch_array($result))
{$i++;
      echo $row['name'];
}
$county_total=mysql_num_rows($result);
echo "$county_total";

echo 'You Have '  .  "$county_total"  .  ' Counties ';

?>

The first thing I see is that you do
   $county_total=mysql_num_rows($result)
twice. Now I'm not to sure, but it is possible that looping over
mysql_fetch_array($result) moves an array pointer so the count is not
valid after the operation... that's a long shot.

But since you are looping over the database records anyway, why not just
count them as you go? Isn't $i the number of counties after all the
looping?


--
Peter Ford, Developer                 phone: 01580 893333 fax: 01580
893399
Justcroft International Ltd.
www.justcroft.com
Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United
Kingdom
Registered in England and Wales: 2297906
Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17
1XS


Peter

Thank you for your reply.

I did notice that I had the $county_total=mysql_num_rows($result) twice.  I
had moved and removed it, always getting either a 0 or 1 result.

I put up another test page with

$result = mysql_query("SELECT * FROM `counties` ") or die(mysql_error());

$tot=mysql_num_rows($result);
echo "$tot";

?>

And it worked fine.

I have tried count() as well as mysql_num_rows() but am getting the same
result.

Could you explain what you mean by count them as I go?

Again, Thank you for your reply.

Gary



__________ Information from ESET Smart Security, version of virus signature 
database 5895 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





Well,

Lets go back to your original code and cut out the decoration:

$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
$county_total=mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
    echo $row['name'];
}
echo "$county_total";

That code should do pretty much what you want...

But, because you only show the number of records AFTER the loop, you could do:

$result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
$county_total = 0;
while($row = mysql_fetch_array($result))
{
    echo $row['name'];
    $county_total++;
}
echo "$county_total";





--
Peter Ford, Developer                 phone: 01580 893333 fax: 01580 893399
Justcroft International Ltd.                              www.justcroft.com
Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United Kingdom
Registered in England and Wales: 2297906
Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XS

--- End Message ---
--- Begin Message ---
"Pete Ford" <[email protected]> wrote in message 
news:[email protected]...
> On 22/02/11 13:59, Gary wrote:
>> "Pete Ford"<[email protected]>  wrote in message
>> news:[email protected]...
>>> On 22/02/11 05:40, Gary wrote:
>>>> Can someone tell me why this is not working?  I do not get an error
>>>> message,
>>>> the results are called and echo'd to screen, the count does not work, I
>>>> get
>>>> a 0 for a result...
>>>>
>>>>
>>>>
>>>> $result = mysql_query("SELECT * FROM `counties` WHERE name = 
>>>> 'checked'")
>>>> or
>>>> die(mysql_error());
>>>>
>>>> if ( isset($_POST['submit']) ) {
>>>> for($i=1; $i<=$_POST['counties']; $i++) {
>>>> if ( isset($_POST["county$i"] ) ) {
>>>> echo "You have chosen ". $_POST["county$i"]."<br/>";
>>>>           }
>>>>       }
>>>> }
>>>>
>>>> $county_total=mysql_num_rows($result);
>>>>
>>>> while($row = mysql_fetch_array($result))
>>>> {$i++;
>>>>       echo $row['name'];
>>>> }
>>>> $county_total=mysql_num_rows($result);
>>>> echo "$county_total";
>>>>
>>>> echo 'You Have '  .  "$county_total"  .  ' Counties ';
>>>>
>>>> ?>
>>>
>>> The first thing I see is that you do
>>>    $county_total=mysql_num_rows($result)
>>> twice. Now I'm not to sure, but it is possible that looping over
>>> mysql_fetch_array($result) moves an array pointer so the count is not
>>> valid after the operation... that's a long shot.
>>>
>>> But since you are looping over the database records anyway, why not just
>>> count them as you go? Isn't $i the number of counties after all the
>>> looping?
>>>
>>>
>>> --
>>> Peter Ford, Developer                 phone: 01580 893333 fax: 01580
>>> 893399
>>> Justcroft International Ltd.
>>> www.justcroft.com
>>> Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United
>>> Kingdom
>>> Registered in England and Wales: 2297906
>>> Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17
>>> 1XS
>>
>>
>> Peter
>>
>> Thank you for your reply.
>>
>> I did notice that I had the $county_total=mysql_num_rows($result) twice. 
>> I
>> had moved and removed it, always getting either a 0 or 1 result.
>>
>> I put up another test page with
>>
>> $result = mysql_query("SELECT * FROM `counties` ") or die(mysql_error());
>>
>> $tot=mysql_num_rows($result);
>> echo "$tot";
>>
>> ?>
>>
>> And it worked fine.
>>
>> I have tried count() as well as mysql_num_rows() but am getting the same
>> result.
>>
>> Could you explain what you mean by count them as I go?
>>
>> Again, Thank you for your reply.
>>
>> Gary
>>
>>
>>
>> __________ Information from ESET Smart Security, version of virus 
>> signature database 5895 (20110222) __________
>>
>> The message was checked by ESET Smart Security.
>>
>> http://www.eset.com
>>
>>
>>
>>
>
> Well,
>
> Lets go back to your original code and cut out the decoration:
>
> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
> $county_total=mysql_num_rows($result);
> while($row = mysql_fetch_array($result))
> {
>     echo $row['name'];
> }
> echo "$county_total";
>
> That code should do pretty much what you want...
>
> But, because you only show the number of records AFTER the loop, you could 
> do:
>
> $result = mysql_query("SELECT * FROM `counties` WHERE name = 'checked'")
> $county_total = 0;
> while($row = mysql_fetch_array($result))
> {
>     echo $row['name'];
>     $county_total++;
> }
> echo "$county_total";
>

Peter

Thank you for your suggestion...btw "cut out the decoration"  LOL

I'm sorry to report it did not work. I tried various configurations of it 
but to no avail.

Any other suggestions?

Again, thank you for your help.

Gary 



__________ Information from ESET Smart Security, version of virus signature 
database 5895 (20110222) __________

The message was checked by ESET Smart Security.

http://www.eset.com





--- End Message ---
--- Begin Message ---
I wrote a short page on how to actually type of code that one writes,
it can be found here:
http://dotancohen.com/howto/write_code.html

The point that I stress on the page is that first you close an
element, then you fill it's contents. The page has examples in HTML
and PHP. I would like to know what the experienced programmers here
think about this. Am I going about it wrong?

Thanks!

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
[snip]
The point that I stress on the page is that first you close an
element, then you fill it's contents. The page has examples in HTML
and PHP. I would like to know what the experienced programmers here
think about this. Am I going about it wrong?
[/snip]

It is an interesting concept Dotan, what is the goal? Who is the page
targeted to?

--- End Message ---
--- Begin Message ---
It's an interesting idea (a different take on coding best practices)
but I find the PHP example to be laborious and time consuming with
little benefit.  If I'm typing an IF statement, I hope to god I know
what the condition is before I start typing it.  Creating the if/else
structure first and then filling in the conditions after is a lot of
cursor-shuffling that could be lived without.

2 cents
Marc

--- End Message ---
--- Begin Message ---
On 11-02-22 06:29 AM, Dotan Cohen wrote:
I wrote a short page on how to actually type of code that one writes,
it can be found here:
http://dotancohen.com/howto/write_code.html

The point that I stress on the page is that first you close an
element, then you fill it's contents. The page has examples in HTML
and PHP. I would like to know what the experienced programmers here
think about this. Am I going about it wrong?

I'm more likely to do this stuff for HTML than PHP. However, I do sometimes lay out the structure of some conditionals/functions before fleshing them out so that I can do some early testing... but I always fill the conditional as I'm doing this. In case that's not clear... the code flows from first character to last character as I type all of the conditionals (no jumping around). Later I fill in the associated activity for the conditional.

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 6:29 AM, Dotan Cohen <[email protected]> wrote:
> I wrote a short page on how to actually type of code that one writes,
> it can be found here:
> http://dotancohen.com/howto/write_code.html
>
> The point that I stress on the page is that first you close an
> element, then you fill it's contents. The page has examples in HTML
> and PHP. I would like to know what the experienced programmers here
> think about this. Am I going about it wrong?

I'll be the first to tell you that I'm not a great programmer, so my
take may not be worth a lot.  However, this is pretty close to how I
write.  Not exactly, but close.  I also always label open and closing
brackets on everything, unless the brackets are less than three lines
apart.  For instance, I might find myself writing:

if($foo == 'bar')
{ # Begin foo=bar test
   # If foo=bar, do a lot of things.

} # End foo=bar test

Then I go back and fill in the conditional stuff.  I've found two sets
of benefits to doing things this way.

1) I don't forget to close the brackets later, and I know they're
indented properly.
2) The comments mean that if I get to the beginning of a section and
want to skip to the end, I can just search for whatever comes after
"Begin", and know that the next instance will be the end of that
section.

I also tend to document my code in comments before I start writing
actual code.  I frequently find that that helps keep me on track,
rather than getting distracted by random new features that occur to me
after I start.  It also means that when the time comes to document
what I did, most of it is already there... that's saved me a few
times.  (I tend to wind up with about a 2:1 ratio of comments to code,
which at least means I can figure out later what I was thinking when I
wrote that horrible mess.)

So I can't say whether it's worthwhile practice for a good programmer
who writes on a regular basis:  for someone like me, who throws
together an occasional script to save time later, or a personal
web-site that needs a database backend, it can save a lot of
aggravation.

-Alex

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 14:11, Jay Blanchard <[email protected]> wrote:
> It is an interesting concept Dotan, what is the goal? Who is the page
> targeted to?
>

The goal is to have every open and close bracket matched, and not have
to worry about what is still open.

The page was specifically written for a friend who is learning HTML,
but I plan on presenting it to my C# and Java classmates who I think
would benefit from it as well. I choose to display the concepts with
PHP instead of C# or Java as I feel that there would be more PHP
learners online to benefit from the concept than C# or Java beginners.

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 14:15, Marc Guay <[email protected]> wrote:
> It's an interesting idea (a different take on coding best practices)
> but I find the PHP example to be laborious and time consuming with
> little benefit.  If I'm typing an IF statement, I hope to god I know
> what the condition is before I start typing it.  Creating the if/else
> structure first and then filling in the conditions after is a lot of
> cursor-shuffling that could be lived without.
>
>

If the if statement is simple, then I do agree with you. But once
there are nestled functions or conditionals, I like to have the layout
already ready. Consider:

if ( someFunction( someCheck( srrtolower( $_POST["variable"] ) ) ) ){
    // Some Code
}

Now, after the $_POST variable, how many close parentheses does the
code need? This does trip up beginners, especially those who
rightfully learn outside an IDE. Similar situations occur for
something like this (unindented to not overflow email line character
limit):
function someFunction(){
if($something==true){
while($someCondition){
switch($someVariable){
    // Some Code
}
}
}
}

Writing that is fine, but if the user goes in to add another while or
if, he will get lost in the sea of parenthesis. Therefore, I always
close elements before filling them in. It keeps the mind's state
machine saner!

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 14:58, Robert Cummings <[email protected]> wrote:
> I'm more likely to do this stuff for HTML than PHP. However, I do sometimes
> lay out the structure of some conditionals/functions before fleshing them
> out so that I can do some early testing... but I always fill the conditional
> as I'm doing this. In case that's not clear... the code flows from first
> character to last character as I type all of the conditionals (no jumping
> around). Later I fill in the associated activity for the conditional.
>

Thanks for the insight. I could see where that is a good compromise.
Like this I suppose:

if (something)

----

if (something) {

}

----

if (something) {
    // Code here
}


-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 15:00, Andy McKenzie <[email protected]> wrote:
> I'll be the first to tell you that I'm not a great programmer, so my
> take may not be worth a lot.  However, this is pretty close to how I
> write.  Not exactly, but close.  I also always label open and closing
> brackets on everything, unless the brackets are less than three lines
> apart.  For instance, I might find myself writing:
>
> if($foo == 'bar')
> { # Begin foo=bar test
>   # If foo=bar, do a lot of things.
>
> } # End foo=bar test
>
> Then I go back and fill in the conditional stuff.

I also do something similar, I debated writing about that as well:

class someClass{

    function someFunction() {
        if (true) {
            // Some Code
        }
    } // end someFunction

} // end someClass

I don't strictly subscribe to a three-line limit, but whatever feels
reasonable at the time. Often that depends on the complexity of
surrounding code.

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
On 11-02-22 08:58 AM, Dotan Cohen wrote:
On Tue, Feb 22, 2011 at 14:11, Jay Blanchard<[email protected]>  wrote:
It is an interesting concept Dotan, what is the goal? Who is the page
targeted to?


The goal is to have every open and close bracket matched, and not have
to worry about what is still open.

This is why I use the bracing style I use in PHP. A cursory glance of the code will show you where you've forgotten a brace. Syntax highlighting is also nice.

HTML can trip you up with missing or superfluous tags, but a quick run through the W3C validator will catch those errors.

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--- End Message ---
--- Begin Message ---


On 11-02-22 09:06 AM, Dotan Cohen wrote:
On Tue, Feb 22, 2011 at 14:58, Robert Cummings<[email protected]>  wrote:
I'm more likely to do this stuff for HTML than PHP. However, I do sometimes
lay out the structure of some conditionals/functions before fleshing them
out so that I can do some early testing... but I always fill the conditional
as I'm doing this. In case that's not clear... the code flows from first
character to last character as I type all of the conditionals (no jumping
around). Later I fill in the associated activity for the conditional.


Thanks for the insight. I could see where that is a good compromise.
Like this I suppose:

if (something)

----

if (something) {

}

----

if (something) {
     // Code here
}

If you switch to vertically aligned braces you will have an easier time matching up open and close braces...

if (something)
{
    // Code here
}

It's trivial to match using this style since you only need to scan one axis.

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--- End Message ---
--- Begin Message ---
On Tue, Feb 22, 2011 at 16:15, Robert Cummings <[email protected]> wrote:
> If you switch to vertically aligned braces you will have an easier time
> matching up open and close braces...
>
> if (something)
> {
>    // Code here
> }
>
> It's trivial to match using this style since you only need to scan one axis.
>

That bracing style drives me nuts! But I have no problem scanning a
single axis for the close brace and any statement, be it an if, while,
switch, or something else.

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com

--- End Message ---
--- Begin Message ---
Le 19/02/2011 0:23, Tommy Pham a écrit :
@Simon,

Thanks for explaining about the [^href].  I need to read up more about
greediness.  I thought I understood it but guess not.

@Peter,

I tried your pattern but it didn't capture all of my new test cases.
Also, it captures the single/double quotes in addition to the
fragments inside the href.  I couldn't figure out how to modify your
pattern to exclude the ', ", and URL fragment from group 1 matches.

Below is the new pattern with the new sample test cases that I got it
to work.  The new pattern failed only 1 of the non-compliant.

$html =<<<HTML
<a href=/sample/link>content</a>
<a class=link href=/sample/link_extra_attribs title=sample
link>content link_extra_attribs</a>
<a href='/sample/link_single_quote'>content link_single_quote</a>
<a class='link' href='/sample/link_single_quote_pre_attribs'>content
link_single_quote_pre_attribs</a>
<a class='link' href='/sample/link_single_quote_extra_attribs'
title='sample link'>content link_single_quote_extra_attribs</a>
<a class='link'
href='/sample/link_single_quote_extra_attribs_frag#fragment'
title='sample link'>content
link_single_quote_extra_attribs_frag#fragment</a>
<a class='link'
href='/sample/link_single_quote_extra_attribs_query_frag?par=val#fragment'
title='sample link'>content
link_single_quote_extra_attribs_query_frag?par=val#fragment</a>
<a href="/sample/link_double_quote">content link_double_quote</a>
<a class="link" href="/sample/link_double_quote_pre_attribs">content
link_double_quote_pre_attribs</a>
<a class="link"
href="/sample/link_double_quote_extra_attribs_frag#fragment"
title="sample link">content
link_double_quote_extra_attribs_frag#fragment</a>
<a class="link"
href="/sample/link_double_quote_extra_attribs_nested_tag"
title="sample link"><img class="image" src="/images/content.jpg"
alt="content" title="content">
link_double_quote_extra_attribs_nested_tag</a>
<a href="#fragment">content fragment</a>
<a class="link" href="#fragment" title="sample link">content fragment</a>
<li class="small  tab "><a class="y-mast-link images"
href="http://images.search.yahoo.com/images";
data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
style="padding-left:0em;padding-right:0em;">Images</span></a></li>
<li class="small  tab "><a class="y-mast-link video"
href="http://video.search.yahoo.com/video";
data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
style="padding-left:0em;padding-right:0em;">Video</span></a></li>
<li class="small  tab "><a class="y-mast-link local"
href="http://local.yahoo.com/results";
data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
style="padding-left:0em;padding-right:0em;">Local</span></a></li>
<li class="small  tab "><a class="y-mast-link shopping"
href="http://shopping.yahoo.com/search";
data-b="http://www.yahoo.com";><span class="tab-cover y-mast-bg-hide"
style="padding-left:0em;padding-right:0em;">Shopping</span></a></li>
<li class="small lasttab more-tab "><a class="y-mast-link more"
href="http://tools.search.yahoo.com/about/forsearchers.html";><span
class="tab-cover y-mast-bg-hide">More</span><span
class="y-fp-pg-controls arrow"></span></a></li>
HTML;

$pattern = 
'%<a[\s]+[^>]*?href\s*=\s*["\']?([^"\'#>]*)["\']?\s?[^>]*>(.*?)</a>%ims';

preg_match_all($pattern, $html, $matches);

Thanks for your time,
Tommy

Hi Tommy,

This is why you shouldn't mix regexes and HTML/XML, especially when you are not sure that you are working with valid/consistent html. A great/fun answer has been posted on StackOverflow about this at http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454

You could easily break any regular expressions solution by adding some valid comments, see example here : http://stackoverflow.com/questions/1357357/regexp-to-add-attribute-in-any-xml-tags/1357393#1357393

You really should consider using a XML parser instead for this kind of job.

Here is a simple sample that matches your example :

<?php
$oTidy = new tidy();
$html = $oTidy->repairString($html,array("clean" => true, "drop-proprietary-attributes" => true));
unset($oTidy);

$matches = get_links($html);

function get_links($html) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTML($html);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
$links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>

Regards,
Yann

--- End Message ---

Reply via email to