To register for an Internet.com membership to receive newsletters and white papers, use the Register button ABOVE.
To participate in the message forums BELOW, click here
PHPBuilder.com  
 

 

Go Back   PHPBuilder.com > PHP Help > Coding

Coding Help with PHP coding

Reply
 
Thread Tools Search this Thread Rate Thread Display Modes
Old 03-19-2010, 04:43 PM   #1
gwerner
Member
 
Join Date: Mar 2010
Posts: 39
resolved [RESOLVED] Organizing MySQL queries

I've been in the process of going back through an existing site I've developed. I'm trying to better organize and streamline the code I initially put together. I've been pulling apart my code and building towards a more modular approach.

Originally, I had included all of my queries inline along with my html. Upon further reading it seems like this might not be the best practice. I'm looking for tips and best practices when dealing with organization of mySQL queries.

My first thoughts would be to put the most common queries inside functions and access them through a require_once. It seems weird though to call a function grabData() within the html. Am I thinking about this correctly?

Most of my pages only need one to two queries, while others might have up to seven plus. The higher numbered queries would be on a dashboard pages where a lot of data is being displayed.

Another example would be a states database that is accessed quite often through various form pages. It seems like I should build the query once and then call from a function?

Any insight or guidance is appreciated. Thanks.
gwerner is offline   Reply With Quote
Old 03-19-2010, 05:48 PM   #2
ixalmida
Deviloper
 
Join Date: Jul 2008
Location: Chicago-area
Posts: 470
I think the gurus will tell you that your best bet is to build functions or classes that will do all the validation and scrubbing. Then you only need to pass fields, values, and possibly extra conditions to the function/class.

I'd even raise you one on the states thing. I have built functions to retrieve states and display them in a drop-down box. I use the stateSelectBox() function in many of my forms.

However...encapsulating queries this way may not always be more efficient, and in many cases it obscures your code from yourself. I tend to like to do things as simply as possible. If that means building a function or class for queries that get used frequently, then I'll do that. But sometimes it is a waste of my time because the query is unique to the page. IMO you should consider it on a case-by-case basis.

I've actually seen people build functions/classes for all queries in general, but in the end they have to pass almost the entire query to the function and reassemble it on the other side. Where's the efficiency in that?
ixalmida is offline   Reply With Quote
Old 03-20-2010, 01:13 AM   #3
NogDog
High Energy Magic Dept.
 
NogDog's Avatar
 
Join Date: Aug 2006
Location: Ankh-Morpork
Posts: 12,638
For the state select box example, it might be two separate functions: one to retrieve the states from the DB as an array, and a generic function to display a select element from an array.

db_functions.php:
PHP Code:
<?php

/**
* Get states from DB as array
* @return array
*/
function getStateArray()
{
   
$sql = "SELECT `abbrev`, `name` FROM `state` ORDER BY `name`";
   
$result = mysql_query($sql);
   if(!
$result)
   {
      
error_log(mysql_error()."\n$sql");
      return
false;
   }
   
$arr = array();
   while(
$row = mysql_fetch_assoc($result))
   {
      
$arr[$row['abbrev']] = $row['name'];
   }
   return
$arr;
}
html_functions.php:
PHP Code:
<?php
/**
* get <select> HTML for an array of data
* @return string
* @param string $name Select element name & ID
* @param array $data  Key: option value, Value: displayed value
* @param string $class Select element class (optional)
*/
function selectFromArray($name, $data, $class=null)
{
   
$html = sprintf(
      
"<select name='%s' id='%s'%s>\n",
      
htmlspecialchars($name, ENT_QUOTES),
      
htmlspecialchars($name, ENT_QUOTES),
      (empty(
$class)) ? '' : " class='".htmlspecialchars($class,ENT_QUOTES)."'"
   
);
   foreach(
$data as $key => $value)
   {
      
$html .= sprintf(
         
"<option value='%s'>%s</option>\n",
         
htmlspecialchars($key, ENT_QUOTES),
         
htmlspecialchars($value, ENT_QUOTES)
      );
      
$html .= "</select>\n";
   }
   return
$html;
}
index.php:
PHP Code:
<?php
require_once 'db_functions.php';
require_once
'html_functions.php';
?>
<form action='' method='post'>
<fieldset>
<legend>Test</legend>
<label for='state'>Select state:</label>
<?php echo selectFromArray('state', getStateArray(), 'class_foo'); ?>
</fieldset>
</form>
If you are reasonably comfortable with the basics of object-oriented PHP, the next step might be to organize related functions into classes.
__________________
"That's what the gods are! An answer that will do! Because there's food to be caught and babies to be born and life to be lived and so there is not time for big, complicated, and worrying answers! Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." -- from Nation, by Terry Pratchett

Email me

Last edited by NogDog; 03-22-2010 at 05:10 PM. Reason: fixed return value in first function
NogDog is offline   Reply With Quote
Old 03-20-2010, 11:44 AM   #4
ixalmida
Deviloper
 
Join Date: Jul 2008
Location: Chicago-area
Posts: 470
Nog --> great post!
ixalmida is offline   Reply With Quote
Old 03-22-2010, 09:41 AM   #5
gwerner
Member
 
Join Date: Mar 2010
Posts: 39
Thanks for the help. I'm doing something similar to what NogDog posted. My code on index.php is not nearly as clean though. Have to go back and retool it a bit.

This helps out quite a bit. Still learning and trying to wrap my head around all of this. Thanks guys.
gwerner is offline   Reply With Quote
Old 03-22-2010, 10:16 AM   #6
gwerner
Member
 
Join Date: Mar 2010
Posts: 39
Actually another quick question. After looking through NogDog's suggestion I went back and retooled my code a bit now have a cleaner bit of code.

I'm using this in a form and I like to do error checking to help the user if they forget a field or input incorrect data. For dropdowns I check to see if the field is set to -1, which is the default selction of "Choose below..." Anything else should be a state selection. For NogDog's example I would normally add the code below. Is this the right approach?

PHP Code:
<?php
if (isset($_POST['state'])) {
    
$selected = $_POST['state'];
}
else {
    
$selected = '-1';
}
echo
dropdown('state', getStates(), $selected);
?>
gwerner is offline   Reply With Quote
Old 03-22-2010, 05:19 PM   #7
NogDog
High Energy Magic Dept.
 
NogDog's Avatar
 
Join Date: Aug 2006
Location: Ankh-Morpork
Posts: 12,638
Quote:
Originally Posted by gwerner View Post
Actually another quick question. After looking through NogDog's suggestion I went back and retooled my code a bit now have a cleaner bit of code.

I'm using this in a form and I like to do error checking to help the user if they forget a field or input incorrect data. For dropdowns I check to see if the field is set to -1, which is the default selction of "Choose below..." Anything else should be a state selection. For NogDog's example I would normally add the code below. Is this the right approach?

PHP Code:
<?php
if (isset($_POST['state'])) {
    
$selected = $_POST['state'];
}
else {
    
$selected = '-1';
}
echo
dropdown('state', getStates(), $selected);
?>
There is nothing wrong with that, but if you're one of those people who likes terse code, you could do:
PHP Code:
<?php
echo dropdown('state', getStates(), isset($_POST['state']) ? $_POST['state'] : -1);
?>
Functionally it gains you nothing. In readability it probably loses something. In performance it might save a microsecond or two, typing-wise it saves a few seconds.
__________________
"That's what the gods are! An answer that will do! Because there's food to be caught and babies to be born and life to be lived and so there is not time for big, complicated, and worrying answers! Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." -- from Nation, by Terry Pratchett

Email me
NogDog is offline   Reply With Quote
Old 03-23-2010, 05:08 PM   #8
gwerner
Member
 
Join Date: Mar 2010
Posts: 39
I do like me some terse code. I've been noticing this style more and more and would like to learn how to write in this manner. Do you have a good resource on how to write code this way?

Thanks again for all the help.
gwerner is offline   Reply With Quote
Old 03-23-2010, 05:14 PM   #9
bradgrafelman
Pna lbh ernq guvf?
 
Join Date: Jul 2004
Location: Around 0:0:0:0:0:0:0:1
Posts: 14,488
Quote:
Originally Posted by gwerner View Post
Do you have a good resource on how to write code this way?
Not sure what you mean by "this way." If you mean taking an if/else statement and shortening it to one line, then you're looking at using the ternary operator.
__________________
***If your problem has been solved, PLEASE click the RESOLVED LINK under "Thread Tools"***

"Well Bones, do the new medical facilities meet with your approval?" -- Kirk
"They do not. It's like working in a damn computer center" -- McCoy (Star Trek: TMP)

Useful links: Debugging 101 || NJOE || (Sig image) || Rolla Engineered Solutions, LLC
bradgrafelman is offline   Reply With Quote
Old 03-23-2010, 07:19 PM   #10
gwerner
Member
 
Join Date: Mar 2010
Posts: 39
Yes, that is what I meant. Sorry. I'm just not familiar with how that looks compared to the traditional if/else. And, I didn't know if this was the only instance you can write the code in this manner or if there were others as well. You answered my question, and thanks for the link. I keep learning new stuff every day.
gwerner is offline   Reply With Quote
Reply

Bookmarks

Tags
mysql, organize, queries, query


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Forum Jump


All times are GMT -4. The time now is 02:58 AM.








Acceptable Use Policy

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.