Create mysql function php

Как создать функцию на сервере базы данных MySQL

В сегодняшней статье мы рассмотрим как создать функцию на сервере MySQL. Итак, что же такое функция.

В программировании функция — это часть бизнес-процесса или вычисления, инкапсулированная под именем функции. Когда вам нужно запустить процесс или расчет, вы можете сделать это, просто вызвав имя функции.

Вот пример функции в JavaScript:

function hello() console.log(«Hello World»)
>

В MySQL вы можете создать хранимую функцию, используя синтаксис CREATE FUNCTION. Основной синтаксис для создания функции в MySQL следующий:

CREATE FUNCTION [function name] (
[parameter name] [parameter type],
[parameter name] [parameter type],
.
)

RETURNS [data type] [DETERMINISTIC]
RETURN [expression]

Во-первых, вам нужно указать имя функции в [function name]. Далее вам нужно объявить любые параметры, которые вы должны получить для функции. Вы можете объявить столько параметров, сколько вам нужно, но лучше всего, чтобы одна функция имела от 0 до 5 параметров. Слишком большое количество параметров может запутать вас при последующем обслуживании программы. Получив параметры, укажите тип данных, возвращаемый функцией, с помощью ключевого слова RETURNS.

Вам также необходимо указать, находится ли функция DETERMINISTIC или NOT DETERMINISTIC рядом с ключевым словом RETURNS. DETERMINISTIC означает, что функция всегда будет возвращать один и тот же вывод для одного и того же ввода, что позволяет MySQL оптимизировать выполнение функции.

Если вы не уверены, просто укажите, DETERMINISTIC потому что это значение по умолчанию, которое MySQL будет использовать для функций.

Наконец, вам нужно указать [expression] возвращаемое функцией RETURN ключевое слово. Вот функция MySQL, похожая на функцию JavaScript выше:

CREATE FUNCTION hello ()
RETURNS VARCHAR(20) DETERMINISTIC
RETURN «Hello World»;

Как только вы запустите приведенный выше оператор, вы можете запросить функцию с помощью оператора SELECT:

Имя функции MySQL уникально, что означает, что у вас может быть только одна функция с определенным именем. Запуск CREATE FUNCTION дважды вызовет, ERROR 1304 даже если одна и та же функция имеет разные параметры:

CREATE FUNCTION hello (
input1 VARCHAR(10)
Nfr)
RETURNS VARCHAR(20) DETERMINISTIC
RETURN «Hello World»;
ERROR 1304 (42000): FUNCTION hello already exists

Чтобы изменить существующую функцию, вам нужно сначала удалить функцию, используя DROP FUNCTION синтаксис.

DROP FUNCTION IF EXISTS hello;

Таким образом, функции в MySQL позволяют производить некоторые действия и возвращать результат выполнения.

Создано 25.04.2023 11:00:58

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Execute mysql «create function» statement with PHP

    Solution 1: I have created below function in MYSQL Using it as Solution 2: I have created a simple php function to use MySQL queries. For ex : or you can set your own variable name by putting » as » result output will be : If more number of rows has been selected, the variable name will be created as an array for ex : or you can set your own variable name by putting » as » Result output will be : (If the user table has three rows )

    Execute mysql «create function» statement with PHP

    I want to run the following mysql create function statement from PHP:

    DELIMITER $$ CREATE FUNCTION `myFunc`(`instring` varchar(4000)) RETURNS int(11) NO SQL DETERMINISTIC SQL SECURITY INVOKER BEGIN DECLARE position int; . here comes function logic RETURN position; END$$ DELIMITER ; 

    But I get this mysql error:

    check the manual that corresponds to your MySQL server version for the right syntax to use near ‘DELIMITER’

    What can I do? Can I execute create statement without DELIMITER keyword?

    You most likely do not need the DELIMTER command. That belongs to MySQL-centric client programs.

    Please try with plain old semicolons:

    if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") || !$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;")) < echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error; > 

    and let PHP worry about delimiting

    CAVEAT

    I got the above code from http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

    PHP mysqli query() Function, For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure: PHP Version: 5+ PHP Changelog: PHP 5.3.0 added the ability for async queries Code samplemysqli_query($con,»SELECT * FROM Persons»);mysqli_query($con,»INSERT INTO Persons (FirstName,LastName,Age)VALUES (‘Glenn’,’Quagmire’,33)»);mysqli_close($con);Feedback

    Custom function for mysqli queries

    I’m trying my hand at custom functions in PHP in order to streamline a lot of stuff I’m otherwise doing manually. I’m damn new to custom functions so I’m not sure the limitations. Right now I’m trying to get data with MySQLi using custom functions Here’s the code, and then I’ll explain the issue:

    function connect_db($db = 'db_username') < iconv_set_encoding("internal_encoding", "UTF-8"); mb_language('uni'); mb_internal_encoding('UTF-8'); @ $mysqli = new mysqli('host',$db,'password',$db); if(mysqli_connect_errno()) < die('connection error'); >> 

    This one seems to be working fine. It’s the next function I’m having more trouble with.

    edit: Updated thanks to Jeremy1026’s response

    function do_query($db = 'default_db', $query) < connect_db(); $result = $mysqli->query($query); if(!$result) < trigger_error("data selection error"); >while($row = $result->fetch_assoc()) < $result_array[] = $row; >return $result_array; > 

    My host forces database names and usernames as the same, so if the db name is ‘bob’ the username to access it will be ‘bob’ as well, so that’s why $db shows up twice in the connection.

    The problem I’m having is that these two functions are in functions.php and being called from another page. I want to be able to pull the results from the query in that other page based on the column name. But I also need to be able to do this with formatting, so then maybe the while() loop has to happen on that page and not in a function? I want this to be as universal as possible, regardless of the page or the data, so that I can use these two functions for all connections and all queries of the three databases I’m running for the site.

    God I hope I’m being clear.

    Big thanks in advance for any suggestions. I’ve googled this a bit but it’s tough to find anything that’s not using obsolescent mysql_ prefixes or anything that’s actually returning the data in a way that I can use.

    Update: I’m now getting the following error when accessing the page in question:

    Fatal error: Call to a member function query() on a non-object in /functions.php `

    with the line in question being $result = $mysqli->query($query); . I assume that’s because it thinks $query is undefined, but shouldn’t it be getting the definition from being called in the page? This is that page’s code:

    $query = "SELECT * FROM `table`"; $myArray = do_query($db, $query); echo $myArray['column_name']; 

    In your 2nd function you aren’t returning any data, so it is getting lost. You need to tell it what to return, see below:

    function do_query($db = 'default_db', $query) < connect_db(); $result = $mysqli->query($query); if(!$result) < trigger_error("data selection error"); >while($row = $result->fetch_assoc()) < $result_array[] = $row; >return $result_array; > 

    Then, when using the function you’ll do something like:

    $myArray = do_query($db, 'select column from table'); 

    $myArray would then be populated with the results of your query.

    This is a half-answer. The following single function works in place of the two.

    function query_db($database, $new_query) < $sqli = new mysqli('host', $database, 'password', $database); $sqli->set_charset("utf8"); global $result; if($result = $sqli->query($new_query)) < return $result; >> 

    By adding global $result I was able to access the results from the query, run from another page as

    query_db("username","SELECT * FROM `column`"); while($row = $result->fetch_assoc())

    It’s more streamlined than I have without functions, but it’s still not idea. If I have the connection to the database in another function, it doesn’t work. If I try to put the while loop in the combined function, it doesn’t work. Better than nothing, I guess.

    PHP mysqli_query() Function, Return Values. For SELECT, SHOW, DESCRIBE and EXPLAIN queries this function returns a mysqli_result object holding the result of the query in case of success and, false if failed.. For other queries this function returns an boolean value which is, true if the operation/query is successful and, false if not. PHP …

    How can i use function in my mysql query?

    i want to find out the places which are with in a given distance from a geographical latitude and longitude.

    i have one table in a mysql database called places , in which there are three columns placeId , latitude and longitude .

    user provide latitude , longitude of a place and a distance , then by using the following formula:

    i can check whether these place are with in the distance given by the user or not.

    I want to know that how can i write a query and function to implement this functionality.

    I have created below function in MYSQL

    DELIMITER $$ DROP FUNCTION IF EXISTS `great_circle_distance`$$ CREATE DEFINER=`root`@`localhost` FUNCTION `great_circle_distance`( lat1 DOUBLE(10,6), lon1 DOUBLE(10,6), lat2 DOUBLE(10,6), lon2 DOUBLE(10,6) ) RETURNS double(10,2) DETERMINISTIC BEGIN DECLARE delta_lat DOUBLE(10,6); DECLARE delta_lon DOUBLE(10,6); DECLARE temp1 DOUBLE(10,6); DECLARE EARTH_RADIUS DOUBLE(10,2); DECLARE distance DOUBLE(10,2); SET lat1 = RADIANS(lat1); SET lon1 = RADIANS(lon1); SET lat2 = RADIANS(lat2); SET lon2 = RADIANS(lon2); SET delta_lat = lat2 - lat1; SET delta_lon = lon2 - lon1; SET temp1 = pow(sin(delta_lat/2.0),2) + cos(lat1) * cos(lat2) * pow(sin(delta_lon/2.0),2); SET EARTH_RADIUS = 3956.0; SET distance = EARTH_RADIUS * 2 * atan2(sqrt(temp1),sqrt(1-temp1)); RETURN distance; END$$ DELIMITER ; 
    Select great_circle_distance(z.lat,z.log, 32.2342,-72.42342) AS Distance from tbl_abc AS z; 

    I have created a simple php function to use MySQL queries.

    Any query can be executed in 1 simple function.

    In case of select query, We can get the selected arguments as variable name contains the selected argument value.

    or you can set your own variable name by putting » as «

    If more number of rows has been selected, the variable name will be created as an array for ex :

    or you can set your own variable name by putting » as «

    else < $username_val=$un[$n]; // for multiple rows selected $user_ids=$uid[$n]; >echo $username_val; echo " "; echo $user_ids; echo "
    "; > ?>

    Result output will be : (If the user table has three rows )

    User1 4043 User2 4048 User3 4056 

    Create mysql Connection file ex : mysql_connect_file.php

    The php function is below

     else< $mysql_err= mysqli_error($dbc); $err= debug_backtrace(); $err_line=$err[0]['line']; $err_file=$err[0]['file']; echo "Error at $err_file on line $err_line query -->$main_q ( $mysql_err )"; return FALSE; > >elseif(strpos($temp, "select")==1)< $qn= str_replace("select ", "", $q); $qn=substr($qn,0, strpos($qn, " from")); $qn="$qn,"; $selc= str_replace("`","", $qn); $qn= str_replace("`","", $qn); $my_var=array(); $my_nm=array(); for($m=1;$m<=substr_count($selc, ',');$m++) < $my_nm[$m]=substr($qn,0, strpos($qn, ",")); $qn=substr($qn,strpos($qn, ",")+1, strlen($qn)); if(strpos($my_nm[$m]," as ")>0) < $my_var[$m]= str_replace(" as ", "~", $my_nm[$m]); $my_var[$m]= str_replace(" ", "", $my_var[$m]); $my_var[$m]=substr($my_var[$m],strpos($my_var[$m],"~")+1,strlen($my_var[$m])); >else < $my_var[$m]=substr($my_nm[$m],0, strlen($my_nm[$m])); $my_var[$m]= str_replace(" ","", $my_var[$m]); >> $rn=mysqli_query($dbc, $main_q); if($rn) < if(mysqli_num_rows($rn)>0) < for($t=1;$t<=count($my_var);$t++) < $$my_var[$t]=array(); >while($row=mysqli_fetch_array($rn,MYSQLI_ASSOC)) < if(mysqli_num_rows($rn)>1) < for($t=1;$t<=count($my_var);$t++) < $<$my_var[$t]>[]=$row[$my_var[$t]]; > >else < for($t=1;$t<=count($my_var);$t++) < $$my_var[$t]=$row[$my_var[$t]]; >> > if(mysqli_num_rows($rn)>1) < for($t=1;$t<=count($my_var);$t++) < $GLOBALS[$my_var[$t]]= sel_mr($my_var,$$my_var[$t]); >for($t=1;$t <=count($my_var);$t++) < return $$my_var[$t]; >> if(mysqli_num_rows($rn)==1) < for($t=1;$t<=count($my_var);$t++) < $GLOBALS[$my_var[$t]]=$$my_var[$t]; >for($t=1;$t <=count($my_var);$t++) < return $$my_var[$t]; >> >else < for($t=1;$t<=count($my_var);$t++) < $GLOBALS[$my_var[$t]]=NULL; >for($t=1;$t <=count($my_var);$t++) < return $my_var[$t]; >> >else < for($t=1;$t<=count($my_var);$t++) < $my= mysqli_error($dbc); if($t==1) < $err= debug_backtrace(); $err_line=$err[0]['line']; $err_file=$err[0]['file']; echo "Error at $err_file on line $err_line query -->$q ( $my )"; > > for($t=1;$t <=count($my_var);$t++) < for($p=0;$p> > > > function sel_mr($a,$ab) < for($t=1;$t<=count($a);$t++) < foreach ($ab as $my) < $<$a[$t]>[]=$my; > > for($t=1;$t <=count($a);$t++) < return $$a[$t]; >> ?> 

    You can save this code into a file then you can call this function by including that file name

    for ex : if your file name is q.php ( —> contains q function ) then you can use the code for another files by including

    Mysql — php function with mysqli, To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it’s handle all the …

    Источник

    Читайте также:  Python как скрыть процесс
    Оцените статью