Re: [PHP] Custom function
"Andre Polykanine" wrote: >Hello Ashley, > >By the way, the non-last optional parameter can't be missed, am I >right? In some languages we could write something like: >function test ($a, $foo=50, $bar=true) { >// ... >} > >Then call it like this: > >$m=test("blah", , false); > >meaning > >$m=test("blah", 50, false); >This is impossible in PHP, isn't it? >Thanks! > >-- >With best regards from Ukraine, >Andre >Skype: Francophile >My blog: http://oire.org/menelion (mostly in Russian) >Twitter: http://twitter.com/m_elensule >Facebook: http://facebook.com/menelion > >-------- Original message >From: Ashley Sheridan >To: Ron Piggott >Date created: , 1:37:59 AM >Subject: [PHP] Custom function > > > On Mon, 2011-05-02 at 18:28 -0400, Ron Piggott wrote: > >> On Mon, May 2, 2011 at 3:16 PM, Ron Piggott > wrote: >> >> >> Is it possible to write a function with an optional flag? What >would the syntax look like? >> >> So far I have: >> >> function load_advertisement( $web_page_reference , >$web_advertising_sizes_reference ) { >> >> >> >> Hi Ron: >> >> I'm not sure what you mean by "optional flag"? Do you mean an >optional parameter? >> >> Richard >> >> >> Correct Richard. Ron > > >function load_advertisement( $web_page_reference , >$web_advertising_sizes_reference=default_value) > >This sets a default value for a parameter, which you can check for >within the function itself and use it if it differs from what you set. >Set it to something that it shouldn't be, like null or something. > >Also note that these parameters have to occur after any that don't have >a default value > >-- >Thanks, >Ash >http://www.ashleysheridan.co.uk > > > >-- >PHP General Mailing List (http://www.php.net/) >To unsubscribe, visit: http://www.php.net/unsub.php Yes, it behaves like any built-in php function in that respect, you can't omit a parameter mid-way in a param list. However, you can give it a dummy value that you can look for and ignore in your code, but it gets a little more complex then. I did forget to mention that a function also has a special func_get_args() method that can be used to access parameters sent to the function that weren't in the function declaration. Thanks Ash -- Sent from my Android phone with K-9 Mail. Please excuse my brevity. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
Hello Ashley, By the way, the non-last optional parameter can't be missed, am I right? In some languages we could write something like: function test ($a, $foo=50, $bar=true) { // ... } Then call it like this: $m=test("blah", , false); meaning $m=test("blah", 50, false); This is impossible in PHP, isn't it? Thanks! -- With best regards from Ukraine, Andre Skype: Francophile My blog: http://oire.org/menelion (mostly in Russian) Twitter: http://twitter.com/m_elensule Facebook: http://facebook.com/menelion Original message From: Ashley Sheridan To: Ron Piggott Date created: , 1:37:59 AM Subject: [PHP] Custom function On Mon, 2011-05-02 at 18:28 -0400, Ron Piggott wrote: > On Mon, May 2, 2011 at 3:16 PM, Ron Piggott > wrote: > > > Is it possible to write a function with an optional flag? What would the > syntax look like? > > So far I have: > > function load_advertisement( $web_page_reference , > $web_advertising_sizes_reference ) { > > > > Hi Ron: > > I'm not sure what you mean by "optional flag"? Do you mean an optional > parameter? > > Richard > > > Correct Richard. Ron function load_advertisement( $web_page_reference , $web_advertising_sizes_reference=default_value) This sets a default value for a parameter, which you can check for within the function itself and use it if it differs from what you set. Set it to something that it shouldn't be, like null or something. Also note that these parameters have to occur after any that don't have a default value -- Thanks, Ash http://www.ashleysheridan.co.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On Mon, 2011-05-02 at 18:28 -0400, Ron Piggott wrote: > On Mon, May 2, 2011 at 3:16 PM, Ron Piggott > wrote: > > > Is it possible to write a function with an optional flag? What would the > syntax look like? > > So far I have: > > function load_advertisement( $web_page_reference , > $web_advertising_sizes_reference ) { > > > > Hi Ron: > > I'm not sure what you mean by "optional flag"? Do you mean an optional > parameter? > > Richard > > > Correct Richard. Ron function load_advertisement( $web_page_reference , $web_advertising_sizes_reference=default_value) This sets a default value for a parameter, which you can check for within the function itself and use it if it differs from what you set. Set it to something that it shouldn't be, like null or something. Also note that these parameters have to occur after any that don't have a default value -- Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] Custom function
On Mon, May 2, 2011 at 3:16 PM, Ron Piggott wrote: Is it possible to write a function with an optional flag? What would the syntax look like? So far I have: function load_advertisement( $web_page_reference , $web_advertising_sizes_reference ) { Hi Ron: I'm not sure what you mean by "optional flag"? Do you mean an optional parameter? Richard Correct Richard. Ron
Re: [PHP] Custom function
On Mon, May 2, 2011 at 3:16 PM, Ron Piggott wrote: > > Is it possible to write a function with an optional flag? What would the > syntax look like? > > So far I have: > > function load_advertisement( $web_page_reference , > $web_advertising_sizes_reference ) { > Hi Ron: I'm not sure what you mean by "optional flag"? Do you mean an optional parameter? Richard -- Sláinte, Richard S. Crawford (rich...@underpope.com) http://www.underpope.com Publisher and Editor in Chief, Daikaijuzine (http://www.daikaijuzine.com)
[PHP] Custom function
Is it possible to write a function with an optional flag? What would the syntax look like? So far I have: function load_advertisement( $web_page_reference , $web_advertising_sizes_reference ) { Thanks Ron The Verse of the Day “Encouragement from God’s Word” http://www.TheVerseOfTheDay.info
Re: [PHP] Custom function
On 16 February 2011 22:04, Paul M Foster wrote: > On Wed, Feb 16, 2011 at 09:21:20PM +0100, Peter Lind wrote: > >> On 16 February 2011 21:00, Dan Schaefer wrote: >> > In my code, I set the optional parameter to NULL and check for triple >> equals >> > "===" or "!==" to see if the variable has been passed with a value. IMO, >> > this is the safest way. >> > >> > function MyFunction($x, $y, $z=NULL) { >> > if ($z !== NULL) { >> > // Do Something >> > } >> > } >> >> In case you're actually trying to test if a variable was passed or not >> that doesn't work (as it doesn't detect NULL passed in). Use >> func_get_args() as that gives you any and all arguments passed to the >> function, excluding defaults. > > This must be my week to make enemies. > > I beg to differ. If the user passes in NULL for $z or passes in nothing > for that variable, it does in fact show up as NULL. The following test > code works as indicated: Did anyone say it wouldn't? > > The responses in the first and third cases are NULL. You might be able > to argue that in the first case, where the user passed in NULL, it's > not the same as if the user passed in nothing. But I would assume that the > author considers NULL a signal value, such that if the user passed such > a value in, it would be equivalent to not passing a value for the third > parameter. The point I was trying to make was specifically that someone might try to distinguish whether a value was passed in for an optional parameter or not (like the case Adam outlined). Relying on the value of the optional parameter will not do, in that case (well it might, depending upon how stringent you really need to be). >> >> That said, if you're making use of optional parameters and need to >> check if anything was passed in, you're almost certainly doing things >> wrong. > > Again, assuming you're talking about examples like the one above, I have > to disagree. Presumably, passing in an optional parameter changes the > action inside the function. Thus, you would *need* to test for its > presence. Otherwise, you would be stuck with assuming it's there, > attempting to use it on that assumption, and dealing with whatever > errors it causes when-- surprise!-- it's not there. You should be wary of assumptions, they're not really working out for you. - a) you're not addressing Adam's use case - b) I wouldn't need to test for any presence if I wrote the function as I would personally prefer, i.e. not trying to test if any value was passed to the function or not. That's the whole point of optional values: even if nothing is passed in, there's a default value. That's why trying to check if something was passed for the optional parameter is counter-productive: the idea of the default value is that you shouldn't have to check. Regards Peter -- WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On Wed, Feb 16, 2011 at 09:21:20PM +0100, Peter Lind wrote: > On 16 February 2011 21:00, Dan Schaefer wrote: > > In my code, I set the optional parameter to NULL and check for triple > equals > > "===" or "!==" to see if the variable has been passed with a value. IMO, > > this is the safest way. > > > > function MyFunction($x, $y, $z=NULL) { > > if ($z !== NULL) { > > // Do Something > > } > > } > > In case you're actually trying to test if a variable was passed or not > that doesn't work (as it doesn't detect NULL passed in). Use > func_get_args() as that gives you any and all arguments passed to the > function, excluding defaults. This must be my week to make enemies. I beg to differ. If the user passes in NULL for $z or passes in nothing for that variable, it does in fact show up as NULL. The following test code works as indicated: function pizza($a, $b, $c = NULL) { if ($c === NULL) echo "c is null\n"; elseif ($c !== NULL) echo "c is not null. it has a value of $c\n"; else echo "indeterminate: c is $c\n"; } pizza(1, 2, NULL); pizza(1, 2, 3); pizza(1, 2); =-=-=-=-=-=-= The responses in the first and third cases are NULL. You might be able to argue that in the first case, where the user passed in NULL, it's not the same as if the user passed in nothing. But I would assume that the author considers NULL a signal value, such that if the user passed such a value in, it would be equivalent to not passing a value for the third parameter. > > That said, if you're making use of optional parameters and need to > check if anything was passed in, you're almost certainly doing things > wrong. Again, assuming you're talking about examples like the one above, I have to disagree. Presumably, passing in an optional parameter changes the action inside the function. Thus, you would *need* to test for its presence. Otherwise, you would be stuck with assuming it's there, attempting to use it on that assumption, and dealing with whatever errors it causes when-- surprise!-- it's not there. Paul -- Paul M. Foster http://noferblatz.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On 16 February 2011 21:45, Adam Richardson wrote: > On Wed, Feb 16, 2011 at 3:21 PM, Peter Lind wrote: > >> On 16 February 2011 21:00, Dan Schaefer wrote: >> > In my code, I set the optional parameter to NULL and check for triple >> equals >> > "===" or "!==" to see if the variable has been passed with a value. IMO, >> > this is the safest way. >> > >> > function MyFunction($x, $y, $z=NULL) { >> > if ($z !== NULL) { >> > // Do Something >> > } >> > } >> >> In case you're actually trying to test if a variable was passed or not >> that doesn't work (as it doesn't detect NULL passed in). Use >> func_get_args() as that gives you any and all arguments passed to the >> function, excluding defaults. >> > > I'm not sure what you're saying here, Peter? Are you saying that the code > wouldn't detect if $z was set to NULL by the calling code or by the default? > I believe the point would be that no matter the case, the check would still > perform the same task. > > Maybe I misunderstood (sorry.) The point is the poster seemed to suggest the safest way to use optional parameters was to use null as the default value and use === null to check against the optional parameter - as a way to check if anything was passed in or not. I just pointed out that that would fail to check for a null passed in and that func_get_args() would be a better match. You're obviously right that the check inside the function would work the same whether null was passed in or the value was defaulted to null. > >> >> That said, if you're making use of optional parameters and need to >> check if anything was passed in, you're almost certainly doing things >> wrong. >> > > I sometimes use this approach. PHP doesn't to my knowledge allow you to use > function calls within defaults. There are times that I want the default to > be the result of a function, and to accomplish this, I'll often set the > default to null, then check for the null and carry out the function within. > > Is there a better solution? As noted in the post, func_get_args will show any and all (at least on my 5.3.3 install and 5.2.6 install) values passed in to the function - hence it will also show if no parameter was passed in (and is thus safer than relying on the default value). That noted, I don't think checking if a value was passed in is good design - I think the function should be ignorant of what is passed to it. But that's just me :) Regards Peter -- WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On 16 February 2011 21:45, Andre Polykanine wrote: > Hello Peter, > > So is > func_get_args() > the unique way? > Not really sure what you mean by the unique way. Most things proposed so far in the thread would be fine for most purposes, I'd say. If you really need finegrained control, I'd suggest func_get_args. Regards Peter -- WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On Wed, Feb 16, 2011 at 3:21 PM, Peter Lind wrote: > On 16 February 2011 21:00, Dan Schaefer wrote: > > In my code, I set the optional parameter to NULL and check for triple > equals > > "===" or "!==" to see if the variable has been passed with a value. IMO, > > this is the safest way. > > > > function MyFunction($x, $y, $z=NULL) { > > if ($z !== NULL) { > > // Do Something > > } > > } > > In case you're actually trying to test if a variable was passed or not > that doesn't work (as it doesn't detect NULL passed in). Use > func_get_args() as that gives you any and all arguments passed to the > function, excluding defaults. > I'm not sure what you're saying here, Peter? Are you saying that the code wouldn't detect if $z was set to NULL by the calling code or by the default? I believe the point would be that no matter the case, the check would still perform the same task. Maybe I misunderstood (sorry.) > > That said, if you're making use of optional parameters and need to > check if anything was passed in, you're almost certainly doing things > wrong. > I sometimes use this approach. PHP doesn't to my knowledge allow you to use function calls within defaults. There are times that I want the default to be the result of a function, and to accomplish this, I'll often set the default to null, then check for the null and carry out the function within. Is there a better solution? Adam -- Nephtali: A simple, flexible, fast, and security-focused PHP framework http://nephtaliproject.com
Re: [PHP] Custom function
Hello Peter, So is func_get_args() the unique way? -- With best regards from Ukraine, Andre Skype: Francophile My blog: http://oire.org/menelion (mostly in Russian) Twitter: http://twitter.com/m_elensule Facebook: http://facebook.com/menelion Original message From: Peter Lind To: Dan Schaefer Date created: , 10:21:20 PM Subject: [PHP] Custom function On 16 February 2011 21:00, Dan Schaefer wrote: > In my code, I set the optional parameter to NULL and check for triple equals > "===" or "!==" to see if the variable has been passed with a value. IMO, > this is the safest way. > > function MyFunction($x, $y, $z=NULL) { > if ($z !== NULL) { > // Do Something > } > } In case you're actually trying to test if a variable was passed or not that doesn't work (as it doesn't detect NULL passed in). Use func_get_args() as that gives you any and all arguments passed to the function, excluding defaults. That said, if you're making use of optional parameters and need to check if anything was passed in, you're almost certainly doing things wrong. Regards Peter -- WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On 16 February 2011 21:00, Dan Schaefer wrote: > In my code, I set the optional parameter to NULL and check for triple equals > "===" or "!==" to see if the variable has been passed with a value. IMO, > this is the safest way. > > function MyFunction($x, $y, $z=NULL) { > if ($z !== NULL) { > // Do Something > } > } In case you're actually trying to test if a variable was passed or not that doesn't work (as it doesn't detect NULL passed in). Use func_get_args() as that gives you any and all arguments passed to the function, excluding defaults. That said, if you're making use of optional parameters and need to check if anything was passed in, you're almost certainly doing things wrong. Regards Peter -- WWW: plphp.dk / plind.dk LinkedIn: plind BeWelcome/Couchsurfing: Fake51 Twitter: kafe15 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
In my code, I set the optional parameter to NULL and check for triple equals "===" or "!==" to see if the variable has been passed with a value. IMO, this is the safest way. function MyFunction($x, $y, $z=NULL) { if ($z !== NULL) { // Do Something } } Dan Schaefer Web Developer/Systems Analyst Performance Administration Corp. On 2-15-2011 6:32 PM, Ron Piggott wrote: Is there a way to make an optional flag in a custom function --- 2 parameters required, 1 optional? Ron The Verse of the Day “Encouragement from God’s Word” http://www.TheVerseOfTheDay.info -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
Hi. On Wednesday 16 Feb 2011 at 00:49 Simon J Welsh wrote: > As $z is converted to a boolean and exists, that works just the same way as > !empty(). --- First I'd like to apologise for handing out bad advice, and second, to thank Simon and Andre for pointing out my mistake. I'll go back to keeping my mouth shut in future :) Cheers guys, Mark -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On 16/02/2011, at 1:21 PM, Mark Kelly wrote: > In this way almost any value in $z will trigger the conditional code, > including 0 or an empty string. The exceptions are FALSE and NULL. If you > explicitly need to react to a NULL value, use is_null() to detect it. http://nz.php.net/boolean#language.types.boolean.casting As $z is converted to a boolean and exists, that works just the same way as !empty(). --- Simon Welsh Admin of http://simon.geek.nz/ Who said Microsoft never created a bug-free program? The blue screen never, ever crashes! http://www.thinkgeek.com/brain/gimme.cgi?wid=81d520e5e -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
Hello Mark, Hm... will if ($z) evaluate to true if $z==0? I thought no... Actually, we can use if (isset($z)) -- With best regards from Ukraine, Andre Skype: Francophile My blog: http://oire.org/menelion (mostly in Russian) Twitter: http://twitter.com/m_elensule Facebook: http://facebook.com/menelion Original message From: Mark Kelly To: php-general@lists.php.net Date created: , 2:21:36 AM Subject: [PHP] Custom function Hi. On Tuesday 15 Feb 2011 at 23:41 Andre Polykanine wrote: > Give it a default (possible empty) value: > > function MyFunction($x, $y, $z="") { > // function goes here > if (!empty($z)) { > // The optional parameter is given > } > } Using an empty string and the empty() function in this way can lead to subtle and hard to find bugs - for example if $z = 0, the code will not be executed. Note the list of things that are considered empty: http://uk.php.net/manual/en/function.empty.php Instead, consider setting the default value for $z to boolean false: function MyFunction ($x, $y, $z = FALSE) { if ($z) { // do stuff with $z } } In this way almost any value in $z will trigger the conditional code, including 0 or an empty string. The exceptions are FALSE and NULL. If you explicitly need to react to a NULL value, use is_null() to detect it. Cheers, Mark -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
On 16 February 2011 00:21, Mark Kelly wrote: > Hi. > > On Tuesday 15 Feb 2011 at 23:41 Andre Polykanine wrote: > >> Give it a default (possible empty) value: >> >> function MyFunction($x, $y, $z="") { >> // function goes here >> if (!empty($z)) { >> // The optional parameter is given >> } >> } > > Using an empty string and the empty() function in this way can lead to subtle > and hard to find bugs - for example if $z = 0, the code will not be executed. > Note the list of things that are considered empty: > > http://uk.php.net/manual/en/function.empty.php > > Instead, consider setting the default value for $z to boolean false: > > function MyFunction ($x, $y, $z = FALSE) { > if ($z) { > // do stuff with $z > } > } > > In this way almost any value in $z will trigger the conditional code, > including 0 or an empty string. The exceptions are FALSE and NULL. If you > explicitly need to react to a NULL value, use is_null() to detect it. > > Cheers, > > Mark You also have the option of variable arguments. function foo($x, $y) // 2 mandatory arguments { print_r(func_get_args()); // Show all arguments. } func_get_args() will return an array of arguments to the function. All of them, not just the declared ones. -- Richard Quadling Twitter : EE : Zend @RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
Hi. On Tuesday 15 Feb 2011 at 23:41 Andre Polykanine wrote: > Give it a default (possible empty) value: > > function MyFunction($x, $y, $z="") { > // function goes here > if (!empty($z)) { > // The optional parameter is given > } > } Using an empty string and the empty() function in this way can lead to subtle and hard to find bugs - for example if $z = 0, the code will not be executed. Note the list of things that are considered empty: http://uk.php.net/manual/en/function.empty.php Instead, consider setting the default value for $z to boolean false: function MyFunction ($x, $y, $z = FALSE) { if ($z) { // do stuff with $z } } In this way almost any value in $z will trigger the conditional code, including 0 or an empty string. The exceptions are FALSE and NULL. If you explicitly need to react to a NULL value, use is_null() to detect it. Cheers, Mark -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function
Hello Ron, Give it a default (possible empty) value: function MyFunction($x, $y, $z="") { // function goes here if (!empty($z)) { // The optional parameter is given } } -- With best regards from Ukraine, Andre Skype: Francophile My blog: http://oire.org/menelion (mostly in Russian) Twitter: http://twitter.com/m_elensule Facebook: http://facebook.com/menelion Original message From: Ron Piggott To: php-general@lists.php.net Date created: , 1:32:16 AM Subject: [PHP] Custom function Is there a way to make an optional flag in a custom function --- 2 parameters required, 1 optional? Ron The Verse of the Day “Encouragement from God’s Word” http://www.TheVerseOfTheDay.info -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Custom function for inserting values into MySQL
> -Original Message- > From: Shawn McKenzie [mailto:nos...@mckenzies.net] > Sent: Thursday, November 05, 2009 6:14 AM > To: Daevid Vincent > Cc: 'Allen McCabe'; 'PHP General' > Subject: Re: [PHP] Custom function for inserting values into MySQL > > Daevid Vincent wrote: > > > > > >> -Original Message- > >> From: Shawn McKenzie [mailto:nos...@mckenzies.net] > >> Sent: Wednesday, November 04, 2009 4:59 PM > >> To: Daevid Vincent > >> Cc: 'Allen McCabe'; 'PHP General' > >> Subject: Re: [PHP] Custom function for inserting values into MySQL > >> > >> Daevid Vincent wrote: > >>>> -Original Message- > >>>> From: Shawn McKenzie [mailto:nos...@mckenzies.net] > >>>> Sent: Wednesday, November 04, 2009 6:20 AM > >>>> To: Allen McCabe; PHP General > >>>> Subject: Re: [PHP] Custom function for inserting values > into MySQL > >>>> > >>>> In your example, I would name my form inputs similar to name > >>>> ="data[user_id]". > >>>> > >>>> Then you just pass the $_POST['data'] array to your function. > >>>> > >>>> -Shawn > >>>> > >>>> Allen McCabe wrote: > >>>>> You raise some good points. I always name my input fields > >> after the > >>>>> entity names ( eg. input type="hidden" name ="user_id" > >> value=" ?php > >>>>> echo $resultRow['user_id'] ? " ). > >>>>> > >>>>> I suppose I am still in the phase of learning efficiency, > >>>> and perhaps > >>>>> trying to 'get out it' by writing functions that I can > >> just call and > >>>>> pass parameters instead of fully learning the core concepts. > >>>>> > >>>>> I just think functions are so damn cool :) > >>>>> > >>>>> > >>>>> I'll echo what the others have said about the > >>>> parameters. For me > >>>>> personally, if I am passing more than three parameters > >>>> (sometimes even > >>>>> three) I rethink my function. I'm not sure what > you envision > >>>>> using this > >>>>> function for, but the approach I use for forms and > >>>> databases is always > >>>>> arrays. I get an array from my forms, I insert that > >>>> array into the > >>>>> database, and of course I fetch arrays out of the > >>>> database. These are > >>>>> all indexed the same with the index as the field name > >>>> of the table so > >>>>> it's easy. > >>>>> > >>>>> > >>>>> -- > >>>>> Thanks! > >>>>> -Shawn > >>>>> http://www.spidean.com > >>>>> > >>>>> > >>>>> > >>> There are pro's and cons to this type of thing. In general > >> that is how I do > >>> it too, but you have to be aware of security and > >> organization. It's not > >>> always smart to expose your DB field names directly so you > >> might want to > >>> obscure them for some critical values. If your passing from > >> one controlled > >>> function/method to another then this isnt an issue so much. > >>> > >>> I also follow the ruby/rails ideal where tables are plural > >> names ("users") > >>> and classes are singular names ("user.class.php"). Tables > >> always have fields > >>> for 'id','created_on','timestamp','enabled'. Except in > >> 'glue table' cases > >>> (1:n or n:m). Classes extend a base class which handles a > >> lot of the minutea > >>> including the magic __get() and __set() routines as well as > >> knowing what > >>> table they should be through introspection (ie. Their own > >> file name). > >>> No need to name your fields as arrays. $_POST is already an > >> array. You've > >>> just added more complexity/dimensions. When you submit your > >> form just pass > >>> $_
RE: [PHP] Custom function for inserting values into MySQL
> -Original Message- > From: Shawn McKenzie [mailto:nos...@mckenzies.net] > Sent: Wednesday, November 04, 2009 6:20 AM > To: Allen McCabe; PHP General > Subject: Re: [PHP] Custom function for inserting values into MySQL > > In your example, I would name my form inputs similar to name > ="data[user_id]". > > Then you just pass the $_POST['data'] array to your function. > > -Shawn > > Allen McCabe wrote: > > You raise some good points. I always name my input fields after the > > entity names ( eg. input type="hidden" name ="user_id" value=" ?php > > echo $resultRow['user_id'] ? " ). > > > > I suppose I am still in the phase of learning efficiency, > and perhaps > > trying to 'get out it' by writing functions that I can just call and > > pass parameters instead of fully learning the core concepts. > > > > I just think functions are so damn cool :) > > > > > > I'll echo what the others have said about the > parameters. For me > > personally, if I am passing more than three parameters > (sometimes even > > three) I rethink my function. I'm not sure what you envision > > using this > > function for, but the approach I use for forms and > databases is always > > arrays. I get an array from my forms, I insert that > array into the > > database, and of course I fetch arrays out of the > database. These are > > all indexed the same with the index as the field name > of the table so > > it's easy. > > > > > > -- > > Thanks! > > -Shawn > > http://www.spidean.com > > > > > > There are pro's and cons to this type of thing. In general that is how I do it too, but you have to be aware of security and organization. It's not always smart to expose your DB field names directly so you might want to obscure them for some critical values. If your passing from one controlled function/method to another then this isnt an issue so much. I also follow the ruby/rails ideal where tables are plural names ("users") and classes are singular names ("user.class.php"). Tables always have fields for 'id','created_on','timestamp','enabled'. Except in 'glue table' cases (1:n or n:m). Classes extend a base class which handles a lot of the minutea including the magic __get() and __set() routines as well as knowing what table they should be through introspection (ie. Their own file name). No need to name your fields as arrays. $_POST is already an array. You've just added more complexity/dimensions. When you submit your form just pass $_POST to your function instead. In the function, is where you should do any normalizing, scrubbing and unsetting (as per good MVC ideology)... In your page form: if ($_POST['submit'] == 'Update') { $result = process_data($_POST); } Then in some include file somewhere (here is a simplified example of course): function process_data($data) { //perhaps you don't care about the submit button unset($data['submit']); //maybe you don't want everyone to know your DB schema //so you re-map from form element names to DB fields... $data['user_id'] = $data['uid']; unset($data['uid']); //strip white space off foreach ($data as $k => $v) $data[$k] = trim($v); //do validity checking of each important data item if (intval($data['user_id']) < 1) return false; //any other pre-processing //do interesting stuff here with scrubbed $data array now sql_query('UPDATE mytable SET .. WHERE user_id = '.$data['user_id'].' LIMIT 1'); //of course, I would use a routine that builds the update / insert statements from //the array key/value pairs -- see previous attached example base.class.php in this thread. } http://daevid.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function for inserting values into MySQL
Shawn McKenzie wrote: Allen McCabe wrote: Do you see any major hangups or screwups on first glance? And is my fear of trying this out on my database unfounded? Does this even seem that useful? in all honesty.. loads of screwups - don't try it out on your database & ultimately if it isn't re-usable then it isn't useful (and it's isn't re-usable unless every single table you have is the same.. which they aren't) to be a bit more constructive though.. this is a road most developers have been down, and well known solutions already exist. You've got two choices.. 1] continue down this route and learn as you go (but for god sake get a test database) - recommended if you really want to learn not just PHP but programming in general; once you understand it all you can go looking at design patterns, common solutions and how other people do it and have enough knowledge to make informed decisions. 2] just use what's made and don't think too much about it, you'll be productive and can throw in support/help requests whenever it goes wrong, works for some people.. to do this get a decent framework and read it's manual (or use pdo, or an ORM for PHP or something) all depends on what you want, how much time you have, and where you want to end up. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function for inserting values into MySQL
In your example, I would name my form inputs similar to name ="data[user_id]". Then you just pass the $_POST['data'] array to your function. -Shawn Allen McCabe wrote: > You raise some good points. I always name my input fields after the > entity names ( eg. input type="hidden" name ="user_id" value=" ?php > echo $resultRow['user_id'] ? " ). > > I suppose I am still in the phase of learning efficiency, and perhaps > trying to 'get out it' by writing functions that I can just call and > pass parameters instead of fully learning the core concepts. > > I just think functions are so damn cool :) > > > I'll echo what the others have said about the parameters. For me > personally, if I am passing more than three parameters (sometimes even > three) I rethink my function. I'm not sure what you envision > using this > function for, but the approach I use for forms and databases is always > arrays. I get an array from my forms, I insert that array into the > database, and of course I fetch arrays out of the database. These are > all indexed the same with the index as the field name of the table so > it's easy. > > > -- > Thanks! > -Shawn > http://www.spidean.com > > > -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function for inserting values into MySQL
Allen McCabe wrote: > Okay friends, I have been wondering about writing a simple function that > will help me with my MySQL inserting. Not because I need to save time and > space, but because I wanted to. > > I wrote a function for inserting 10 values (I have not been able to come up > with an idea how to make the number of values I'm inserting variable, so I'm > sticking with ten). > > This function takes 22 parameters: #1 is the table name, #2-21 are the row > names and the values, and #22 is the "integar string". > > The first 21 parameters are self-explanatory, the 22nd is a string of values > that need to be inserted as an integar, basically, not adding single quotes > around the value. Eg. $value2 = 5, not $value2 = '5'. > > I am very hesitant to try this one out on my database, I've got tables of > important information and don't want to, I don't know, inadvertantly throw a > wrench into the works, AND I want to open up a dialoug about custom PHP > functions for working with MySQL, for the fun of it! > > Here is my 10 value function for inserting data into a MySQL database table. > > function insertinto10($table, $field1, $value1, $field2, $value2, $field3, > $value3, $field4, $value4, $field5, $value5, $field6, $value6, $field7, > $value7, $field8, $value8, $field9, $value9, $field10, $value10, $int = > NULL) > { > if (isset($int)) > { > $sPattern = '/\s*/m'; > $sReplace = ''; > $int = preg_replace($sPattern, $sReplace, $int); > $pieces = explode(",", $int); // $pieces[0], $pieces[1] - each equal to > value numbers that are integars > $length = count($pieces); > // call custom function to create associative array eg. $newarray[2] = 1, > $newarray[4] = 1, $newarray[5] = 1 . . . > $integarArray = strtoarray($length, $int); > } > > $valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6, > $value7, $value8, $value9, $value10); > > foreach ($valuesArray as $key => $value) > { > if (isset($integarArray[$key]) && $integarArray[$key] == 1) > { >// INTEGAR VALUE >$valuesArray[$key] = mysql_real_escape_string(stripslashes($value)); > } > else > { >// STRING VALUE >$cleanValue = mysql_real_escape_string(stripslashes($value)); >$valuesArray[$key] = "'{$cleanValue}'"; > } > } > > $result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, `{$field2}`, > `{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray[2]}, > {$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]}, {$valuesArray[6]}, > {$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]}, > {$valuesArray[10]})"); > return $result; > } > > > You may find copying/pasting into your favorite code-editor helps make it > more readable. > > Do you see any major hangups or screwups on first glance? And is my fear of > trying this out on my database unfounded? Does this even seem that useful? > I'll echo what the others have said about the parameters. For me personally, if I am passing more than three parameters (sometimes even three) I rethink my function. I'm not sure what you envision using this function for, but the approach I use for forms and databases is always arrays. I get an array from my forms, I insert that array into the database, and of course I fetch arrays out of the database. These are all indexed the same with the index as the field name of the table so it's easy. -- Thanks! -Shawn http://www.spidean.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Custom function for inserting values into MySQL
I would take a look at some of the frameworks like codeignter to see how they do things. But like Davied mentioned a simpler way to handle the passing into the function would be Function save($table, $data) Where data is an array of key value pairs which takes your 22 parameters down to 2. The array could look like $data = array('id' => 1, 'name' => 'bob' ...) Bastien Sent from my iPod On Nov 2, 2009, at 8:32 PM, Allen McCabe wrote: Okay friends, I have been wondering about writing a simple function that will help me with my MySQL inserting. Not because I need to save time and space, but because I wanted to. I wrote a function for inserting 10 values (I have not been able to come up with an idea how to make the number of values I'm inserting variable, so I'm sticking with ten). This function takes 22 parameters: #1 is the table name, #2-21 are the row names and the values, and #22 is the "integar string". The first 21 parameters are self-explanatory, the 22nd is a string of values that need to be inserted as an integar, basically, not adding single quotes around the value. Eg. $value2 = 5, not $value2 = '5'. I am very hesitant to try this one out on my database, I've got tables of important information and don't want to, I don't know, inadvertantly throw a wrench into the works, AND I want to open up a dialoug about custom PHP functions for working with MySQL, for the fun of it! Here is my 10 value function for inserting data into a MySQL database table. function insertinto10($table, $field1, $value1, $field2, $value2, $field3, $value3, $field4, $value4, $field5, $value5, $field6, $value6, $field7, $value7, $field8, $value8, $field9, $value9, $field10, $value10, $int = NULL) { if (isset($int)) { $sPattern = '/\s*/m'; $sReplace = ''; $int = preg_replace($sPattern, $sReplace, $int); $pieces = explode(",", $int); // $pieces[0], $pieces[1] - each equal to value numbers that are integars $length = count($pieces); // call custom function to create associative array eg. $newarray [2] = 1, $newarray[4] = 1, $newarray[5] = 1 . . . $integarArray = strtoarray($length, $int); } $valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8, $value9, $value10); foreach ($valuesArray as $key => $value) { if (isset($integarArray[$key]) && $integarArray[$key] == 1) { // INTEGAR VALUE $valuesArray[$key] = mysql_real_escape_string(stripslashes($value)); } else { // STRING VALUE $cleanValue = mysql_real_escape_string(stripslashes($value)); $valuesArray[$key] = "'{$cleanValue}'"; } } $result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, ` {$field2}`, `{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray [2]}, {$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]}, {$valuesArray[6]}, {$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]}, {$valuesArray[10]})"); return $result; } You may find copying/pasting into your favorite code-editor helps make it more readable. Do you see any major hangups or screwups on first glance? And is my fear of trying this out on my database unfounded? Does this even seem that useful? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] Custom function for inserting values into MySQL
> Do you see any major hangups or screwups on first glance? Yes. There is so much wrong with this I don't even know where to begin... > This function takes 22 parameters: #1 is the table name, > #2-21 are the row > names and the values, and #22 is the "integar string". Dude. Seriously? TWENTY TWO parameters. Use this for variable number of parameters: http://us2.php.net/manual/en/function.func-get-args.php Or how about using an array/hash as your second parameter with the field=>value pairs. Which is astonishing since you have the concept of an array with this hack: $valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8, $value9, $value10); foreach ($valuesArray as $key => $value) The word you're looking for is "INTEGER" not "INTEGAR". > And is my fear of trying this out on my database unfounded? No. Don't use it. > Does this even seem that useful? No. Your function is so very limited in scope and use. You're better off writing a wrapper around the SQL functions and submit direct SQL as the string parameter to the function. See attached db.inc.php. You would also be better served using a method/function such as my base.class.php::sync() which will insert or update a row. The attached code is about a year old or so and has since been refined further, but this should give you a good place to start. http://daevid.com _stamp; } function set_stamp($stamp) { $this->_stamp = $stamp; } /** * Constructor * * @access public * @return object * @parammixed $id the ID of the object to load from the database (this could be a string or usually an integer) * @author Daevid Vincent [dae...@] * @version 1.2 * @date 09/20/07 */ function __construct($id = NULL) { if ($_SESSION['companydb']) $this->db = $_SESSION['companydb']; //this follows the Ruby way for ease of porting/sharring, please stick with the convention. if (is_null($this->table) && preg_match( '/y$/', $this->getClassname() ) > 0) $this->table = strtolower(preg_replace( '/y$/', 'ies', $this->getClassName() )); elseif( is_null( $this->table ) ) $this->table = strtolower($this->getClassName()).'s'; if (!is_null($id)) $this->load($id); } /** * generate a key/value pair from the class' variables. * * @access public * @return array * @author Daevid Vincent [dae...@] * @version 1.0 * @date 08/13/07 */ public function get_array() { $row = array(); foreach($this as $key => $value) $row[$key] = $value; $row['enabled'] = ($this->enabled) ? 1 : 0; return $row; } /** * set the class' values based upon a SQL query. * * Note: Usually this is called by an extension class, * which in turn calls the parent::load_from_sql() * which generates an array and then calls load_from_array() * * @access public * @return array or false * @paramint $id ID of the object to load * @author Daevid Vincent [dae...@] * @version 1.0 * @date 08/20/07 * @see load_from_array() */ function load($id = null) { if (intval($id) < 1) return false; $sql = "SELECT * FROM".$this->db.".".$this->table." WHERE id = '".SQL_ESCAPE($id)."'"; $result = $this->load_from_sql($sql); //LIMIT 1 is appended by base class if ($result) return $result; else throw new Exception(translate('%1$s threw an exception trying to load object #%2$s', __CLASS__, $id)); } /** * set the class' values based upon a SQL table which is converted to an array of column(key) value pairs and passed to load_from_array(). * * @access public * @return array or false * @paramstring $sql SQL schema columns to use as array keys * @author Daevid Vincent [dae...@] * @version 1.0 * @date 08/13/07 * @see load_from_array() */ public function load_from_sql($sql = null) { if (is_null($sql)) return false; $result = SQL_QUERY($sql." LIMIT 1");
[PHP] Custom function for inserting values into MySQL
Okay friends, I have been wondering about writing a simple function that will help me with my MySQL inserting. Not because I need to save time and space, but because I wanted to. I wrote a function for inserting 10 values (I have not been able to come up with an idea how to make the number of values I'm inserting variable, so I'm sticking with ten). This function takes 22 parameters: #1 is the table name, #2-21 are the row names and the values, and #22 is the "integar string". The first 21 parameters are self-explanatory, the 22nd is a string of values that need to be inserted as an integar, basically, not adding single quotes around the value. Eg. $value2 = 5, not $value2 = '5'. I am very hesitant to try this one out on my database, I've got tables of important information and don't want to, I don't know, inadvertantly throw a wrench into the works, AND I want to open up a dialoug about custom PHP functions for working with MySQL, for the fun of it! Here is my 10 value function for inserting data into a MySQL database table. function insertinto10($table, $field1, $value1, $field2, $value2, $field3, $value3, $field4, $value4, $field5, $value5, $field6, $value6, $field7, $value7, $field8, $value8, $field9, $value9, $field10, $value10, $int = NULL) { if (isset($int)) { $sPattern = '/\s*/m'; $sReplace = ''; $int = preg_replace($sPattern, $sReplace, $int); $pieces = explode(",", $int); // $pieces[0], $pieces[1] - each equal to value numbers that are integars $length = count($pieces); // call custom function to create associative array eg. $newarray[2] = 1, $newarray[4] = 1, $newarray[5] = 1 . . . $integarArray = strtoarray($length, $int); } $valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8, $value9, $value10); foreach ($valuesArray as $key => $value) { if (isset($integarArray[$key]) && $integarArray[$key] == 1) { // INTEGAR VALUE $valuesArray[$key] = mysql_real_escape_string(stripslashes($value)); } else { // STRING VALUE $cleanValue = mysql_real_escape_string(stripslashes($value)); $valuesArray[$key] = "'{$cleanValue}'"; } } $result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, `{$field2}`, `{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray[2]}, {$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]}, {$valuesArray[6]}, {$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]}, {$valuesArray[10]})"); return $result; } You may find copying/pasting into your favorite code-editor helps make it more readable. Do you see any major hangups or screwups on first glance? And is my fear of trying this out on my database unfounded? Does this even seem that useful?