php-general Digest 6 May 2009 07:49:12 -0000 Issue 6106

Topics (messages 292307 through 292327):

Re: elseif statements
        292307 by: tedd
        292326 by: Jim Lucas

Re: how to enable ttf support in php 5.2.9
        292308 by: Ashley Sheridan
        292312 by: tedd
        292319 by: Michael A. Peters

How to deal with identical fields in db
        292309 by: PJ
        292310 by: Richard S. Crawford
        292311 by: Stephen
        292313 by: tedd
        292314 by: Tom Worster
        292317 by: PJ

Re: Generating dynamic PDFs
        292315 by: O. Lavell
        292323 by: Phpster

Re: Avoid to open mysql querries then times in the page
        292316 by: Daevid Vincent
        292318 by: Daevid Vincent
        292327 by: Michael A. Peters

Need Help! - Looking over a wireframe doc...
        292320 by: bruce

Re: Newbie - Setting Up Some Basic Sendmail Scripts
        292321 by: Manuel Lemos

Re: speaking of control structures...
        292322 by: Clancy

Re: Muticast Support in PHP
        292324 by: Shameem Muhammed

Re: SimpleXML output encoding
        292325 by: Ondrej Kulaty

Administrivia:

To subscribe to the digest, e-mail:
        php-general-digest-subscr...@lists.php.net

To unsubscribe from the digest, e-mail:
        php-general-digest-unsubscr...@lists.php.net

To post to the list, e-mail:
        php-gene...@lists.php.net


----------------------------------------------------------------------
--- Begin Message ---
At 1:11 PM -0400 5/5/09, Paul M Foster wrote:
I hate to dogpile on Tedd, ...

No problem.

Some days you're the windshield and some days you're the bug.

Hey, I've been wrong before -- I'm used to it.

But in my defense, I've always had major problems understanding long ifelse's.

You see, I'm dyslexic and I can not follow those long constructs (i.e., more than two decisions). I've always been able to work around the problem.

Sure the way php allows switch(true) is very opportunistic for me, but it's legal. I've seen a lot worse, not that my practicing such grants me permission to do so. But I don't seriously think that anyone who reviews my code would be confused as to what I was doing using a switch in such fashion.

Cheers,

tedd

--
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com

--- End Message ---
--- Begin Message ---
Well, since nobody seems to want to answer your question, I will...  :)

It has to do with you using an assignment '=' instead of a comparison '==' 
operator in your condition.

Follow along with my inline notes below.

Gary wrote:
I am trying to get this to work, however it only reads the second if statement. I get no error messages, but as I change counties, the % stays the same.

Can someone enlighten me, or should I be looking at switch statements?

Thanks for your help.

Gary



<?php
$_SESSION['sale_session']=$_POST['sale'];
$_SESSION['assess_session']=$_POST['assess'];
$_SESSION['county_session']=$_POST['county'];

// checks if bot
   if ($_POST['address'] != '' ){
exit("Changed field");
    }


$sale_value=$_POST['sale'];
$assess_value=$_POST['assess'];
$county=$_POST['county'];

$chester_ratio=.51;
$montco_ratio=.53;
$delco_ratio=.58;
/*$ratio=.51;


/*$correct_assess=($sale_value)*($ratio); this is now the assessment should be */
$chester_correct_assess=($sale_value)*($chester_ratio);
$montco_correct_assess=($sale_value)*($montco_ratio);
$delco_correct_assess=($sale_value)*($delco_ratio);


$chester_assess_difference=($assess_value)-($chester_correct_assess);
$montco_assess_difference=($assess_value)-($montco_correct_assess);
$delco_assess_difference=($assess_value)-($delco_correct_assess);

/*  $assess_difference=($assess_value)-($sale_value * $ratio);
$percent_difference=($assess_difference)/($assess_value);*/
$chester_percent_difference=($chester_assess_difference)/($assess_value);
$delco_percent_difference=($delco_assess_difference)/($assess_value);
$montco_percent_difference=($montco_assess_difference)/($assess_value);

$chester_percent_savings=($chester_percent_difference)*100;
$delco_percent_savings=($delco_percent_difference)*100;
$montco_percent_savings=($montco_percent_difference)*100;

if(($_COOKIE['county_cookie'] ='Chester') && ($chester_assess_difference >=50000))


The previous line should be, notice the missing == comparison ???
if(($_COOKIE['county_cookie'] == 'Chester') && ($chester_assess_difference  >= 
50000))


{
echo '<h2 style="margin:0;color:#ff0000;">Yes, Your property appears to qualify!</h2><br /><br />'; echo "You 1 believe your home would today sell for <b> $".number_format($sale_value)." </b><br />"; echo "Your current tax assessment is<b> $".number_format($assess_value)."</b><br />";
echo "You live in <b>$county </b><br />";
echo "Your potential savings could be<b> " .number_format($chester_percent_savings,0)."%</b><br /><br />"; echo "According to preliminary calculations based on the information you have entered, you may enjoy a savings of <b> ".number_format($chester_percent_savings,0)."% </b>off a combined total of county, school and township real estate taxes. Actual dollar amount savings will differ depending on the township that the property is located. Please contact my office for a more precise estimate of savings.<br />";

}
elseif(($_COOKIE['county_cookie']='Delaware') && ($delco_assess_difference >=30000)) {

Same thing here



echo '<h2 style="margin:0;color:#ff0000;">Yes, Your property appears to qualify!</h2><br /><br />'; echo "You 2 believe your home would today sell for <b> $".number_format($sale_value)." </b><br />"; echo "Your current tax assessment is<b> $".number_format($assess_value)."</b><br />";
echo "You live in <b>$county </b><br />";
echo "Your potential savings could be<b> " .number_format($delco_percent_savings,0)."%</b><br /><br />"; echo "According to preliminary calculations based on the information you have entered, you may enjoy a savings of <b> ".number_format($delco_percent_savings,0)."% </b>off a combined total of county, school and township real estate taxes. Actual dollar amount savings will differ depending on the township that the property is located. Please contact my office for a more precise estimate of savings.<br />";
}
elseif(($_COOKIE['county_cookie']='Montgomery') && ($montco_assess_difference >=50000))


Same thing here


{
echo '<h2 style="margin:0;color:#ff0000;">Yes, Your property appears to qualify!</h2><br /><br />'; echo "You 3 believe your home would today sell for <b> $".number_format($sale_value)." </b><br />"; echo "Your current tax assessment is<b> $".number_format($assess_value)."</b><br />";
echo "You live in <b>$county </b><br />";
echo "Your potential savings could be<b> " .number_format($montco_percent_savings,0)."%</b><br /><br />"; echo "According to preliminary calculations based on the information you have entered, you may enjoy a savings of <b> ".number_format($montco_percent_savings,0)."% </b>off a combined total of county, school and township real estate taxes. Actual dollar amount savings will differ depending on the township that the property is located. Please contact my office for a more precise estimate of savings.<br />";
}

else if(($chester_assess_difference <=50000) && ($chester_assess_difference>=1000)) { echo '<h3 style="margin:0;">While it appears you may enjoy some savings, the dollar amount may not reach the threshold required for action. If property values in your area continue to decline, you may wish to revisit this issue again next year.</h3><br /><br />';
}
else if(($delco_assess_difference <=30000) && ($delco_assess_difference>=1000)) { echo '<h3 style="margin:0;">While it appears you may enjoy some savings, the dollar amount may not reach the threshold required for action. If property values in your area continue to decline, you may wish to revisit this issue again next year.</h3><br /><br />';
}
else if(($montco_assess_difference <=50000) && ($montco_assess_difference>=1000)) { echo '<h3 style="margin:0;">While it appears you may enjoy some savings, the dollar amount may not reach the threshold required for action. If property values in your area continue to decline, you may wish to revisit this issue again next year.</h3><br /><br />';
}
else if(isset($chester_assess_difference) <=1000){
echo '<h3 style="margin:0;">NO, Your property does not appear to qualify. If property values in your area continue to decline, you may wish to revisit this issue again next year. </h3><br /><br />';
}
else if(isset($delco_assess_difference) <=1000){
echo '<h3 style="margin:0;">NO, Your property does not appear to qualify. If property values in your area continue to decline, you may wish to revisit this issue again next year. </h3><br /><br />';
}
else if(isset($montco_assess_difference) <=1000){
echo '<h3 style="margin:0;">NO, Your property does not appear to qualify. If property values in your area continue to decline, you may wish to revisit this issue again next year. </h3><br /><br />';
}
/*This is just a test to see which one is being displayed*/
echo "chester $chester_ratio .''. $chester_correct_assess .''. $chester_percent_savings<br/>"; echo "montco $montco_ratio.''. $montco_correct_assess .''. $montco_percent_savings<br />"; echo "delco $delco_ratio .''. $delco_correct_assess.''. $delco_percent_savings";
?>





--- End Message ---
--- Begin Message ---
On Tue, 2009-05-05 at 09:57 -0400, PJ wrote:
> Ashley Sheridan wrote:
> > On Mon, 2009-05-04 at 18:42 -0400, PJ wrote:
> >   
> >> Jim Lucas wrote:
> >>     
> >>> PJ wrote:
> >>>       
> >>>> Is there a module to be activated or what has to be installed to have
> >>>> ttf support in php?
> >>>> My port on FreeBSD does not have an option for ttf support under make
> >>>> config .
> >>>> I'm trying to learn & understand the following:
> >>>> In file1 : <img src="button.php?s=36&text=PHP+is+Cool" />
> >>>> In file2 (button.php)- originally php3 :
> >>>> <?php
> >>>>   Header("Content-type: image/gif");
> >>>>   if(!isset($s)) $s=11;
> >>>>         
> >>> The above should be:
> >>>
> >>> if ( empty($_GET['s']) ) {
> >>>     $s = 11;
> >>> } else {
> >>>     $s = (int)$_GET['s'];
> >>> }
> >>>
> >>>       
> >>>>   $size = imagettfbbox($s,0,"times.ttf",$text);
> >>>>         
> >>> and this should be
> >>>
> >>> $text = '';
> >>> if ( !empty($_GET['text']) )
> >>>     $text = your_custom_input_cleaner_function($_GET['text']);
> >>>
> >>> $size = imagettfbbox($s,0,"times.ttf",$text);
> >>>
> >>>       
> >>>>   $dx = abs($size[2]-$size[0]);
> >>>>   $dy = abs($size[5]-$size[3]);
> >>>>   $xpad=9;
> >>>>   $ypad=9;
> >>>>   $im = imagecreate($dx+$xpad,$dy+$ypad);
> >>>>   $blue = ImageColorAllocate($im, 0x2c,0x6D,0xAF);
> >>>>   $black = ImageColorAllocate($im, 0,0,0);
> >>>>   $white = ImageColorAllocate($im, 255,255,255);
> >>>>   ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black);
> >>>>   ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white);
> >>>>   ImageTTFText($im, $s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black,
> >>>> "times.ttf", $text);
> >>>>   ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1, $white,
> >>>> "times.ttf", $text);
> >>>>   ImageGif($im);
> >>>>   ImageDestroy($im);
> >>>> ?>
> >>>> ONLY the above & nothing else. So far, all I get is a small blue square.
> >>>> Replacing the $text with the text just gives a rectangle a bit wider.
> >>>> gd is installed but ttf is not, so I figure that is the culprit.
> >>>> But how is the text supposed to be assigned to $text from file1?
> >>>> TIA
> >>>>         
> >> Thank you for that. Now it works. I see, the $s had to come from
> >> somewhere...
> >> But what's the custom_cleaner_function - I mean, to clean what? & Why?
> >> What if I use some foreign accents, like &eacute; or  &Agrave; ?
> >>
> >> -- 
> >> Hervé Kempf: "Pour sauver la planète, sortez du capitalisme."
> >> -------------------------------------------------------------
> >> Phil Jourdan --- p...@ptahhotep.com
> >>    http://www.ptahhotep.com
> >>    http://www.chiccantine.com/andypantry.php
> >>
> >>
> >>     
> > content coming from MS Office clipboard pastes generally contain
> > characters that are encoded wrong, and do not display correctly in web
> > pages unless they have very relaxed doctypes. The function I generally
> > use is:
> >
> > function removeMSCrap($crap)
> > {
> >     $find = Array(chr(128), chr(133), chr(8226), chr(145), chr(8217),
> > chr(146), chr(8220), chr(147), chr(8221), chr(148), chr(8226), chr(149),
> > chr(8211), chr(150), chr(8212), chr(151), chr(8282), chr(153), chr(169),
> > chr(174));
> >     $replace = Array("&euro;", "&#133;", "&#8243;", "&#039;", "&#039;",
> > "&#039;", "&#039;", "&#034;", "&#034;", "&#034;", "&#034;", "&#149;",
> > "&#149;", "&#150;", "&#150;", "&#151;", "&#151;", "&#153;", "&#153;",
> > "&copy;", "&reg;");
> >     
> >     $roses = str_replace($find, $replace, $crap);
> >     return $roses;
> > }
> >
> >
> > Ash
> > www.ashleysheridan.co.uk
> >
> >
> >   
> Uh. Ok. That's cool. Somehow I have managed to never use MS Office for
> anything else than web applications. Generally I open .doc with
> OpenOffice. But, who know's? Thanks, anyway. :-)
> 
> -- 
> Hervé Kempf: "Pour sauver la planète, sortez du capitalisme."
> -------------------------------------------------------------
> Phil Jourdan --- p...@ptahhotep.com
>    http://www.ptahhotep.com
>    http://www.chiccantine.com/andypantry.php
> 
> 
It's mainly for the benefit of other people, who do use MS programs and
copy and paste things into your web apps and then wonder why things
don't work exactly how they expect


Ash
www.ashleysheridan.co.uk


--- End Message ---
--- Begin Message ---
At 9:17 PM +0100 5/5/09, Ashley Sheridan wrote:

It's mainly for the benefit of other people, who do use MS programs and
copy and paste things into your web apps and then wonder why things
don't work exactly how they expect


Ash
www.ashleysheridan.co.uk


Ash:

Ain't that the truth.

I have one client who no matter how many times I talk to him about gremlins and how he should make sure his entries are plain text, he still cuts and paste things directly from M$ Word and then wonders "Where did those come from? They weren't there when I added that text. What did you do?"

Oh well, we all stand somewhere between the stupid and smart marks on the scale of intelligence.

Cheers,

tedd

--
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com

--- End Message ---
--- Begin Message ---
Ashley Sheridan wrote:


content coming from MS Office clipboard pastes generally contain
characters that are encoded wrong, and do not display correctly in web
pages unless they have very relaxed doctypes. The function I generally
use is:

function removeMSCrap($crap)
{
        $find = Array(chr(128), chr(133), chr(8226), chr(145), chr(8217),
chr(146), chr(8220), chr(147), chr(8221), chr(148), chr(8226), chr(149),
chr(8211), chr(150), chr(8212), chr(151), chr(8282), chr(153), chr(169),
chr(174));
        $replace = Array("&euro;", "&#133;", "&#8243;", "&#039;", "&#039;",
"&#039;", "&#039;", "&#034;", "&#034;", "&#034;", "&#034;", "&#149;",
"&#149;", "&#150;", "&#150;", "&#151;", "&#151;", "&#153;", "&#153;",
"&copy;", "&reg;");
        
        $roses = str_replace($find, $replace, $crap);
        return $roses;
}

Is that something you would suggest be used in any web app that has a textarea for input?
--- End Message ---
--- Begin Message ---
I'm coming up with a bit of a quandry: how to enter and retrieve an
identical book title with different authors.
It is rather unbelievable what contortions one finds as authors :-(
like editors, associations and then the unknowns and anon y mouses.
I suppose one has to get really creative...
Anyone for tea?

-- 
Hervé Kempf: "Pour sauver la planète, sortez du capitalisme."
-------------------------------------------------------------
Phil Jourdan --- p...@ptahhotep.com
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


--- End Message ---
--- Begin Message ---
On Tue, May 5, 2009 at 1:34 PM, PJ <af.gour...@videotron.ca> wrote:
> I'm coming up with a bit of a quandry: how to enter and retrieve an
> identical book title with different authors.
> It is rather unbelievable what contortions one finds as authors :-(
> like editors, associations and then the unknowns and anon y mouses.
> I suppose one has to get really creative...
> Anyone for tea?

What I've done for this sort of project in the past was create
separate tables for authors, books, and author relationships (e.g.,
author, translator, editor), then linking tables for each of those.
You seriously want to do some normalization on this task; otherwise,
you end up with a giant table of books, with multiple rows duplicating
the title of the book, leading to a huge "books" table, and nobody
wants that.

-- 
Richard S. Crawford (rscrawf...@mossroot.com)
http://www.mossroot.com
Publisher and Editor in Chief, Daikaijuzine (http://www.daikaijuzine.com)

--- End Message ---
--- Begin Message ---
PJ wrote:
I'm coming up with a bit of a quandry: how to enter and retrieve an
identical book title with different authors.
It is rather unbelievable what contortions one finds as authors :-(
like editors, associations and then the unknowns and anon y mouses.
I suppose one has to get really creative...
Anyone for tea?
You should have a title_id field in your titles table, and this field should be unique. Probably auto assigned and auto increment.

If you search for a book title, and there are two books with that title, you should get two records back!

Stephen

--- End Message ---
--- Begin Message ---
At 4:34 PM -0400 5/5/09, PJ wrote:
I'm coming up with a bit of a quandry: how to enter and retrieve an
identical book title with different authors.
It is rather unbelievable what contortions one finds as authors :-(
like editors, associations and then the unknowns and anon y mouses.
I suppose one has to get really creative...
Anyone for tea?

You need to normalize.

Authors should have an unique id in an authors table. The authors table has all the specific information about authors, but not the books they have written.

Books should have an unique id in a books table. The books table has all the specific information about books, but not the contributing authors.

Then you connect the two tables with a Book-Author table that has only the id's of both -- no real need for any other information.

That way when you want to see all the books an author has written, then you pull out all the records that has the author's id and look up each book via the book id.

Likewise, when you want to see all the authors who have contributed to a book, then you pull out all records that has the book's id and look up each author via their author id.

Do you see how it works?

Cheers,

tedd

--
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com

--- End Message ---
--- Begin Message ---
On 5/5/09 4:42 PM, "Richard S. Crawford" <rscrawf...@mossroot.com> wrote:

> On Tue, May 5, 2009 at 1:34 PM, PJ <af.gour...@videotron.ca> wrote:
>> I'm coming up with a bit of a quandry: how to enter and retrieve an
>> identical book title with different authors.
>> It is rather unbelievable what contortions one finds as authors :-(
>> like editors, associations and then the unknowns and anon y mouses.
>> I suppose one has to get really creative...

don't forget to consider the handling of anthologies :-)


>> Anyone for tea?

yes please, i'd love some.


> What I've done for this sort of project in the past was create
> separate tables for authors, books, and author relationships (e.g.,
> author, translator, editor), then linking tables for each of those.
> You seriously want to do some normalization on this task; otherwise,
> you end up with a giant table of books, with multiple rows duplicating
> the title of the book, leading to a huge "books" table, and nobody
> wants that.

i have a db with 10s of millions of artists, disks, songs etc. i've tried it
both ways. and after 5 years working with it i still can't make up my mind
which way i prefer it. i keep finding pros and cons to each approach that
differ depending on what functionality i'm programming. i will never have a
simple answer.

so i can't help answer the original question other than to say that, for me,
personally, in my opinion, i don't accept the dogma that normal forms are
always good for you. they might be. it depends. it's like being dogmatic
about specific foods without taking the overall diet and lifestyle into
account. despite the simple dogma some may espouse, whether or not a big mac
with fries is bad for you depends on many factors.

in any case, it's amazing what you can do these days with one huge table and
some well chosen indexes. and it's amazing how mind bending it can get when
joining 5 data tables using 3 join tables.

good luck, phil.



--- End Message ---
--- Begin Message ---
Tom Worster wrote:
> On 5/5/09 4:42 PM, "Richard S. Crawford" <rscrawf...@mossroot.com> wrote:
>
>   
>> On Tue, May 5, 2009 at 1:34 PM, PJ <af.gour...@videotron.ca> wrote:
>>     
>>> I'm coming up with a bit of a quandry: how to enter and retrieve an
>>> identical book title with different authors.
>>> It is rather unbelievable what contortions one finds as authors :-(
>>> like editors, associations and then the unknowns and anon y mouses.
>>> I suppose one has to get really creative...
>>>       
>
> don't forget to consider the handling of anthologies :-)
>   
Well, that usually comes under editors and I have a couple of options
where to enter that info: sub_title or description fields and I can
always add a &nbsp; for author first_name and Various or whatever for
last_name :-)
>
>   
>>> Anyone for tea?
>>>       
>
> yes please, i'd love some.
>
>
>   
>> What I've done for this sort of project in the past was create
>> separate tables for authors, books, and author relationships (e.g.,
>> author, translator, editor), then linking tables for each of those.
>> You seriously want to do some normalization on this task; otherwise,
>> you end up with a giant table of books, with multiple rows duplicating
>> the title of the book, leading to a huge "books" table, and nobody
>> wants that.
>>     
>
> i have a db with 10s of millions of artists, disks, songs etc. i've tried it
> both ways. and after 5 years working with it i still can't make up my mind
> which way i prefer it. i keep finding pros and cons to each approach that
> differ depending on what functionality i'm programming. i will never have a
> simple answer.
>
> so i can't help answer the original question other than to say that, for me,
> personally, in my opinion, i don't accept the dogma that normal forms are
> always good for you. they might be. it depends. it's like being dogmatic
> about specific foods without taking the overall diet and lifestyle into
> account. despite the simple dogma some may espouse, whether or not a big mac
> with fries is bad for you depends on many factors.
>
> in any case, it's amazing what you can do these days with one huge table and
> some well chosen indexes. and it's amazing how mind bending it can get when
> joining 5 data tables using 3 join tables.
>   
ain't that the truth !
> good luck, phil.
>   
Thank you guys, for the input. Never thought so many would help so
few(little me). ;-)
I'm really just a little shorter than BG at 6'5" :-D
Actually, I started out and still am with the db normalized. It all
works quite well, it's just frustrating to have to go through all the
contortions to check things. I started out with just checking the title,
then had to add a check to the sub_title, (already have a check for
author) but now have to add another to go with the specific book... oh,
well... all a part of the learning process. :-)

-- 
Hervé Kempf: "Pour sauver la planète, sortez du capitalisme."
-------------------------------------------------------------
Phil Jourdan --- p...@ptahhotep.com
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


--- End Message ---
--- Begin Message ---
Kevin Kaiser wrote:

[..]

> All you have to do is sign up for an API key, upload your document
> templates and POST data to our server. We handle everything else. A
> stream of PDF data is passed back to your application and you can save
> it as a file, prompt the user to download it right then and there or
> push it into a database.

So what else do you do with the documents that get posted to your server, 
and why should anyone trust you?

--- End Message ---
--- Begin Message ---
There are way too many php based options to even waste time with this.

Bastien

Sent from my iPod

On May 5, 2009, at 17:54, "O. Lavell" <olav...@xs4all.nl> wrote:

Kevin Kaiser wrote:

[..]

All you have to do is sign up for an API key, upload your document
templates and POST data to our server. We handle everything else. A
stream of PDF data is passed back to your application and you can save
it as a file, prompt the user to download it right then and there or
push it into a database.

So what else do you do with the documents that get posted to your server,
and why should anyone trust you?

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


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

> -----Original Message-----
> From: tedd [mailto:tedd.sperl...@gmail.com] 
> Sent: Tuesday, May 05, 2009 7:55 AM
> To: php-gene...@lists.php.net
> Subject: Re: [PHP] Avoid to open mysql querries then times in the page
> 
> On 5/4/09, Matthieu <spama...@gmail.com> wrote:
> >  Hello,
> >
> >  I'm a totally newbie to php/Mysql but I'd like to know if 
> it is normal that
> >  I have to connect 3 times to the db in one page.
> >
> >  For example, I have
> >
> >  1. A connection for the login / pass a $_SESSION['login'] 
> before the HTML
> >  tags
> >
> >  2. I need to say hello to the user so I reconnect, run a 
> query to select the
> >  user having the login and echo 'Hello '.$user['login'].'!''
> >
> >  3. I need to show him his friends a bit later, so I have 
> to connect a last
> >  time and re-run a querry because I can't use the data 
> $user that I used in
> >  my upper php code...
> >
> >
> >  Is there a walkthroug to have only one connection for the page?
> >
> >  Thanks
> >
> >  Matthieu

I usually include a db.inc.php file that opens up a connection in the header
of the page and I continue to use the connection throughout till the end.

A basic example is do something like this:

//this will hold each db connection so we'll only create one at a time. like
a singleton.
$GLOBALS['DB_CONNECTIONS'] = array(); 

function connect_to_db_reliability() 
{
        if ($GLOBALS['DB_CONNECTIONS']['reliability']) 
                return $GLOBALS['DB_CONNECTIONS']['reliability'];

        global $global_db_dsn_reliability;

        $options = array(
                'debug'   => 0,
                'persistent'  => FALSE,
                'portability' => DB_PORTABILITY_ALL
        );

        $db_connection =& DB::connect($global_db_dsn_reliability, $options);
        if ( PEAR::isError( $db_connection ) )
                die( $db_connection->getMessage() );

        $GLOBALS['DB_CONNECTIONS']['reliability'] = $db_connection;
        
$GLOBALS['DB_CONNECTIONS']['reliability']->setFetchMode(DB_FETCHMODE_ASSOC);

        return $GLOBALS['DB_CONNECTIONS']['reliability'];
}

Then in all your code you can either do a simple call at the top of your
page:

        $db_connection = connect_to_db_reliability();

and later on, you don't have to worry about it because you have already made
a connection.

        $db_result =& $db_connection->getAll($sql);

Be aware of scope and such, for example if you're inside a function or
method. But that's easy enough to handle since calling $db_connection =
connect_to_db_reliability(); will return you the same connection anyways, so
it's free to use wherever you are unsure.

This method is a fairly simple "singleton" like methodology that handles
multiple database connections (here at my job, we have NINE databases we
connect to at any given time.

In my other jobs/projects where I only have a single database (which is the
norm), I do this same sort of logic just not in a multi-dimensional array
and I have more wrapper functions that handle the connection if it doesn't
exist and do all sorts of useful things like colorized debug output,
backtraces. Search the PHP list archives for my posts and SQL_QUERY,
SQL_CONNECT, etc in a "db.inc.php" file I shared...

http://daevid.com


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

> -----Original Message-----
> From: tedd [mailto:tedd.sperl...@gmail.com] 
> Sent: Tuesday, May 05, 2009 7:55 AM
> To: php-gene...@lists.php.net
> Subject: Re: [PHP] Avoid to open mysql querries then times in the page
> 
> On 5/4/09, Matthieu <spama...@gmail.com> wrote:
> >  Hello,
> >
> >  I'm a totally newbie to php/Mysql but I'd like to know if 
> it is normal that
> >  I have to connect 3 times to the db in one page.
> >
> >  For example, I have
> >
> >  1. A connection for the login / pass a $_SESSION['login'] 
> before the HTML
> >  tags
> >
> >  2. I need to say hello to the user so I reconnect, run a 
> query to select the
> >  user having the login and echo 'Hello '.$user['login'].'!''
> >
> >  3. I need to show him his friends a bit later, so I have 
> to connect a last
> >  time and re-run a querry because I can't use the data 
> $user that I used in
> >  my upper php code...
> >
> >
> >  Is there a walkthroug to have only one connection for the page?
> >
> >  Thanks
> >
> >  Matthieu
> 
> 
> Matthieu:
> 
> The way I usually have a user navigate a protected site is to first 
> to have them identify themselves via a logon/password script -- and 
> then I store their user_id in a SESSION. Note, I do not store all 
> their data in a SESSION, just their user_id. The user_id should be an 
> unique auto_increment integer primary key from your users' table.
> 
> At the start of each protected page, I have:
> 
> <?php session_start();
> 
> $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
> 
> if($user_id == 0)
>     {
>     header('location: login.php);
>     exit();
>     }
> 
> // proceed with processing
> 
> As such, I check if $user_id > 0 -- if so, then I process the request 
> as directed. If not, then I send the user back to login.
> 
> As for connecting to the database, I connect as needed to get 
> information needed. I do not use SESSIONs to store all the data to be 
> passed from page to page, I gather only what's needed for that page.
> 
> I also make sure that when I open a connection, I close the 
> connection I may have several open/close statements within a page, 
> but normally I try to avoid that.
> 
> HTH's
> 
> tedd

I would disagree with this. I strongly believe you should use a
User.class.php and store that instance in the $_SESSION. This gives you the
ID, name, login name, login state, roles, and every other thing you could
want to know about a user on a given page in a handy to access object. In
fact, a User class is one of those things that really benefits from being
OOP.

The only trick here Matthieu is to make sure you
require_once('User.class.php') BEFORE you session_start(); or it won't work.

Opening and closing the connections is also IMHO a bad idea. The connection
is one of the slowest parts. In mySQL it's not so bad, but it's very narrow
sighted to think in terms of only one RDBMS. Other RDBMS like Oracle for
example have a very slow connection. Why not just keep it around. Your page
only lasts a few seconds and will automatically close when completed
anyways.

If you're writing a command line tool like a daemon, then that's another
story, but I doubt the OP is doing that.

Lastly, why all the extra variable, assignment and checking stuff here?

        $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;

Why not just this?

        if( intval($_SESSION['user_id']) < 1 ) { ... }

What I normally do is set a $_SESSION['login'] = true; 

A boolean is always faster to check and in your code you could do this:

        if ( !$_SESSION['login'] ) { ... }

or if you're really paranoid use the '===':

        if ( $_SESSION['login'] !== true ) { ... }


D.Vin
http://daevid.com





--- End Message ---
--- Begin Message ---
tedd wrote:
On 5/4/09, Matthieu <spama...@gmail.com> wrote:
 Hello,

I'm a totally newbie to php/Mysql but I'd like to know if it is normal that
 I have to connect 3 times to the db in one page.

 For example, I have

1. A connection for the login / pass a $_SESSION['login'] before the HTML
 tags

2. I need to say hello to the user so I reconnect, run a query to select the
 user having the login and echo 'Hello '.$user['login'].'!''

3. I need to show him his friends a bit later, so I have to connect a last time and re-run a querry because I can't use the data $user that I used in
 my upper php code...


 Is there a walkthroug to have only one connection for the page?

 Thanks

 Matthieu


Matthieu:

The way I usually have a user navigate a protected site is to first to have them identify themselves via a logon/password script -- and then I store their user_id in a SESSION. Note, I do not store all their data in a SESSION, just their user_id. The user_id should be an unique auto_increment integer primary key from your users' table.

At the start of each protected page, I have:

<?php session_start();

$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;

if($user_id == 0)
   {
   header('location: login.php);
   exit();
   }

// proceed with processing

As such, I check if $user_id > 0 -- if so, then I process the request as directed. If not, then I send the user back to login.

That's basically what i do.
I don't store much in sessions, just the id of the logged in user (set to 0 for not logged in) and maybe a few temporary things (IE a page that requires login, if the uid is set to 0 I'll store the page in the session so that after login they can be redirected back). There's a few other things I do in session data, but not much.

Since I only use non persistent cookies for security reasons, almost anything worth saving is worth saving as a db record tied to the user id. Sessions for me mostly are just a way to know a user is authenticated and who they are authenticated as.


As for connecting to the database, I connect as needed to get information needed. I do not use SESSIONs to store all the data to be passed from page to page, I gather only what's needed for that page.

I also make sure that when I open a connection, I close the connection I may have several open/close statements within a page, but normally I try to avoid that.

I just use pear mdb2 - they make it easy to deal with multiple different databases etc. and I just let the connection close when the page finished executing, I don't explicitly close any connections.

I do explicitly unset prepared statements, but only on pages that do many queries (short fast pages free up the memory when the page finishes executing anyway).

Since I generally use the same database for session handling as I use for rest of the app, the database will be opened when the page starts and need to be open when the page finishes execution for writing any new session data, so it doesn't make sense to me to explicitly close the connection except for my search engine (it uses a different database) - but when the search query has run, the search results are displayed and the script finishes executing anyway, so closing that connection isn't needed anyway - the job is done and the script exits quickly closing the connection on it's own.


HTH's

tedd



--- End Message ---
--- Begin Message ---
Hi..

I'm playing around with creating an app to allow users to
add/checkin/checkout docs from a web based app. The backend will tie into
SVN as a repository.

The app is intended to be a php/mysql/linux app.

I'm trying to find a few people that I might get to take a look at the
current doc(s) I have and give me some comments/feedback...

The goal of the app is to allow a user to register, and then select the
given doc he wants to work on, as well as the given workflow phase. This
allows the app to kind of restrict the access rights a user has to the doc,
based on where in the workflow the doc is..

Get to me offline if you're interested in taking a look.

thanks

-bruce


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

on 05/05/2009 02:20 PM revDAVE said the following:
> I'm trying to set up some basic php send mail scripts - and I'm curious of
> the best way to go...
> 
> 
> I checked these basics out:
> 
> http://us.php.net/manual/en/function.mail.php
> 
> And got this code below going, but I'll bet I need a bit more - like adding
> authentication - smtp - port - sending user / pass etc.
> 
> Any hints how to get this to the next level?

It seems the SMTP server is only requiring authentication because it is
in a different machine of what you run PHP. In that case, you may want
to read this article:

http://www.phpclasses.org/blog/package/9/post/1-Sending-email-using-SMTP-servers-of-Gmail-Hotmail-or-Yahoo-with-PHP.html

-- 

Regards,
Manuel Lemos

Find and post PHP jobs
http://www.phpclasses.org/jobs/

PHP Classes - Free ready to use OOP components written in PHP
http://www.phpclasses.org/

--- End Message ---
--- Begin Message ---
On Tue, 05 May 2009 14:13:23 -0400, rob...@interjinn.com (Robert Cummings) 
wrote:

>On Tue, 2009-05-05 at 13:56 -0400, Tom Worster wrote:
>> there's a control structure i wish php had: a simple block that you can 
>> ...........

>But PHP 5.3 introduces goto:
>
><?php
>
>header:
>
>    if( $something ) ...
>
>    goto body;
>
>body:
>
>    if( $soemthingElse ) ...
>        goto footer;
>
>    if( $seomthingerElse ) ...
>
>    goto footer;
>
>footer:
>
>    // blah blah blah
>    goto done;
>
>done;

I heartily agree. In my opinion 'break' is like a 'goto' without a label. As I 
used to
tell my students "if I say 'break' the one thing I can be sure of is that you 
will all
disappear. I had no idea where most of you go, or what you do, and I'm not even 
sure if
I'll ever see some of you again."

'Goto' makes it possible to set up the more complex control sequences you 
sometimes need,
yet have them clearly defined. For example:

<?php

begin:  .......
        if ( ... ) { goto error; }
        .......
        if ( .... ) { goto footer; }
        .......
        goto body;

repeat: ....
        if ( .... ) { goto footer; }
        .......
        if ( ... ) { goto error; }

body:   .........
        if ($error) { goto error; }
        ........
        if (!$error) { goto footer; }
error:  ........

footer:   ........
        if ( .... ) { goto repeat; }
?>

I find it very difficult to set up sequences like this using if/else if (or 
switches, but
I don't like them anyway), and have to resort to setting flags and very careful
indentation to make sure that I'm doing what I intended. Unfortunately my 
provider is
still using PHP 4.something, and I have been too busy to switch to someone more
up-to-date.


--- End Message ---
--- Begin Message ---
Hi,

I woud like to know ,whether PHP can Support muticast messages.I wand sent and receive muticast messages using PHP.


--
Thanks & Regards

Muhammed Shameem PV
Product Devpt & Support
Kalki Communication Technologies Ltd
Bangalore
India
"Disclaimer: This message is being sent from Kalki Communication Technologies 
Ltd (KALKITECH). and may contain information which is confidential or
privileged. If you are not the intended recipient, please advise the sender 
immediately by reply e-mail and delete this message and any attachments
without retaining a copy. Any unauthorized use of the content of this message 
can expose the responsible party to civil and/or criminal penalties,
and may constitute a more serious offense. Further the company does not accept 
liability for any errors, omissions, viruses or computer problems
experienced as a result of this transmission. If you have received this message 
in error, notice is hereby given that no representation, contract or
other binding obligation shall be created by this e-mail."

--- End Message ---
--- Begin Message ---
Because i am working on an old system which is in ISO, i cant use unicode.

--
Ondrej Kulaty

"tedd" <tedd.sperl...@gmail.com> píse v diskusním príspevku 
news:p06240802c625f6b4e...@[192.168.1.101]...
> At 2:40 PM +0200 5/5/09, Ondrej Kulaty wrote:
>>Hi,
>>is there any way how to set output encoding for SimpleXML?
>>It will load XML document in any encoding, but internally, it converts the
>>document to UTF-8 and outputs it in this encoding.
>>I would like to have output encoding set to ISO-8859-2, is it possible?
>>thanks.
>>
>>--
>>Ondrej Kulaty
>
> Why?
>
> <http://www.cl.cam.ac.uk/~mgk25/unicode.html>
>
> tedd
>
> -- 
> -------
> http://sperling.com  http://ancientstones.com  http://earthstones.com 



--- End Message ---

Reply via email to