Jump to content

Recommended Posts

This is a general question about what is the proper way to use mySQL queries. 

 

I generally make all PHP functions very short because I was trained to code that way.  So, I might have a function that takes two dates and returns the difference in days or something of that nature.  The functions do one thing for the most part, and that is it.

 

However, when it comes to mySQL, I am not sure I am doing the right thing.  For instance, I might have a function called getProductTitle that returns the title, getProductImage that gets the image URL, etc.  Each of these makes a separate query, but they are short and fast.  This is especially useful if what I return might not be exactly what is in the database but tweak it before returning to conform to something else. 

 

Alternatively, there would be less overhead if I actually had a function called getProductData that got everything I might possibly need.   

 

For those of you who write short functions, how do you handle this when it comes to mySQL queries being involved?  Is it wrong to make a lot of short queries when you could get away with on large one?  Or is making a lot of queries only wrong if you return large datasets that you do not use.

 

Link to comment
https://forums.phpfreaks.com/topic/62625-php-functions-and-mysql-queries/
Share on other sites

I prefer one query that returns everything I need vs. many little queries that get the same information.  To some extent I also prefer to pull the data from MySQL in the form I'll need it rather than play with it in PHP -- the code is cleaner.  For instance, rather than get a raw DATETIME value then format it in PHP using strtotime and date, I'd just use DATE_FORMAT in MySQL.

 

In your example, I think getting all the product information in one query would be much less expensive than getting pieces of information individually.  Even if you don't use all the data, you avoid the query overhead and annoying the SQL server multiple times.

 

$0.02

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.