从SQL数组中添加字符串长度

时间:2012-01-12 21:27:16

标签: php mysql html

我正在尝试从插入的网址中添加字符长度。我已从数组中的数据库中获取所有选定的URL,并尝试在foreach函数中添加它们。

function countLen($email) {

    $countLen = mysql_query("SELECT url FROM urls WHERE user='$email'");
    $resultLen = mysql_result($countLen, 0);

    foreach($resultLen as &$string) {


        $length = strlen($string);
        $totallen = ($totallen + $length);

        return $totallen;




    }





}

3 个答案:

答案 0 :(得分:6)

你可以在SQL中完成所有求和:

function countLen($email)
{
    $res = mysql_query("SELECT SUM(LENGTH(url)) as 'sum' FROM urls WHERE user='$email'");
    return current(mysql_fetch_array($res));
}

答案 1 :(得分:2)

尝试:

$total = 0;

$res = mysql_query("SELECT url FROM urls WHERE user='$email'");
while( $row = mysql_fetch_assoc($res) )
{
  $total += strlen( $row['url'] );
}

答案 2 :(得分:1)

返回应该在循环之外..比如

function countLen($email) {

  $countLen = mysql_query("SELECT url FROM urls WHERE user='$email'");
  $resultLen = mysql_result($countLen, 0);
  $totallen = 0;
  foreach($resultLen as &$string) {
    $length = strlen($string);
    $totallen = ($length + $totallen);
  }
  return $totallen;
}