For a legacy project, I would like to execute this query using CodeIgniter :
DELIMITER $$
CREATE FUNCTION `getCustomerFullName`(intCustomerID INT)
RETURNS varchar(100) CHARSET latin1
return CONCAT(
(SELECT FirstName FROM Customer WHERE CustomerID = intCustomerID),
' ',
(SELECT LastName FROM Customer WHERE CustomerID = intCustomerID))$$
DELIMITER ;
When I try to use $this->db->query(), I get this error :
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'DELIMITER $$ CREATE FUNCTION `getCustomerFullName`(intCustomerID INT) RETURNS '
at line 1
How can I execute such "multi-line" query using CodeIgniter ?
The issue is in the query, not CodeIgniter. Use the regular delimiter inside your function:
DELIMITER $$
CREATE FUNCTION `getCustomerFullName`(intCustomerID INT)
RETURNS varchar(100) CHARSET latin1
return CONCAT(
(SELECT FirstName FROM Customer WHERE CustomerID = intCustomerID),
' ',
(SELECT LastName FROM Customer WHERE CustomerID = intCustomerID));
$$
DELIMITER ;
if you want to execute a Function or SP, you need to add this to mysql (in the mtop menu of your phpmyadmin or Workbench) you have many otions
in More (routine / new / add new)
create a function or sp
Then in CI you only call like
$this->db->query('call Function()');
Best solution i get was looking inside system libs and use it.
$this->db->simple_query("YOUR FULL SQL STRING");
I was looking on google and not solution provided.
Related
I'm trying to write a PHP program to update a MySQL table entry according to a phone number. The phone numbers in the database are entered without limitations and are typically formatted in the XXX-XXX-XXXX way, but sometimes have other characters due to typos. In order to ensure the query works every time, I want to remove all non-numeric characters from the entries so that I can compare the entries to phone numbers formatted like XXXXXXXXXX coming from a separate source.
I've done some research and found some solutions but am unsure how to incorporate them into the PHP script. I am fairly new to MySQL and most of the solutions provided user defined MySQL functions and I don't know how to put them into the PHP script and use them with the query I already have.
Here's one of the solutions I found:
CREATE FUNCTION [dbo].[CleanPhoneNumber] (#Temp VARCHAR(1000))
RETURNS VARCHAR(1000) AS BEGIN
DECLARE #KeepValues AS VARCHAR(50)
SET #KeepValues = '%[^0-9]%'
WHILE PATINDEX(#KeepValues, #Temp) > 0
SET #Temp = STUFF(#Temp, PATINDEX(#KeepValues, #Temp), 1, '')
RETURN #Temp
END
And this is the query I need the solution for:
$sql = "SELECT pid AS pid FROM patient_data " .
"WHERE pid = '$pID' AND phone_cell = '$phone_number';";
The query should return the data in the pid column for a single patient, so if the phone number is 1234567890 and the pid is 15, 15 should be returned. I have no output at the moment.
The example function definition is Transact-SQL (i.e. for Microsoft SQL Server), it's not valid MySQL syntax.
A function like this doesn't go "into" the PHP code. The function gets created on the MySQL database as a separate step, similar to creating a table. The PHP code can call (reference) the defined function just like it references builtin functions such as DATE_FORMAT or SUBSTR.
The SELECT statement follows the pattern of SQL that is vulnerable to SQL Injection. Any potentially unsafe values that are incorporated into SQL text must be properly escaped. A better pattern is to use prepared statements with bind placeholders.
As an example of a MySQL function:
DELIMITER $$
CREATE FUNCTION clean_phone_number(as_phone_string VARCHAR(1024))
RETURNS VARCHAR(1024)
DETERMINISTIC
BEGIN
DECLARE c CHAR(1) DEFAULT NULL;
DECLARE i INT DEFAULT 0;
DECLARE n INT DEFAULT 0;
DECLARE ls_digits VARCHAR(20) DEFAULT '0,1,2,3,4,5,6,7,8,9';
DECLARE ls_retval VARCHAR(1024) DEFAULT '';
IF ( as_phone_string IS NULL OR as_phone_string = '' ) THEN
RETURN as_phone_string;
END IF;
SET n := CHAR_LENGTH(as_phone_string);
WHILE ( i < n ) DO
SET i := i + 1;
SET c := SUBSTR(as_phone_string,i,1);
IF ( FIND_IN_SET(c,ls_digits) ) THEN
SET ls_retval := CONCAT(ls_retval,c);
END IF;
END WHILE;
RETURN ls_retval;
END$$
DELIMITER ;
We can execute these statements in the mysql command line client, connected as a user with sufficient privilege, to create the function.
This isn't necessarily the best way to write the function, but it does serve as a demonstration.
Once the function is created, we can reference it a SQL statement, for example:
SELECT t.foo
, clean_phone_number(t.foo)
FROM ( SELECT '1' AS foo
UNION ALL SELECT '1-888-TAXICAB'
UNION ALL SELECT '888-555-1212'
UNION ALL SELECT '+=_-()*&^%$##"''<>?/;:"abc...xyz'
UNION ALL SELECT ''
UNION ALL SELECT NULL
) t
I am trying to create a stored procedure using PHP. My reading indicates the best way to do this by running the .sql file using the 'exec' command in PHP.
In testing i created a file named amtv3_create_routines.sql with this contents:
DELIMITER //
DROP PROCEDURE IF EXISTS createTc //
CREATE PROCEDURE createTc()
BEGIN
drop table if exists v3_tc;
CREATE TABLE v3_tc (
source BIGINT UNSIGNED NOT NULL ,
dest BIGINT UNSIGNED NOT NULL ,
PRIMARY KEY (source, dest) )
ENGINE = InnoDB;
insert into v3_tc (source, dest)
select distinct rel.sourceid, rel.destinationid
from rf2_ss_relationships rel inner join rf2_ss_concepts con
on rel.sourceid = con.id and con.active = 1
where rel.typeid = (select distinct conceptid from rf2_ss_descriptions where term = 'is a')
and rel.active = 1;
REPEAT
insert into v3_tc (source, dest)
select distinct b.source, a.dest
from v3_tc a
join v3_tc b on a.source = b.dest
left join v3_tc c on c.source = b.source and c.dest = a.dest
where c.source is null;
set #x = row_count();
select concat('Inserted ', #x);
UNTIL #x = 0 END REPEAT;
create index idx_v3_tc_source on v3_tc (source);
create index idx_v3_tc_dest on v3_tc (dest);
END //
DELIMITER;
This code works fine when I manually enter it into mysql 5.6.22
However if I save the file and from the prompt enter the command.
mysql -uroot -p -hlocalhost amtv3 < [full path]/amtv3_create_routines.sql
I have tried saving the file using utf8 encoding and windows 1252 encoding.
From the command prompt, there is no feedback, and the procedure is not created.
In PHP I am using the codeigniter framework. If I use the db->query method I can create the stored procedure, however the database loses connection. issuing $db->reconnect() works, but not reliably.
Any suggestions on how to create the stored procedure?
Omitting the space in the last line, DELIMITER; should result in a syntax error (there may be some other reason why this error is not being printed).
DELIMITER is only a feature of certain MySQL clients, and not a feature of the server. Therefore, when executing a .sql file directly, the server will interpret the first semi-colon as the end of the first statement and DELIMITER // will be seen as a syntax violation:
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //
CREATE PROCEDURE . . .
Discovered this here:
https://github.com/go-sql-driver/mysql/issues/351#issuecomment-120081608
The Solution?
Simply don't change the delimiter. The BEGIN and END already delimit a compound statement.
Source:
https://www.tutorialspoint.com/mysql/mysql_begin_end_compound.htm
You can try this
mysql -h localhost -U <username> -d <database_name> -f /home/user/<procedure_name>.sql
DELIMITER $$
CREATE DEFINER= 'sports'`#`'%'` PROCEDURE `CheckMembership`(IN BrandId int,
IN Email varchar(128),
IN PhoneNumber varchar(10),
OUT ResponseCode int,
OUT ResponseMessage varchar(256))
BEGIN
declare _count int;
select count(*) from Member where Phone1 = PhoneNumber into _count;
set ResponseCode = 1;
set ResponseMessage = '';
END
Can anyone please help me to resolve this stored procedure as I a new to this and couldnot find any good solution in the internet . All I need to do is to get the count value by running it in php
For one thing, the syntax of the SELECT statement is wrong because the INTO clause is misplaced.
That should follow the SELECT list and come before the FROM keyword. For example:
SELECT COUNT(*) INTO _count
FROM Member
WHERE Phone1 = PhoneNumber ;
Syntax help is available in MySQL Reference Manual: http://dev.mysql.com/doc/refman/5.5/en/select-into.html
I'm not sure if this answers the question you were asking. (It's not at all clear what question you were asking.)
Q: I don't know how to call this stored procedure in a php file to get the answers.
From PHP, I think you would need to use MySQL user-defined variables for the OUT arguments, and retrieve those values with a separate SELECT statement:
As a simple demonstration of a pattern you could use, given the arguments of the procedure as shown in the question:
-- set user defined variables
SELECT #brandid = 'fee', #email = 'fi', #phonenumber = 'fo', #rc := '', #rm := '';
-- execute stored procedure with user-defined variables as arguments
CALL CheckMembership(#brandid, #email, #phonenumber, #rc, #rm);
-- retrieve user-defined variables
SELECT #rc AS ResponseCode, #rm AS ResponseMessage;
To return the "count" value, you could follow the same pattern. Modify the procedure to add another OUT parameter, and then set that to the value of that parameter in the procedure.
(This seems an unnecessary rigmarole, using a stored procedure to return a result which could just as easily be returned by a simple query.)
when I try to create a function to retrieve userName from user table using their email it gives me this useless error:
#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'DECLARE name VARCHAR; BEGIN select userName AS name from
user WHERE `ema' at line 2
, the same code with a different syntax works in mssql so I wonder what is the difference? in better words what am I doing wrong here?
DELIMITER ;;
CREATE FUNCTION getUserName(email varchar(50)) RETURNS VARCHAR
BEGIN
DECLARE name VARCHAR;
SELECT `userName` AS name FROM `user` WHERE `email` = email;
RETURN name;
END ;;
Well, first of all, varchar needs to have length, which you lack in two places. Also, you need to select into the variable and return the variable, because you cannot return resultset. Also you should escape name, and you do not need to alias your column because you are selecting into anyway. So, your code should be like this:
DELIMITER ;;
CREATE FUNCTION getUserName(email VARCHAR(50)) RETURNS VARCHAR(50)
BEGIN
DECLARE NAME VARCHAR(50);
SELECT `userName` FROM `user` WHERE `email` = email
INTO `name`;
RETURN `name`;
END ;;
Ok let me try this again.
query("CALL getemployee('$eml')");
$result = $sql->fetch_array();
?>
This is my stored procedure:
Delimiter //
Create procedure getemployee(in eml varchar(50))
Begin
Select * from employees where email = eml;
End//
Delimiter ;
The error i get from browser:
"Fatal error: Call to a member function fetch_array() on a non-object ...".
I use phpmyadmin version 3.2.4 and the mysql client version: 5.1.41
Your CREATE PROCEDURE statement appears to be invalid.
You need to give a name to your procedure, and to the parameter that you are passing. Therefore you may want to try something like the following example:
DELIMITER //
CREATE PROCEDURE procName (IN eml varchar(50))
BEGIN
SELECT * FROM employees WHERE email = eml;
END//
DELIMITER ;
The eml variable you use is not defined. Should not it be as following:
Create procedure getemployee (in eml varchar(50))
CREATE PROCEDURE get_customers(IN inCustomerIdList VARCHAR(100))
BEGIN
SELECT first_name, last_name, email FROM tbl_customers
WHERE customer_id IN (inCustomerIdList);
END$$