加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 创建自定义MySQL函数?

发布时间:2020-12-13 13:35:44 所属栏目:PHP教程 来源:网络整理
导读:我刚开始使用 MySQL和 PHP,我想知道是否可以创建自定义函数.这段代码片段应该说明我正在尝试做的事情. // a somewhat complicated formula not suitable to embed into the queryfunction Distance($latA,$lonA,$latB,$lonB){ // earth's radius $radius = 3
我刚开始使用 MySQL和 PHP,我想知道是否可以创建自定义函数.这段代码片段应该说明我正在尝试做的事情.
// a somewhat complicated formula not suitable to embed into the query
function Distance($latA,$lonA,$latB,$lonB)
{
  // earth's radius
  $radius = 3956;

  $latA = deg2rad($latA);
  $lonA = deg2rad($lonA);
  $latB = deg2rad($latB);
  $lonB = deg2rad($lonB);

  // calculate deltas
  $deltaLat = $latB - $latA;
  $deltaLon = $lonB - $lonA;

  // calculate Great Circle distance
  $result = pow(sin($deltaLatitude / 2.0),2) + (cos($latA) * cos($latB) * pow(sin($deltaLon / 2.0),2));
  $distance = $radius * 2 * atan2(sqrt($result),sqrt(1 - $result));

  return $distance;
}

// how can I call Distance() in my query?
$query = "SELECT lat,lon FROM zipcodes WHERE Distance(lat,lon,0) < 20";
mysql_query($query);

在此先感谢您的帮助!

您在应用程序中声明此MySQL函数,它将保留在数据库中,直到重新启动数据库服务器.
mysql_query("CREATE FUNCTION Distance(LAT_A INT,LON_A INT,LAT_B INT,LON_B INT,)
RETURNS INT
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE radius,deltaLat,deltaLon,result,distance BIGINT;
SET radius=3956;
SET deltaLat=LAT_B-LAT_A;
SET deltaLon=LON_B-LON_A;
SET result=POW(SIN(deltaLat/2),2) + (COS(LAT_A) * COS(LAT_B) * POW(SIN(deltaLon/2.0),2));
SET distance=radius * 2 * ATAN2(SQRT(result),SQRT(1 - result));
RETURN distance;
END");

这使用MySQL的mathematical functions.将此处理卸载到数据库是快速有效的(数据不必通过网络传输,并且您只返回所需的结果).

一旦你宣布了这个,就可以这样使用它:

$query = "SELECT lat,0) < 20";
mysql_query($query);

但是,如果数据库重新启动,则先前声明的任何函数或过程都将丢失.可以在应用程序级别正常处理MySQL错误1305(函数functionName不存在).

在您的数据库错误处理程序

switch (mysql_errno()):
    case 1305:
        if (false === $database->_declareStoredProcedureFlag) {
             if ($c = preg_match_all("/FUNCTION [a-zA-Z0-9]+." .
                 "([a-zA-Z0-9_]*) does not exist/is",mysql_error(),$matches)
             ) {
                 $storedFunctionName = $matches[1][0];
                 $database->_declareStoredProcedureFlag = true;
                 if (true === $database->declareStoredFunction($storedFunctionName)) {
                     $result = mysql_query($query);
                 }
             }
         }
         break;
    ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读