2

I have made request to SQL:

SELECT meta_value,  COUNT(*)  from wp_postmeta; 

and have in respond an array:

array (size=102)
  0 => 
    object(stdClass)[24]
      public 'meta_value' => string '37' (length=2)
      public 'COUNT(*)' => string '147' (length=3)
  1 => 
    object(stdClass)[23]
      public 'meta_value' => string '32' (length=2)
      public 'COUNT(*)' => string '143' (length=3)

I take "meta_value" without any troubles with php code:

$result->meta_value;

But how take values of public 'COUNT(*)' => string '143' (length=3)? I have tried different syntaxis and some errors only.

I need values: 147,143...

3
  • 5
    SELECT meta_value, COUNT(*) as xy from wp_postmeta; does that do the trick for you? Commented Jan 8, 2015 at 15:53
  • Nice, wrote a answer (Also if you want to read up on that it's called an alias name! You can do that with everything you select (e.g. SELECT name as xy from table where id = 1)) Commented Jan 8, 2015 at 15:58
  • Yes. thank you. I have read SQL for Dummiers before and have not remembered this thing. It is really simple. Thank you once again. Commented Jan 8, 2015 at 16:00

5 Answers 5

8

Use AS to create an alias

SELECT meta_value,  COUNT(*) As count  from wp_postmeta; 

then use count

Sign up to request clarification or add additional context in comments.

1 Comment

It is called an alias name
5

Use the alias AS in your SQL to give the MySQL function a desired name.

SELECT meta_value,  COUNT(*) as counter from wp_postmeta; 

Comments

2
SELECT meta_value,  COUNT(*) AS total  from wp_postmeta; 

This is good solution.

But you can do it alternative way(if you want to keep your query as it is)

$total="count(*)";//keep it inside a variable;
//now you can use it

$result->$total;

$result->count(*) will produce syntax error but $result->$total; will work

Comments

1

You can use a alias name with AS like this:

SELECT meta_value, COUNT(*) as xy from wp_postmeta;

Comments

0
SELECT meta_value,COUNT(*) AS total_count FROM wp_postmeta

echo $result->total_count;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.