FuelPHP - How do I execute custom, multi-line MySQL statement? - fuelphp

How do I execute an SQL statement that is performing multiple actions?
When I try to execute the following code, I get an error Fuel\Core\Database_Exception [ 1064 ]: You have an error in your SQL syntax;
PHP with MySQL embeded
$sql = "
SET #sql = CONCAT(
'CREATE TEMPORARY TABLE IF NOT EXISTS temp_compiled_properties AS
(SELECT
id,
', #sql, '
FROM properties
WHERE properties.property_id = ?
GROUP BY properties.property_id)');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #property_id;
DEALLOCATE PREPARE stmt;";
DB::query($sql)->execute();

At the moment you can't.
You can work around it by fetching the current database connection, and use the native PHP calls directly
$db = \DB::instance()->connection();
$result = $db->exec($sql); // for PDO
Afaik the native MySQL drivers don't support multiple statements at all.

Related

Is there any way to write dynamic queries in Postgres' SQL dialect without using PL/pgSQL?

I need to write dynamic query in Postgres which should not be a function/procedure.
I tried using Prepare and execute statement but, could not find any thing wherein i would generate a plain text and then execute.
SET #sql = 'SELECT #endDate = endDate from '+#metadbname+'.dbo.sometable where some condition';
EXECUTE sp_executesql #sql, some_variables
Can we have any variation of above query in PostgreSQL without using PL/pgSQL.

Azure SQL how to create database user by procedure?

I would like to register new user from client app, by calling webapi, where dapper will execute procedure to create new db user and store credentials in table (without password). After registration, I will change connection string with user credentials to log in.
Is it possible to dynamically create db users by executing stored procedure on Azure sql db?
I've made such query:
CREATE PROCEDURE [dbo].[AddDbUser]
#Login nvarchar(50),
#Password nvarchar(50),
#Mail nvarchar(70),
#Phone nvarchar(9),
#SQL nvarchar(1000)
AS
BEGIN
SET #SQL = 'USE [testdb] '
+ 'CREATE LOGIN '+quotename(#Login)+' WITH PASSWORD =
'+quotename(#Password,'''')+'; '
+ 'CREATE USER '+#Login +'; '
+ 'EXEC [sys].[sp_addrolemember] ''db_datareader'', '+#Login+'; '
+ 'EXEC [sys].[sp_addrolemember] ''db_datawriter'', '+#Login+'; '
+ 'GRANT EXECUTE ON SCHEMA :: [dbo] TO '+#Login+'; '
+ 'INSERT INTO [dbo].[Users] (Login, Mail, Phone) '
+ 'VALUES ('+quotename(#Login,'''')+', '+quotename(#Mail,'''')+',
'+quotename(#Phone,'''')+');'
EXEC (#SQL)
END
GO
exec [dbo].[AddDbUser] 'dawidtest', 'password', 'mail#mail.pl', '123123123', null results in message: "User must be in the master database.", but when I add USE [master] instead of USE [testdb] I get message: "USE statement is not supported to switch between databases. Use a new connection to connect to a different database.".
Anybody could provide me some tips how to solve my problem or maybe there is some other more elegant solution?
Thank you in advance!
According to the Microsoft you will have to do in two steps since the USE statement is not supported:
One thing to note is that SQL Azure does not allow the USE Transact-SQL statement, which means that you cannot create a single script to execute both the CREATE LOGIN and CREATE USER statements, since those statements need to be executed on different databases.
So follow the advice given in the message you are getting. Create two sql statements and execute them using different connections.
One that connects to the master db and creates the login and the other one that connects to the specific db and creates the user.

mysqli cannot call stored procedure

Procedure
delimiter $$
drop procedure if exists db1.test;
create procedure db1.test()
deterministic
begin
select * from table1;
end$$
delimiter ;
php code:
$conn = new mysqli('localhost','username','passwd','db1');
$query1 = 'select * from table1';
$query2 = 'call test()';
Then $conn->query($query1) works while $conn->query($query2) returns bool(false).
But in mysql, both query1 and query2 work.
What did I miss here? Thanks!
Okay, if it's not the syntax, it could be permissions. Did you grant execute privileges to the user for this database?
Edit:
Here's the SQL to do this:
GRANT EXECUTE ON `db1` . * TO 'user'#'localhost';
(Even if a user has all the permissions required to do the SQL inside the stored procedure as individual queries, you'd still need the EXECUTE privilege to actually call the procedure.)
Are you sure the procedure is being created? Both MySQL Workbench and phpMyAdmin are telling me there's a syntax error in select * from table; --- probably because table is a reserved word? This worked in MySQL Workbench:
USE `db1`;
DROP procedure IF EXISTS `test`;
DELIMITER $$
USE `db1`$$
CREATE PROCEDURE `db1`.`test` ()
BEGIN
select * from `table`;
END
$$
DELIMITER ;
Note the addition of backticks to table. With that change on my system, $query2 succeeds but $query1 fails (with or without the change to the procedure of course)

dynamic query postgres

I am new to postgres and running following dynamic query
EXECUTE 'Select * from products';
I get following response.
ERROR: syntax error at or near "'Select * from products'"
LINE 1: EXECUTE 'Select * from products';
I Know this would be something basic I m missing
There is the EXECUTE statement of plpgsql, which would do what you are trying to do - execute an SQL query string. You tagged dynamic, so this may be what you are looking for.
Only works inside plpgsql functions or DO statements (anonymous code blocks). The distinction between EXECUTE and SQL-EXECUTE made clear in the fine manual:
Note: The PL/pgSQL EXECUTE statement is not related to the EXECUTE SQL
statement supported by the PostgreSQL server. The server's EXECUTE
statement cannot be used directly within PL/pgSQL functions (and is
not needed).
If you want to return values from a dynamic SELECT query as your example indicates, you need to create a function. DO statements always return void. More about returning values from a function in the very fine manual.
From the fine manual:
Synopsis
EXECUTE name [ ( parameter [, ...] ) ]
Description
EXECUTE is used to execute a previously prepared statement.
So EXECUTE doesn't execute a string of SQL, it execute a prepared statement that is identified by a name and you need to prepare the statement separately using PREPARE:
=> prepare stmt as select * from products;
=> execute stmt;
-- "select * from products" output goes here...

How to execute an SQL string in DB2

How do I execute an SQL string statement in DB2? I'm using IBM Data Studio.
Do you mean executing a dynamic SQL string? Something like:
DECLARE stmt VARCHAR(1000);
DECLARE my_table VARCHAR(50);
SET my_table = 'DEPT_'||deptNumber;
SET stmt = 'SELECT * FROM '||my_table;
PREPARE s1 FROM stmt;
EXECUTE s1;
You can only do that in a stored proc though. One defined as CREATE PROCEDURE GetDeptInfo (deptNumber VARCHAR(5)) for this example. Read about EXECUTE and PREPARE in the db2 docs http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp
After days of researching I found how to write and run dynamic SQL on DB2:
create or replace procedure Search ()
BEGIN
DECLARE v_dynamicSql varchar(2000);
SET v_dynamicSql = 'INSERT INTO dictonary(name) values(' || 'dynamicSQL in db2' ||')';
EXECUTE IMMEDIATE v_dynamicSql;
END;
Hope to help someone.
What difficulty are you encountering?
There are likely lots of ways to do it. Here's one:
File -> New -> Other -> SQL or XQuery script
You may need to create a project or define a database connection.
Enter the SQL code.
Script -> Run script.
Results will show up at the bottom of your screen.
In Control Center, right click the database, you will see "Query". Click on it and you are good to go.