Jump to content

transform select query into select count query


Goat

Recommended Posts

Hello guys

 

I want to turn some random select query into query that counts how many rows that query returns. So ideally, I would like to make a php function where you send some query as string and it returns select query. It doesn't have to cover ALL situations, but it should be as universal as possible.

 

Something like this:

echo convert_to_count("SELECT * FROM users WHERE age='23'"); /// outputs: SELECT COUNT(*) FROM users WHERE age='23'

 

I am not sure if it would always work to simply replace SELECT .... FROM with SELECT COUNT(*) . What do you think?

 

 

regards,

Goat

Link to comment
Share on other sites

Why don't you just use php's mysql_num_rows on the result of the query?

$num_rows = mysql_num_rows($result)

 

Maybe that's what I am going to do eventually, but that's not very efficient for what I am trying to do. My real goal is to create function that automatically creates html table, complete with <prev 1, 2, 3, 4, 5 next> links, using only standard sql query.

 

Here's how it might work:

/// generate_table (row labels, query, starting point, limit)
generate_table("id, name, age", "SELECT * FROM users", 50, 10); 

 

the function would then create and execute two queries 

1. "SELECT * FROM users LIMIT 50, 10" - to populate html table

2. "SELECT COUNT (*) FROM users" - to figure out how many users we have to generate <prev 1 2 3 next> links

 

I could, of course just execute  "SELECT * FROM users" query, put everything to array, and then use php array functions to count it and extract parts that I need, but that would strain database too much if there are 100's users and I only need first 10.

 

thanks for replaying, thought

 

regards,

Goat

Link to comment
Share on other sites

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.