Create function Error in phpmyadmin - php

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 ;;

Related

How to remove all non-numeric characters from a MySQL table entry

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

Create a SQL FUNCTION with CodeIgniter

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.

create mysql a stored procedure from file

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

Postgresql custom function returning table

I am using PostgreSQL 9.1.11.
I need to return result of SELECT to my php script. The invocation in php is like this:
$res = $pdb->getAssoc("SELECT * FROM my_profile();");
The class code to illustrate what is going on in php
public function getAssoc($in_query) {
$res = pg_query($this->_Link, $in_query);
if($res == FALSE) {
return array("dberror", iconv("utf-8", "windows-1251", pg_last_error($this->_Link)));
}
return pg_fetch_all($res);
}
Next comes my function in Postgres. I fully re-create database by dropping in a script when I update any function. (The project is in the early stage of development.) I have little to no experience doing stored procedures.
I get this error:
structure of query does not match function result type
CONTEXT: PL/pgSQL function "my_profile" line 3 at RETURN QUERY )
Trying to write:
CREATE FUNCTION my_profile()
RETURNS TABLE (_nick text, _email text) AS $$
BEGIN
RETURN QUERY SELECT (nick, email) FROM my_users WHERE id = 1;
END;
$$
LANGUAGE 'plpgsql' SECURITY DEFINER;
Table structure is:
CREATE TABLE my_users(
id integer NOT NULL,
nick text,
email text,
pwd_salt varchar(32),
pwd_hash character(128),
CONSTRAINT users_pk PRIMARY KEY (id)
);
When I return 1 column in a table the query works. Tried to rewrite procedure in LANGUAGE sql instead of plpgsql with some success, but I want to stick to plpgsql.
The Postgres 9.1.11, php-fpm I am using is latest for fully updated amd64 Debian wheezy.
What I want to do is to return a recordset containing from 0 to n rows from proc to php in an associative array.
This part is incorrect:
RETURN QUERY SELECT (nick, email) FROM my_users WHERE id = 1;
You should remove the parentheses around nick,email otherwise they form a unique column with a ROW type.
This is why it doesn't match the result type.
#Daniel already pointed out your immediate problem (incorrect use of parentheses). But there is more:
Never quote the language name plpgsql in this context. It's an identifier, not a string literal. It's tolerated for now since it's a wide-spread anti-pattern. But it may be considered a syntax error in future releases.
The SECURITY DEFINER clause should be accompanied by a local setting for search_path. Be sure to read the according chapter in the manual.
Everything put together, it could look like this:
CREATE FUNCTION my_profile()
RETURNS TABLE (nick text, email text) AS
$func$
BEGIN
RETURN QUERY
SELECT m.nick, m.email FROM my_users m WHERE m.id = 1;
END
$func$
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp;
Replace public whit the actual schema of your table.
To avoid possible naming conflicts between OUT parameters in RETURNS TABLE ... and table columns in the SELECT statement I table-qualified column names with the given alias m.

php mysql error for creating a table

I got an error while creating a table in php with mysql database, and I tried testing directly on mysql query engine it works fine. whereas in php code it gives below 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.
Below is the code I am writing
$query14 = mysql_query("create table $tablename (
project_id INT,
project_client_id INT,
project_partner_id INT,
project_manager_id INT,
project_employees INT,
project_name VARCHAR(500),
project_status TEXT,
project_summary LONGTEXT,
project_order INT,
project_start_date DATETIME,
project_end_date DATETIME
) ENGINE = INNODB;");
and below is the image attached and table structure should be and this is the sample table i create using with phpmyadmin interface.
And below is the full 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 ''8' (project_id INT, project_client_id INT, project_partner_id INT, project_mana' at line 1`
I didn't see any problem with your query. But what is the value of $tablename? Two error possibilities here :
The variable $tablename is empty.
$tablename is a key-word.
Please check the above two otherwise its all right.
UPDATE :
As per your updated question please try with the following code. I think it will help you.
$query14 = mysql_query("create table `$tablename` (
`project_id` INT,
`project_client_id` INT,
`project_partner_id` INT,
`project_manager_id` INT,
`project_employees` INT,
`project_name` VARCHAR(500),
`project_status` TEXT,
`project_summary` LONGTEXT,
`project_order` INT,
`project_start_date` DATETIME,
`project_end_date` DATETIME
) ENGINE = INNODB;");
Your query syntax is fine, it looks like $tablename is empty.
I think the issue is what is getting replaced for $tablename.
Having the full code example would be more useful in debugging the error.
The mysql create statement works just fine here on mysql 5.1.58 .
As you said in above comments that after echoing the $tablename you got the value 8 then it is not possible to create table.
you have to rename the value of $tablename like tbl_8.
remember with the name tbl-8 your also got error,,
The problem is, $tablename is 8 currently and for SQL table, table name must start with a letter. Current tablename is invalid.

Categories