RE: [PHP-DB] Undefined variables in update query
| From: | VanderHart, Robert | Date: | Wed, 27 Mar 2013 12:34:55 +0000 |
| Subject: | RE: [PHP-DB] Undefined variables in update query | ||
| References: | 1 2 3 4 5 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-48714@lists.php.net to get a copy of this message | ||
Many thanks for this great advice! Definitely worth keeping and putting into practice! Any way to
write cleaner and more concise code is always worth learning.
Best regards,
Robert
--
Robert J. Vander Hart
Electronic Resources Librarian | Lamar Soutter Library
University of Massachusetts Medical School 01655
508-856-3290 | Robert.VanderHart@umassmed.edu
http://library.umassmed.edu | LinkedIn: http://www.linkedin.com/in/robertvanderhart
-----Original Message-----
From: tamouse mailing lists [mailto:tamouse.lists@gmail.com]
Sent: Tuesday, March 26, 2013 6:57 PM
To: VanderHart, Robert
Cc: php-db@lists.php.net
Subject: Re: [PHP-DB] Undefined variables in update query
On Tue, Mar 26, 2013 at 10:57 AM, VanderHart, Robert <Robert.VanderHart@umassmed.edu> wrote:
> I appreciate the replies I've received already; thanks! Sorry for not catching my simple
> errors before sending out that message.
No worries, no one I have met yet begins life knowing this stuff!
If you don't mind, Robert, I'd like to introduce you to a couple of concepts that might
make your way easier:
1) Don't Repeat Yourself, aka DRY -- in writing code, it sometimes seems easier to just cut and
paste something over and over again with a couple of minor tweaks. However, if you find you have to
change something structurally (like that form!), having the change in one place is so much simpler.
2) Think in functions, procedures, and modules. It's sometimes very easy when starting out to
just write everything in one straight, linear flow. Going along with #1, using functions to handle
the reduced repetition should help a lot.
If I can give a simple example, you have a whole swath of lines dealing with pulling things out of
$_POST that look almost exactly the same, save for the key.
$fields =
['authorid','lname','fname','mname','email','institution',
'department','comments','sent_email','suffix']
foreach ($fields as $field) {
if (isset($_POST[$field])) $$field =
mysqli_real_escape_string($link, $_POST[$field]); }
If you notice the '$$field' thing in the middle there, it's a Variable Variable,
which is described in:
http://www.php.net/manual/en/language.variables.variable.php
It might look advanced, but most every language has some form of indirection like that. Makes the
above operation really nice and short. You said you've been around the block a couple of times
in other languages and scripts (and if your photo is accurate, we're probably of an age!) so I
hope you'll take this as just trying to help a person get a leg up.