OSEC

Neohapsis is currently accepting applications for employment. For more information, please visit our website www.neohapsis.com or email hr@neohapsis.com
php-general Digest 19 Mar 2008 12:41:12 -0000 Issue 5356

php-general-digest-helplists.php.net
Date: Wed Mar 19 2008 - 07:41:12 CDT


php-general Digest 19 Mar 2008 12:41:12 -0000 Issue 5356

Topics (messages 271753 through 271776):

Re: Closures
        271753 by: Nathan Nobbe
        271761 by: Ray Hauge
        271762 by: Nathan Nobbe
        271765 by: Shawn McKenzie
        271767 by: Robert Cummings

Re: General use of rewrite / redirect
        271754 by: Nathan Nobbe
        271757 by: Larry Garfield
        271758 by: Larry Garfield
        271759 by: Nathan Nobbe
        271771 by: Per Jessen
        271772 by: Per Jessen
        271773 by: Stut
        271774 by: Per Jessen
        271775 by: Stut

Re: Objects as array key names??
        271755 by: Nathan Nobbe

mysqli_stmt_bind_result
        271756 by: Jeremy Mcentire

Re: Is this the best way?
        271760 by: Jochem Maas
        271766 by: Shawn McKenzie
        271776 by: Jason Pruim

Fastest way to get table records' number
        271763 by: Shelley
        271764 by: Nathan Nobbe

question about php with sql database
        271768 by: Sudhakar
        271769 by: Chris
        271770 by: Brady Mitchell

Administrivia:

To subscribe to the digest, e-mail:
        php-general-digest-subscribelists.php.net

To unsubscribe from the digest, e-mail:
        php-general-digest-unsubscribelists.php.net

To post to the list, e-mail:
        php-generallists.php.net

----------------------------------------------------------------------

attached mail follows:


On Tue, Mar 18, 2008 at 12:07 PM, Ray Hauge <ray.hauge.listsgmail.com>
wrote:

> I've been reading up on some of the parts of PHP that has been suggested
> could be improved so that I could be more well informed. One of the
> more "interesting" (for lack of a better word) suggestions is closures.
> I've used closures primarily in JavaScript, and they are handy in that
> context, but JavaScript handles events and other more dynamic situations
> like that.
>
> I can't really think of any good examples of why I'd want to use a
> closure instead of just calling functions or class methods in PHP.
> Variable functions and call_user_func*() have worked for any of the
> cases where I did need to be a bit more dynamic.
>
> I found a great summary of some discussion on the internals mailing list
> over here: http://devzone.zend.com/node/view/id/2013#Heading1
>
> After reading that article through, I do like Wez's idea of how to
> create anonymous functions. The point about it causing confusion with
> people coming from other languages definitely applies though. This
> article also gives me a second idea for this post. How many people
> would want closures in PHP?
>
> In summary:
>
> Would you want closures in PHP, and why?

not really. in my eyes php primarily has taken on the paradigm of the
c-style of programming. eg. c, c++, java. one of the main differences i
see compared to java is the allowance of global functions. php does not
support multiple inheritance, but in php5 there are interfaces, which afford
the multiple inheritance workaround and now i hear talk of these things
called traits. as if learning traits wont be weird enough i have gotten
quite used to leveraging my experience in the aforementioned languages and
also phps dynamic, loosely typed nature. there are a few subtleties of php
that bother me but at the end of the day i can live with them. recently i
have become proficient w/ javascript. closures, and execution context are
starting to make sense and so is the prototype-based object model. i quite
like this paradigm and enjoy programming in javascript, but find that many
of the things i already understand how to do w/ the php-like object / scope
model sometimes difficult to mimic in js. im still learning of course and
one day imagine myself being quite good w/ javascript. that said, i
believe there are languages that supply 'traditional' oop and the functional
model all under the same hood so to speak. at least i know python is
essentially that (though i know it lacks ppp) and i think (though dont know
for a fact) ruby is something like that [enter greg].
i dont know, i mean sure, php is like this crazy hybrid of so many things,
but i just want to master something then start banging out code. the more
features that get added the more i will have to know when i do code reviews
for my developers [gray hairs appearing on chin...]. does the syntax for
create_function() suck, yes.. will just syntactic sugar solve the problem,
no; why because as per the article its really all or nothing. being able to
pass around the php psuedo type callback is good enough at this point.
in short, functional programming support would have been great in php if it
had been incorporated early on, at this point i can live without it. if we
were going to see support for anything anonymous that i would welcome it
would be anonymous objects and the ability to create an object on the fly
from an interface as per java 5. o and inner classes would be nice too, but
maybe traits would address that desire, i dont know.

-nathan

attached mail follows:


Nathan Nobbe wrote:
> if we were going to see support for anything anonymous that i would
> welcome it would be anonymous objects and the ability to create an
> object on the fly from an interface as per java 5.

I'm not sure if this would solve your problem (my lack of java knowledge
is showing), but you can create objects either by creating a new
stdClass() object, or by using (object)NULL. Example:

<?php

$object = (object) NULL;

$object->test1 = 1;
$object->test2 = 2;

echo $object->test1 . "\n";

echo $object->test2;

?>

After trying to add a way to call a function from an object variable, I
have come to the conclusion that it's kinda ugly.

<?php

$obj = (object) NULL;

$obj->test = 2;
$obj->myTestFunc = "myTestFunc";

function myTestFunc () {
    return "test";
}

echo call_user_func($obj->myTestFunc) . $obj->test;

?>

Does anyone have a link to some documentation about the stdClass? All I
could find was a bunch of bug reports and other stuff that wasn't what I
was looking for. I would have thought there'd be a page for it in the
manual, but I didn't find one there either.

--
Ray Hauge
www.primateapplications.com

attached mail follows:


On Tue, Mar 18, 2008 at 10:49 PM, Ray Hauge <ray.hauge.listsgmail.com>
wrote:

> Nathan Nobbe wrote:
> > if we were going to see support for anything anonymous that i would
> > welcome it would be anonymous objects and the ability to create an
> > object on the fly from an interface as per java 5.
>
> I'm not sure if this would solve your problem (my lack of java knowledge
> is showing), but you can create objects either by creating a new
> stdClass() object, or by using (object)NULL. Example:
>

ive messed around w/ stdClass and use it more frequently than most i
imagine, but mostly just as a data transport mechanism. sometimes i prefer
it over an array, what can i say i like the -> ;) but seriously, using it
as an anonymous object doesnt really work. there are some posts on
php.netabout this actually (search for anonymous object)
http://www.php.net/zend-engine-2.php

> <?php
>
> $object = (object) NULL;
>
> $object->test1 = 1;
> $object->test2 = 2;
>
> echo $object->test1 . "\n";
>
> echo $object->test2;
>
> ?>
>
> After trying to add a way to call a function from an object variable, I
> have come to the conclusion that it's kinda ugly.
>
> <?php
>
> $obj = (object) NULL;
>
> $obj->test = 2;
> $obj->myTestFunc = "myTestFunc";
>
> function myTestFunc () {
> return "test";
> }
>
> echo call_user_func($obj->myTestFunc) . $obj->test;
>
> ?>

ive tried experimenting w/ making php more functional, attempting to attach
methods in one way or another to an object, but alas, my attempts have all
been quite fleeting :(

> Does anyone have a link to some documentation about the stdClass? All I
> could find was a bunch of bug reports and other stuff that wasn't what I
> was looking for. I would have thought there'd be a page for it in the
> manual, but I didn't find one there either.

php --rc stdClass

thats about all there is :) but it is nice for usage in conjunction w/
json_encode().

and just to give you an idea what you can do in java (note nothing like
javascript which is why i think its applicable to php [because its already
similar to java])
suppose you have a class,

class N {
  function b() { echo 'b'; }
}

you can create an anonymous sub class like this (added twisted php notation
to give good visual of what could be possible)

$n = new N() {
  function b() { echo "b's been overriden"; }
};

and you can do the same w/ an interface as well, just swap class by
interface in the definition of N above. you can even do this when supplying
an actual parameter to a method call, something like

function callBOnN(N $n) { $n->b(); }

now suppose you dont have an implementation of N, suppose its an interface
or you dont like the base N class (if it were a class) or you like it you
just dont have an instance of it or whatever, you could do this,

callBOnN(new N() {
  function b() { echo 'defined this b on the fly!'; }
});

thats some cool stuff and personally i would much rather see php take this
route than mess around w/ closures. it seems much more natural to me (as
far as the future direction of php). but then again i feel like im way more
into oop than most people on the list let alone the php community as a whole
so likely im hopelessly outnumbered.

-nathan

attached mail follows:


Ray Hauge wrote:
> I've been reading up on some of the parts of PHP that has been suggested
> could be improved so that I could be more well informed. One of the
> more "interesting" (for lack of a better word) suggestions is closures.
> I've used closures primarily in JavaScript, and they are handy in that
> context, but JavaScript handles events and other more dynamic situations
> like that.
>
> I can't really think of any good examples of why I'd want to use a
> closure instead of just calling functions or class methods in PHP.
> Variable functions and call_user_func*() have worked for any of the
> cases where I did need to be a bit more dynamic.
>
> I found a great summary of some discussion on the internals mailing list
> over here: http://devzone.zend.com/node/view/id/2013#Heading1
>
> After reading that article through, I do like Wez's idea of how to
> create anonymous functions. The point about it causing confusion with
> people coming from other languages definitely applies though. This
> article also gives me a second idea for this post. How many people
> would want closures in PHP?
>
> In summary:
>
> Would you want closures in PHP, and why?
>
O.K. so I check wikipedia and read what a closure was :-) But what in a
simple sentence or two would is the benefit of a closure compared to how
you would get the same functionality in PHP now?

-Shawn

attached mail follows:


On Tue, 2008-03-18 at 22:56 -0500, Shawn McKenzie wrote:
> Ray Hauge wrote:
> > I've been reading up on some of the parts of PHP that has been suggested
> > could be improved so that I could be more well informed. One of the
> > more "interesting" (for lack of a better word) suggestions is closures.
> > I've used closures primarily in JavaScript, and they are handy in that
> > context, but JavaScript handles events and other more dynamic situations
> > like that.
> >
> > I can't really think of any good examples of why I'd want to use a
> > closure instead of just calling functions or class methods in PHP.
> > Variable functions and call_user_func*() have worked for any of the
> > cases where I did need to be a bit more dynamic.
> >
> > I found a great summary of some discussion on the internals mailing list
> > over here: http://devzone.zend.com/node/view/id/2013#Heading1
> >
> > After reading that article through, I do like Wez's idea of how to
> > create anonymous functions. The point about it causing confusion with
> > people coming from other languages definitely applies though. This
> > article also gives me a second idea for this post. How many people
> > would want closures in PHP?
> >
> > In summary:
> >
> > Would you want closures in PHP, and why?
> >
> O.K. so I check wikipedia and read what a closure was :-) But what in a
> simple sentence or two would is the benefit of a closure compared to how
> you would get the same functionality in PHP now?

I'm pro closures. Closures allow you to create anonymous functions that
inherit the contextual environment (variables) without the need to
specifically pass the environment (variables). That means within a class
method context I don't need to pass the object to the function, nor do I
need to pass any other variables that have been defined in the method.
The closure can just use them as thought hey had been declared directly
within it's own block. The same thing would happen within a function.
This is very convenient. It goes beyond this though, if I create an
anonymous function and assign it to a variable for later use, it still
inherits the environment. Essentially this enables the environment to
live on beyond the life of the original function in which the closure
was created. This means I can specifically create an environment for
functions/methods, then save off the closures to be run at a later point
and they will retain all the information that was defined in the caller.
Additionally, and unlike using an object instance, the environment is
shared between all functions instantiated within the scope. One might
argue that the same can be done with a singleton... and one would be
correct. Similarly it can be done by pasing around a "singleton" array.
The diffeence is that with a closure the data need not be passed around,
it is part of the function's environment AND the environment is
perfectly hidden from anyone receiving the function (it can't be probed
(not normally anyways)).

Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP

attached mail follows:


im sorry i havent read through all the replies, but i have read through
several of them. i essentially agree w/ Aschwin here. redirects have been
the bane of my existence in several source bases ive worked on. to borrow a
phrase (read in closures article mentioned in another thread) they really
bump up the 'wtf factor'. and ill tell you whats worse, one of the most
horrible things i have ever seen is this crap

<meta http-equiv="refresh" content="0;url=http://wikipedia.org"/>

which is not too dissimilar. i remember my initial encounter with this
construct, it looked as if the page was morphing in front of me, there were
no header() directives on the server there were no window.location calls in
the javascript, it drove me mad, and then when i discovered what it was i
practically became livid. what it boils down to, is the most common usage
of header(location:) is a lack of design capabilities by the person writing
the code on the server side *ducks*. that said, there are plenty of valid
reasons for using them, and i have them in my code in plenty of places, but
plain and simple, if you have a decent sized app, handle routing on the
server side, period.

there is only one caveat i have found that is relevant and that is if GET
parameters in a url from a page submission will incite a change to the
database schema (which is a bad practice anyway) then what can happen is a
page will go to the server, mod the schema, and load up the fresh page
(having been internally routed back to the 'view' code lets say). so then
you have a problem where the 'layman' user will periodically want to see the
latest data on the page (if the data displayed was updated by someone else
in the system for example). so then what happens when they refresh the page?
(the one w/ the GET params that incite the db schema change) well you get
theoretically undefined or at least undesirable behavior,instead of simply
refreshing the 'view' logic, a database schema mod is invoked.

some situations where i find this mechanism useful, and reasonable are
1. implementing pretty urls
2. preventing access to directories
3. mapping one url or sub-domain to another
4. in pitifully trivial applications (of which i have written a few ;)

im sure there are other uses and also im aware that i dont know as much
about http as i should or at least thats how i feel about it anyway. im
sure there are additional uses when implementing restful apis for example.

as aschwin has mentioned about the unnecessary use of server resources (and
bandwidth obviously) i cannot agree enough. what i would say to dissuade
those who view this as a typical page load is, think about the client
experience.
1. unnecessarily long page load time (have to sit through all the mind
numbing redirects)
2. additional, unnecessary full-page reloads
3. awkward transitions in the user interface (morphing described earlier
from previous experience)

this leads to confusion, frustration and in all a degraded experience for
the user. not to mention the confusion, frustration and degradation of the
programming experience for those who have to cleanup a web of these things
on the server side ;)

/end rant

-nathan

attached mail follows:


On Tuesday 18 March 2008, Aschwin Wesselius wrote:

> Point is: why hitting you webserver with multiple requests per user,
> just after submitting a form or whatever caused the redirect? If you
> have 2 users per day, that won't hurt. But if you have 30.000 concurrent
> users a minute, that could be 60.000 requests (besides all the images,
> stylesheets, javascripts that are being re-requested). Or am I talking
> nonsense?

If you send a redirect header, that gets sent before any HTML gets sent so no
JS or images are sent either. The payload cost of a redirect is trivial.

The cost of the second bootstrap process may or may not be problematic. You
have to trade that off against the code simplification you can get out of
redirects (or the code complication you can get if you use it stupidly).

Take for instance Drupal (which I use as an example because I'm a core dev for
it). Drupal does a redirect at the end of every form submission. That
redirect is controllable; it could go back to the form ("submit to self"), or
to a thank you page, or the home page, or to a page in the system that you
just created, or any number of other places. That flexibility is worth the
cost of the second bootstrap (and Drupal's bootstrap is admittedly not
small), especially because the vast majority of Drupal sites and PHP sites in
general are read-heavy, not write-heavy, so it's not a substantial number of
additional bootstraps. It also means that if the user hits reload, they
don't resubmit the form because they're not "on" the POST-requested page.

I will say in general you should not ever have more than one redirect chained
together. While there may be valid reasons for it conceptually, trying to
trace and debug that workflow is overshadow any advantage it could otherwise
offer. (IMO, YMMV, etc.)

--
Larry Garfield AIM: LOLG42
larrygarfieldtech.com ICQ: 6817012

"If nature has made any one thing less susceptible than all others of
exclusive property, it is the action of the thinking power called an idea,
which an individual may exclusively possess as long as he keeps it to
himself; but the moment it is divulged, it forces itself into the possession
of every one, and the receiver cannot dispossess himself of it." -- Thomas
Jefferson

attached mail follows:


On Tuesday 18 March 2008, Jason Pruim wrote:

> I don't know much about the actual load stuff... but I do know unless
> you specifically set it, the CSS should be cached unless you refresh
> it and the date has changed on the file. I assume the same with the
> images as well.

True, but bear in mind that the browser has to make a HEAD request for every
such file in order to determine if it needs to download it again. That's a
non-small amount of HTTP traffic if you have a lot of images or CSS files.
In Drupal (there I go again), we implemented a CSS file aggregator that
merges all queued CSS files into one and caches it, then sends just the one
file. Just switching that aggregator on, I can easily cut page load time in
half.

--
Larry Garfield AIM: LOLG42
larrygarfieldtech.com ICQ: 6817012

"If nature has made any one thing less susceptible than all others of
exclusive property, it is the action of the thinking power called an idea,
which an individual may exclusively possess as long as he keeps it to
himself; but the moment it is divulged, it forces itself into the possession
of every one, and the receiver cannot dispossess himself of it." -- Thomas
Jefferson

attached mail follows:


On Tue, Mar 18, 2008 at 9:45 PM, Larry Garfield <larrygarfieldtech.com>
wrote:

> Take for instance Drupal (which I use as an example because I'm a core dev
> for
> it).

thats pretty cool.

> I will say in general you should not ever have more than one redirect
> chained
> together. While there may be valid reasons for it conceptually, trying to
> trace and debug that workflow is overshadow any advantage it could
> otherwise
> offer. (IMO, YMMV, etc.)

this much i agree w/ and i would say to extend upon it that using multiple
redirection mechanisms in a chain is also a bad idea.
eg.
header(location: ) to some page.
that page uses a meta tag to do a redirect to somewhere else.
ive had to deal w/ this stuff and ended up stripping out all of those stupid
meta tag redirects, as well as many of the header redirects on the server.

-nathan

attached mail follows:


Larry Garfield wrote:

> True, but bear in mind that the browser has to make a HEAD request for
> every such file in order to determine if it needs to download it
> again. That's a non-small amount of HTTP traffic if you have a lot of
> images or CSS files.

True - although I rarely see HEAD requests. I see lots of conditional
GETs instead.

BTW, why does the browser do this for objects it has already cached?
(assuming they're fresh/not expired)

/Per Jessen, Zürich

attached mail follows:


Nathan Nobbe wrote:

> im sorry i havent read through all the replies, but i have read
> through several of them. i essentially agree w/ Aschwin here.

I'm still having difficulties understanding Aschwins main point, as well
as how you can work (properly) with forms without using a 303 redirect.

/Per Jessen, Zürich

attached mail follows:


On 19 Mar 2008, at 09:54, Per Jessen wrote:
> Larry Garfield wrote:
>
>> True, but bear in mind that the browser has to make a HEAD request
>> for
>> every such file in order to determine if it needs to download it
>> again. That's a non-small amount of HTTP traffic if you have a lot
>> of
>> images or CSS files.
>
> True - although I rarely see HEAD requests. I see lots of conditional
> GETs instead.
>
> BTW, why does the browser do this for objects it has already cached?
> (assuming they're fresh/not expired)

Because by default most web servers don't add expiry headers, so it's
up to the browser.

Adding expiry headers for certain content types is very easy in most
web servers and depending on traffic patterns it can cause a very
healthy drop in traffic. Combine that with a convention for new
versions of the files as they get changed and you can put the expiry
date a long time into the future. We use a year on all our images, css
and js files and it's lead to a drop of ~40% in traffic to the static
servers.

-Stut

--
http://stut.net/

attached mail follows:


Stut wrote:

> On 19 Mar 2008, at 09:54, Per Jessen wrote:
>>
>> BTW, why does the browser do this for objects it has already cached?
>> (assuming they're fresh/not expired)
>
> Because by default most web servers don't add expiry headers, so it's
> up to the browser.

My server does add expire headers - and I still see lots of 304s. I've
checked that the expiry information is correct.

> Adding expiry headers for certain content types is very easy in most
> web servers and depending on traffic patterns it can cause a very
> healthy drop in traffic.
> Combine that with a convention for new versions of the files as they
> get changed and you can put the expiry date a long time into the
> future. We use a year on all our images, css and js files and it's
> lead to a drop of ~40% in traffic to the static servers.

Same here - I am just wondering about the need for the conditional GET
then. What makes the browser want to revalidate an object when it has
a valid (=unexpired) copy cached?

/Per Jessen, Zürich

attached mail follows:


On 19 Mar 2008, at 10:11, Per Jessen wrote:
> Stut wrote:
>
>> On 19 Mar 2008, at 09:54, Per Jessen wrote:
>>>
>>> BTW, why does the browser do this for objects it has already cached?
>>> (assuming they're fresh/not expired)
>>
>> Because by default most web servers don't add expiry headers, so it's
>> up to the browser.
>
> My server does add expire headers - and I still see lots of 304s.
> I've
> checked that the expiry information is correct.

We see lots of them as well, but it's far less than before we added
far-future expiry headers.

>> Adding expiry headers for certain content types is very easy in most
>> web servers and depending on traffic patterns it can cause a very
>> healthy drop in traffic.
>> Combine that with a convention for new versions of the files as they
>> get changed and you can put the expiry date a long time into the
>> future. We use a year on all our images, css and js files and it's
>> lead to a drop of ~40% in traffic to the static servers.
>
> Same here - I am just wondering about the need for the conditional GET
> then. What makes the browser want to revalidate an object when it has
> a valid (=unexpired) copy cached?

There could be a number of reasons ranging from browser configuration
to badly implemented caches. There's not a lot you can do about them
beyond making sure your expiry headers are working properly with the
major browsers.

-Stut

--
http://stut.net/

attached mail follows:


another developer brought to my attention the spl method spl_object_hash()
method which afforded a mod in the previously posted class whereby foreach
could be used properly. also, it allows a more efficient internal
implementation. however, to my dismay, it appears that implementing
ArrayAccess does not (not just in this scenario, but in any) allow the class
which does so to hook into the global array methods such as array_keys() or
array_key_exists(). in this sense, i see it as being only about halfway as
useful as it could (or should) be.
what i see ArrayAccess in php as, is something quite similar to properties
in vb.net, if anyones familiar w/ that.
http://www.vbdotnetheaven.com/Uploadfile/rajeshvs/PropertiesInVbDotNet04192005060237AM/PropertiesInVbDotNet.aspx

this is the second scenario where i think there could be c code in php
itself that would override standard behavior provided an spl definition in
user space. sure, the internal code would run a bit slower but imagine
wrapping it in #ifdef directives and mapping those to a configure flag
whereby if spl wasnt enabled that code wasnt included. i think that would
be adequate and it would allow spl to be even more powerful, giving php
programmers the ability to more dramatically, semantically modify the core
w/o writing a scrap of low-level code.

if anybody cares, im happy to send the code for the revision of ObjectArray
that allows usage of the foreach construct over instances of it.

-nathan

attached mail follows:


If I use mysqli's prepared statements in an object and call
mysqli_stmt_bind_params, into which scope does mysqli_stmt_fetch()
place the variables? Can I control it? As of yet, I have no idea
where fetch() stores the results. It is fetching valid data. I'd
really like to use the OO style of MySQLi if possible. Any help or
guidance is greatly appreciated.

The offending code is as follows:

class StmtIterator {

        private $data = 'test';
        private $host = 'localhost';
        private $user = 'root';
        private $pass = '';

        private $db; // Database connection
        private $st; // Prepared statement

        private $sql = "";

        public function __construct ($sql, Array $params){
                $this->db = mysqli_init();
                $this->db->real_connect($this->host, $this->user, $this->pass, $this-
>data);

                $this->sql = $sql;

                $this->st = $this->db->stmt_init();
                $this->st->prepare($this->sql);
                $this->st->execute();

                call_user_func_array(array($this->st, 'bind_result'), $params);
        }

        public function fetch (){
                $result = $this->st->fetch();
                if ($result !== true) echo "No data fetched.";

                echo "Name is...<br /> ";
                echo isset($this->st->name)
                        ? "in this->st->name as {$this->st->name}.<br />"
                        : null;
                echo isset($this->db->name)
                        ? "in this->db->name as {$this->db->name}.<br />"
                        : null;
                echo isset($this->params['name'])
                        ? "in this->params['name'] as {$this->params['name']}.<br />"
                         : null;
                echo isset($this->name)
                        ? " this->name as {$this->name}.<br />"
                        : null;
                echo isset($name)
                        ? "in name as {$name}.<br />"
                        : null;

                return $result;
        }

        public function __destruct (){
                $this->st->close();
                $this->db->close();
        }

}

$sql = "
        SELECT `id`, `name`
        FROM `user`
        WHERE 1
";

$params = array(
        'id',
        'name',
);

$user_iterator = new StmtIterator($sql, $params);

while ($user_iterator->fetch()){
        echo isset($this->db->name)
                ? "in the local scope name as {$name}.<br />"
                : null;
}

Jeremy Mcentire
Ant Farmer
ZooToo LLC

attached mail follows:


Jason Pruim schreef:
>
> On Mar 18, 2008, at 3:20 PM, Jochem Maas wrote:
>
>> what started out as a simple little reply bloated out into an
>> inpromptu brain
>> fart ... lots of bla .. enjoy :-)
>>
>> Jason Pruim schreef:
>>> Hi everyone,
>>> I am attempting to add a little error checking for a very simple
>>> login system. The info is stored in a MySQL database, and I am using
>>> mysqli to connect to it. I have it working with the solution provided
>>> below, but I am wondering if this is the right way to do it or if
>>> there is a better way?
>>
>> at an abstract level you might consider that your function could simply
>> always return a boolean (true = logged in, false = not logged in) and
>> that the
>> rest of the application retrieves all the other data via the session
>> (as opposed to returning half the data and storing half in the session)
>
> I think this is what I am attempting to do... Just going about it all
> wrong...

start from scratch again?

>
> I want the pages to check to see if the person is still logged in and if
> they are, then it's pulling live data from the database... So maybe I
> should edit my authentication function...

maybe.
there are two different things being confused:

1. checking logged in state.
2. attempting to login.

function getUserData()
{
        if (isAuthenticatedUser())
                return $_SESSION['user']['data'];

        return null;
}

function isAuthenticatedUser()
{
        return (isset($_SESSION['user']['authenticated']) && $_SESSION['user']['authenticated']);
}

function authenticateUser($u, $p, $cc = false)
{
        if (($iau = isAuthenticatedUser()) && !$cc)
                throw Exception('Already logged in!');

        $cmd = $iau ? 'verify account' : 'login';

        if (!($p = trim($p)) || !($u = trim($u)))
                throw Exception('Cannot '.$cmd.' without credentials!');

        $p = mysql_real_escape_string($p);
        $u = mysql_real_escape_string($u);

        if (!($res = mysql_query("SELECT * FROM `users` WHERE 'pwd'='$p' AND `usr`='$u'")))
                throw Exception('Cannot '.$cmd.', verification system error.');

        if (mysql_num_rows($res) != 1)
                return false;
                                
        if (!($row = mysql_fetch_assoc($res)))
                throw Exception('Cannot '.$cmd.', verification system error.');
                
        if ($iau)
                return (int)$_SESSION['user']['data']['id'] === (int)$row['id'];
                
        unset($row['pwd']);

        $_SESSION['user'] = array(
                'authenticated' => true,
                'data' => $row,
        );

        return true;
}

>
> function auth($loggedin) {
> query database to see if username & Password match;
> write certain variables into session (Or maybe into the cache?)

> return true if it matches
> if not return false which could then redirect back to login page...
> }
>
> Is it that simple? Am I trying to make things so much more complicated?
>>
>>
>> if you choose to store everything and only return authentication state
>> you
>> might also consider to abstract the storage somewhat so that other
>> code doesn't
>> have to access the session data directly. we call this concept 'loose
>> coupling'.
>> for instance:
>>
>> function getUserInfo($key = null)
>> {
>> if (!isset($_SESSION['user']['loggedin']))
>> return null;
>>
>> if (!$_SESSION['loggedin'])
>> return null;
>>
>> $key = trim((string)$key);
>>
>> if ($key == '')
>> return $_SESSION['user'];
>>
>> if (isset($_SESSION['user'][$key]))
>> return $_SESSION['user'][$key];
>>
>> return null;
>> }
>>
>> this example still requires that the the consumer of getUserInfo() knows
>> the names of the relevant columns (from multiple tables?)
>
> login info is stored on 1 table, while the actual records in the DB are
> stored on another table. After successful login it changes from the
> login table to the data table.
>
>> .. this could also
>> be abstracted, a simple solution would be something like:
>>
>> // put these in a config file, (CKEY = 'cache key' ... just a thought)
>> define('CKEY_USER_NAME', 'loginName');
>> define('CKEY_USER_LEVEL', 'adminLevel');
>> define('CKEY_USER_TABLE', 'tableName');
>>
>>
>> $uName = getUserInfo( CKEY_USER_NAME );
>> $uLevel = getUserInfo( CKEY_USER_LEVEL );
>> $uLevel = getUserInfo( CKEY_USER_TABLE );
>
> And then that would hold the info in a cache until the user hit logout
> and then logged back in? I'm going to try that right after sending this
> message.... That may work perfectly...
>
> Also I'm assuming if I put these into an include file it will work just
> like my other variables where I can call $pass from any page that
> includes the file $pass is defined in?
>>
>>
>> ... you get? ... incidentally your column names seem to be
>> case-sensitive,
>> I recommend lower or upper (depending on DBMS) case only for sql
>> entity names
>> for two reasons:
>>
>> 1. you avoid nitpicky irritations due to SQL case-sensitivity related
>> bugs
>> in your code.
>>
>> 2. if you lowercase all entity names you can write stuff like so:
>>
>> $sql = "SELECT foo, bar FROM qux WHERE abc = 1 AND def=2";
>>
>> which is a little more readable than this:
>>
>> $sql = "SELECT FOO, BAR FROM QUX WHERE ABC = 1 AND DEF=2";
>>
>> of course it should be more like:
>>
>> $sql = "SELECT `foo`, `bar` FROM `qux` WHERE `abc`=1 AND `def`=2";
>>
>> using case to differentiate between SQL and entity names becomes more
>> useful
>> as the queries become more complex. I also tend to then break then up
>> into lines:
>>
>> $sql = "SELECT
>> q.`foo', q.`bar`,
>> na.`foo` AS nafoo, na.`bar` AS nabar,
>> noo.`foo` AS noofoo, noo.`bar` AS noobar,
>> FROM
>> `qux` AS q
>> LEFT JOIN
>> `na` AS na ON na.`qux_id` = q.`id`
>> LEFT JOIN
>> `noo` AS noo ON noo.`qux_id` = q.`id`
>> WHERE
>> (`abc`=? AND `def`=?)
>> AND
>> q.`id` IN (SELECT `qux_id` FROM `quxnobbins` WHERE
>> `nobbin_id`=?)
>> AND (
>> (`start_date` BETWEEN ? AND ?) OR
>> (`start_date` BETWEEN ? AND ?)
>> )";
>>
>>
>>
>>> My thinking with this is if more then 1 record is returned from the
>>> database, then there is a issue... If only is returned then the
>>> username/password matched and I can safely show them the info...
>>> $rowcnt = mysqli_num_rows($loginResult);
>>
>> we'll assume the original sql was suitably prepared (i.e. user values
>> escaped, etc).
>> but why not 'fix' the query and/or table so that it will only ever
>> return one row?
>>
>>> if($rowcnt !="1"){
>>
>> avoid auto-casting!
>>
>> if ($rowcnt !== 1) { /*...*/ }
>>
>>> echo "Auth failed";
>>> die("Auth failed... Sorry");
>>> }else{
>>> while($row1 = mysqli_fetch_array($loginResult)) {
>>
>> this 'while' is completely pointless, you know there is just one row,
>> no point in looping for a single iteration.
>
> Will make that change now :)
>>
>>
>> just do:
>>
>> $row = mysqli_fetch_array($loginResult);
>> $_SESSION['user'] = $row['loginName'];
>> // ... etc
>>
>>
>>> $_SESSION['user'] = $row1['loginName'];
>>> $_SESSION['loggedin'] = "YES";
>>
>> "YES" is not a boolean value, I think $_SESSION['loggedin'] should be
>> boolean (you got deja vu here also?).
>
> Just to double check: $_SESSION['loggedin'] = TRUE; //Is a boolean while:
> $_SESSION['loggedin'] = "TRUE"; // is not correct?
>
>>
>>
>> check the following code to see why:
>>
>> $_SESSION['loggedin'] = "FALSE";
>> if ($_SESSION['loggedin'])
>> echo "your logged in!";
>>
>>
>>
>>> $table = $row1['tableName'];
>>> $adminLevel = $row1['adminLevel'];
>>> $authenticated = "TRUE";
>>
>> again the boolean should be boolean!
>>
>>> echo "<BR>authentication complete";
>>
>> with regard to seperation of responsibilities: the function should
>> really be either attempting an authentication *or* outputting some
>> message
>> regarding the result of the authentication attempt but *not* both.
>
> That was added for debugging, helping me track down where the error was.
>>
>>
>> in practice this means my recommendation would be to remove the echo
>> statements
>> from the function and have the code that calls this function be
>> responsible for
>> outputting feedback ... imagine if you need to, someday, perform an
>> authentication
>> without [direct] output? or you need to change the outputted message
>> under certain
>> conditions (conditions which are outside the scope of this function)?
>>
>> a function should, as much as is possible, do one thing only (and do
>> it well), otherwise,
>> I guess, it would be called a functions. ;-)
>>
>>> }
>>> return Array($table, $authenticated, $adminLevel);
>>
>> pretty much the rest of the world writes 'Array()' as 'array()' .. the
>> convention
>> being that built in functions and lang constructs are always typed
>> lowercase. some
>> people write things like isSet($foo); ... but they are 'wrong' :-)
>
> I thought I saw on the php.net page that it was Array() :)
>>
>>
>> I generally try to distinguish between userland and php functions by
>> using lowercase
>> for php funcs and CamelCase naming schemes for userland functions.
>
> I see what you're getting at though... And I need to do that more
> through my applications..
>
>
>>
>>
>> --
>> "ok, porky pig say your line."
>>
>
> --
>
> Jason Pruim
> Raoset Inc.
> Technology Manager
> MQC Specialist
> 3251 132nd ave
> Holland, MI, 49424-9337
> www.raoset.com
> japruimraoset.com
>
>
>

attached mail follows:


Why is Jason schreefing again?

Jochem Maas wrote:
> Jason Pruim schreef:
>>
>> On Mar 18, 2008, at 3:20 PM, Jochem Maas wrote:
>>
>>> what started out as a simple little reply bloated out into an
>>> inpromptu brain
>>> fart ... lots of bla .. enjoy :-)
>>>
>>> Jason Pruim schreef:
>>>> Hi everyone,
>>>> I am attempting to add a little error checking for a very simple
>>>> login system. The info is stored in a MySQL database, and I am using
>>>> mysqli to connect to it. I have it working with the solution
>>>> provided below, but I am wondering if this is the right way to do it
>>>> or if there is a better way?
>>>
>>> at an abstract level you might consider that your function could simply
>>> always return a boolean (true = logged in, false = not logged in) and
>>> that the
>>> rest of the application retrieves all the other data via the session
>>> (as opposed to returning half the data and storing half in the session)
>>
>> I think this is what I am attempting to do... Just going about it all
>> wrong...
>
> start from scratch again?
>
>>
>> I want the pages to check to see if the person is still logged in and
>> if they are, then it's pulling live data from the database... So
>> maybe I should edit my authentication function...
>
> maybe.
> there are two different things being confused:
>
> 1. checking logged in state.
> 2. attempting to login.
>
> function getUserData()
> {
> if (isAuthenticatedUser())
> return $_SESSION['user']['data'];
>
> return null;
> }
>
> function isAuthenticatedUser()
> {
> return (isset($_SESSION['user']['authenticated']) &&
> $_SESSION['user']['authenticated']);
> }
>
> function authenticateUser($u, $p, $cc = false)
> {
> if (($iau = isAuthenticatedUser()) && !$cc)
> throw Exception('Already logged in!');
>
> $cmd = $iau ? 'verify account' : 'login';
>
> if (!($p = trim($p)) || !($u = trim($u)))
> throw Exception('Cannot '.$cmd.' without credentials!');
>
> $p = mysql_real_escape_string($p);
> $u = mysql_real_escape_string($u);
>
> if (!($res = mysql_query("SELECT * FROM `users` WHERE 'pwd'='$p' AND
> `usr`='$u'")))
> throw Exception('Cannot '.$cmd.', verification system error.');
>
> if (mysql_num_rows($res) != 1)
> return false;
>
> if (!($row = mysql_fetch_assoc($res)))
> throw Exception('Cannot '.$cmd.', verification system error.');
>
> if ($iau)
> return (int)$_SESSION['user']['data']['id'] === (int)$row['id'];
>
> unset($row['pwd']);
>
> $_SESSION['user'] = array(
> 'authenticated' => true,
> 'data' => $row,
> );
>
> return true;
> }
>
>>
>> function auth($loggedin) {
>> query database to see if username & Password match;
>> write certain variables into session (Or maybe into the cache?)
>
>
>
>> return true if it matches
>> if not return false which could then redirect back to login page...
>> }
>>
>> Is it that simple? Am I trying to make things so much more complicated?
>>>
>>>
>>> if you choose to store everything and only return authentication
>>> state you
>>> might also consider to abstract the storage somewhat so that other
>>> code doesn't
>>> have to access the session data directly. we call this concept 'loose
>>> coupling'.
>>> for instance:
>>>
>>> function getUserInfo($key = null)
>>> {
>>> if (!isset($_SESSION['user']['loggedin']))
>>> return null;
>>>
>>> if (!$_SESSION['loggedin'])
>>> return null;
>>>
>>> $key = trim((string)$key);
>>>
>>> if ($key == '')
>>> return $_SESSION['user'];
>>>
>>> if (isset($_SESSION['user'][$key]))
>>> return $_SESSION['user'][$key];
>>> return null;
>>> }
>>>
>>> this example still requires that the the consumer of getUserInfo() knows
>>> the names of the relevant columns (from multiple tables?)
>>
>> login info is stored on 1 table, while the actual records in the DB
>> are stored on another table. After successful login it changes from
>> the login table to the data table.
>>
>>> .. this could also
>>> be abstracted, a simple solution would be something like:
>>>
>>> // put these in a config file, (CKEY = 'cache key' ... just a thought)
>>> define('CKEY_USER_NAME', 'loginName');
>>> define('CKEY_USER_LEVEL', 'adminLevel');
>>> define('CKEY_USER_TABLE', 'tableName');
>>>
>>>
>>> $uName = getUserInfo( CKEY_USER_NAME );
>>> $uLevel = getUserInfo( CKEY_USER_LEVEL );
>>> $uLevel = getUserInfo( CKEY_USER_TABLE );
>>
>> And then that would hold the info in a cache until the user hit logout
>> and then logged back in? I'm going to try that right after sending
>> this message.... That may work perfectly...
>>
>> Also I'm assuming if I put these into an include file it will work
>> just like my other variables where I can call $pass from any page that
>> includes the file $pass is defined in?
>>>
>>>
>>> ... you get? ... incidentally your column names seem to be
>>> case-sensitive,
>>> I recommend lower or upper (depending on DBMS) case only for sql
>>> entity names
>>> for two reasons:
>>>
>>> 1. you avoid nitpicky irritations due to SQL case-sensitivity related
>>> bugs
>>> in your code.
>>>
>>> 2. if you lowercase all entity names you can write stuff like so:
>>>
>>> $sql = "SELECT foo, bar FROM qux WHERE abc = 1 AND def=2";
>>>
>>> which is a little more readable than this:
>>>
>>> $sql = "SELECT FOO, BAR FROM QUX WHERE ABC = 1 AND DEF=2";
>>>
>>> of course it should be more like:
>>>
>>> $sql = "SELECT `foo`, `bar` FROM `qux` WHERE `abc`=1 AND `def`=2";
>>>
>>> using case to differentiate between SQL and entity names becomes more
>>> useful
>>> as the queries become more complex. I also tend to then break then up
>>> into lines:
>>>
>>> $sql = "SELECT
>>> q.`foo', q.`bar`,
>>> na.`foo` AS nafoo, na.`bar` AS nabar,
>>> noo.`foo` AS noofoo, noo.`bar` AS noobar,
>>> FROM
>>> `qux` AS q
>>> LEFT JOIN
>>> `na` AS na ON na.`qux_id` = q.`id`
>>> LEFT JOIN
>>> `noo` AS noo ON noo.`qux_id` = q.`id`
>>> WHERE
>>> (`abc`=? AND `def`=?)
>>> AND
>>> q.`id` IN (SELECT `qux_id` FROM `quxnobbins` WHERE
>>> `nobbin_id`=?)
>>> AND (
>>> (`start_date` BETWEEN ? AND ?) OR
>>> (`start_date` BETWEEN ? AND ?)
>>> )";
>>>
>>>
>>>
>>>> My thinking with this is if more then 1 record is returned from the
>>>> database, then there is a issue... If only is returned then the
>>>> username/password matched and I can safely show them the info...
>>>> $rowcnt = mysqli_num_rows($loginResult);
>>>
>>> we'll assume the original sql was suitably prepared (i.e. user values
>>> escaped, etc).
>>> but why not 'fix' the query and/or table so that it will only ever
>>> return one row?
>>>
>>>> if($rowcnt !="1"){
>>>
>>> avoid auto-casting!
>>>
>>> if ($rowcnt !== 1) { /*...*/ }
>>>
>>>> echo "Auth failed";
>>>> die("Auth failed... Sorry");
>>>> }else{
>>>> while($row1 = mysqli_fetch_array($loginResult)) {
>>>
>>> this 'while' is completely pointless, you know there is just one row,
>>> no point in looping for a single iteration.
>>
>> Will make that change now :)
>>>
>>>
>>> just do:
>>>
>>> $row = mysqli_fetch_array($loginResult);
>>> $_SESSION['user'] = $row['loginName'];
>>> // ... etc
>>>
>>>
>>>> $_SESSION['user'] = $row1['loginName'];
>>>> $_SESSION['loggedin'] = "YES";
>>>
>>> "YES" is not a boolean value, I think $_SESSION['loggedin'] should be
>>> boolean (you got deja vu here also?).
>>
>> Just to double check: $_SESSION['loggedin'] = TRUE; //Is a boolean while:
>> $_SESSION['loggedin'] = "TRUE"; // is not correct?
>>
>>>
>>>
>>> check the following code to see why:
>>>
>>> $_SESSION['loggedin'] = "FALSE";
>>> if ($_SESSION['loggedin'])
>>> echo "your logged in!";
>>>
>>>
>>>
>>>> $table = $row1['tableName'];
>>>> $adminLevel = $row1['adminLevel'];
>>>> $authenticated = "TRUE";
>>>
>>> again the boolean should be boolean!
>>>
>>>> echo "<BR>authentication complete";
>>>
>>> with regard to seperation of responsibilities: the function should
>>> really be either attempting an authentication *or* outputting some
>>> message
>>> regarding the result of the authentication attempt but *not* both.
>>
>> That was added for debugging, helping me track down where the error was.
>>>
>>>
>>> in practice this means my recommendation would be to remove the echo
>>> statements
>>> from the function and have the code that calls this function be
>>> responsible for
>>> outputting feedback ... imagine if you need to, someday, perform an
>>> authentication
>>> without [direct] output? or you need to change the outputted message
>>> under certain
>>> conditions (conditions which are outside the scope of this function)?
>>>
>>> a function should, as much as is possible, do one thing only (and do
>>> it well), otherwise,
>>> I guess, it would be called a functions. ;-)
>>>
>>>> }
>>>> return Array($table, $authenticated, $adminLevel);
>>>
>>> pretty much the rest of the world writes 'Array()' as 'array()' ..
>>> the convention
>>> being that built in functions and lang constructs are always typed
>>> lowercase. some
>>> people write things like isSet($foo); ... but they are 'wrong' :-)
>>
>> I thought I saw on the php.net page that it was Array() :)
>>>
>>>
>>> I generally try to distinguish between userland and php functions by
>>> using lowercase
>>> for php funcs and CamelCase naming schemes for userland functions.
>>
>> I see what you're getting at though... And I need to do that more
>> through my applications..
>>
>>
>>>
>>>
>>> --
>>> "ok, porky pig say your line."
>>>
>>
>> --
>>
>> Jason Pruim
>> Raoset Inc.
>> Technology Manager
>> MQC Specialist
>> 3251 132nd ave
>> Holland, MI, 49424-9337
>> www.raoset.com
>> japruimraoset.com
>>
>>
>>
>

attached mail follows:


On Mar 19, 2008, at 12:02 AM, Shawn McKenzie wrote:

> Why is Jason schreefing again?

Because I'm good at it? ;)

--

Jason Pruim
Raoset Inc.
Technology Manager
MQC Specialist
3251 132nd ave
Holland, MI, 49424-9337
www.raoset.com
japruimraoset.com

attached mail follows:


Hi all,

What do you think is the FASTEST sql to get the total number of a table
with millions of records?

--
Regards,
Shelley (http://phparch.cn)

attached mail follows:


On Tue, Mar 18, 2008 at 11:43 PM, Shelley <myphplistgmail.com> wrote:

> Hi all,
>
> What do you think is the FASTEST sql to get the total number of a table
> with millions of records?

when you say 'total number' do you mean the total number of records? in
that case assuming the table has a field 'id' then i think
select count(id) from some_table;

-nathan

attached mail follows:


instead of using mysql database which is conventionally used as database
with php, if sql server database is used with php are there any major
differences to keep in mind.

1.
are the connection statements ex = $conn = mysql_connect($hostname, $user,
$dbpassword); etc does these remain the same or are they different.

2.
unlike in mysql with phpmyadmin which is browser based to access databases
and tables how to access sql server for the same functionality

3.
can anyone provide a link about a manual for using sql database with php

thanks.

attached mail follows:


Sudhakar wrote:
> instead of using mysql database which is conventionally used as database
> with php, if sql server database is used with php are there any major
> differences to keep in mind.

In syntax or what? Yes there are differences between the two as far as
sql syntax goes.

> 1.
> are the connection statements ex = $conn = mysql_connect($hostname, $user,
> $dbpassword); etc does these remain the same or are they different.

Of course they are different. Why would mysql_connect (note the "MYSQL"
part of that) connect to anything but a mysql database?

> 2.
> unlike in mysql with phpmyadmin which is browser based to access databases
> and tables how to access sql server for the same functionality

I think mssql has something like phpmyadmin built into the server itself.

> 3.
> can anyone provide a link about a manual for using sql database with php

http://php.net/mssql

--
Postgresql & php tutorials
http://www.designmagick.com/

attached mail follows:


On Mar 18, 2008, at 1008PM, Sudhakar wrote:
> 1. are the connection statements ex = $conn =
> mysql_connect($hostname, $user,
> $dbpassword); etc does these remain the same or are they different.

http://php.net/mssql

> 2. unlike in mysql with phpmyadmin which is browser based to access
> databases
> and tables how to access sql server for the same functionality

http://www.mylittleadmin.com/en/welcome.aspx

> 3. can anyone provide a link about a manual for using sql database
> with php

http://php.net/mssql