I need to select some values from a table column which has a datatype of "longtext" where another column has a specific value and add those values up. I need to store the sum as a variable which I will a.) echo on a webpage, and b.) use the value in a calculation later in the page.
This works to find all of the values which I need to add up:
$query = "SELECT meta_value
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'
ORDER BY CAST(`meta_value` AS UNSIGNED) DESC";
and I can display the results with:
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['meta_value']. "<br>";
}
From my searching, I think I am close with my query, but my page fails to load when I try to echo the results. Here is what doesn't work:
$query = "SELECT CAST(SUM('meta_value') as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM('meta_value')]. "<br>";
}
As you may have guessed, this is a Wordpress database table, and I cannot change the datatype. As always, your help is appreciated!
EDIT - Trying Gordon Linoff's suggestion below, I have removed the single quotes around meta_value. It still doesn't work, but thank you for the suggestion:
$query = "SELECT CAST(SUM(meta_value) as UNSIGNED)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row[SUM(meta_value)]. "<br>";
}
SOLVED:
Thank you to Gordon Linoff for pointing out my typographical error. I ended up making a sample table and hammering this out on my own. Indeed, the single quotes in my query were not needed. However, where I was echoing the results, I needed the single quotes, but they were in the wrong place. Note $row['SUM(meta_value)']
instead of $row[SUM('meta_value')]
.
Additionally, I did not need to use CAST (which didn't work), because MYSQL will by default treat values as mathematical values if the query uses math.
$query = "SELECT meta_key, SUM(meta_value)
FROM wp_postmeta
WHERE meta_key = '_crowdfundingtotalprice'";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo $row['SUM(meta_value)'] ."<br>";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.