Laravel 5-Execute sql statement in string - php

I am using Laravel 5.
I need to save some sql statements in a field of a table of the database (these statements are used to get some results).
I want to get these statements in my controller and execute them using Laravel, but the statements are only strings,
Let's suppose the following
$statement = Table::where('ID', 1);
$statement = $statement->STATEMENT;
In $statement I have a string like this
$statement = 'SELECT SUM(VAL) FROM TABLE';
What I need to know is how to execute in the database the statement saved in my string var $statement
I finally want to have something like
$result = 10 (the result of executing 'SELECT SUM(VAL) FROM TABLE', which was in $statement)
Thanks!

This is called raw queries in laravel. For example:
DB::select(DB::raw('select * from users''));
So in your case(if You've already got $statement):
DB::select(DB::raw($statement));

Related

search not returning query

Sorry my english. I'm trying to search mysql database that contains hashtags, but it returns all.
eg Search #NBA returns: #NBA, #NBA2021, #NBAscoreBoard, etc
I've tried every preg_replace on here. eg #(^|\s)#(\w*[a-zA-Z_]+\w*)# But how do I break after the specific search is met?
$_GET["tag"]='#nba'; // $_GET is from a query string
$fulltag = preg_replace("/[^a-zA-Z0-9_]/", '', $_GET["tag"]); //trying to isolate this problem
$sql='SELECT * FROM status WHERE data LIKE "%#'.$fulltag.'%" LIMIT 12';
//
//
//
echo //the result containing the "# $fulltag";
As I said in my comment--just doing two queries with one to test if data = fullTag, and then if that returns nothing, then doing the wildcard search--is probably going to be simpler.
However, if you really want this to be a single query, you could do something like this, wherein you test to see if it is an exact match within a sub-query, then order by whether it's an exact match so that if there is an exact match, it will be the first result.
SELECT *
FROM (
SELECT
data,
CASE
WHEN data = "#NBA"
THEN 1
ELSE 0
END AS is_exact
FROM status
WHERE data LIKE "%#NBA%"
LIMIT 12
) AS matches
ORDER BY is_exact DESC
A separate note: You code right now is very vulnerable to SQL Injection. You should try using parameterized prepared statements instead of manually building your queries. See PDO or MySQLi prepared statements.
Here is an example of the above query using PDO, and this method of using CONCAT to safely add wildcards to your query:
$_GET["tag"]='#nba'; // $_GET is from a query string
$fulltag = preg_replace("/[^a-zA-Z0-9_]/", '', $_GET["tag"]); //trying to isolate this problem
$pdo = new PDO(/* your connection details */);
$sql =
'SELECT *
FROM (
SELECT
data,
CASE
WHEN data = CONCAT("#", :tag1)
THEN 1
ELSE 0
END AS is_exact
FROM status
WHERE data LIKE CONCAT("%#", :tag2, "%")
LIMIT 12
) AS matches
ORDER BY is_exact DESC
';
$stmt = $pdo->prepare($sql);
$stmt->execute([
':tag1' => $fulltag,
':tag2' => $fulltag,
]);
Here's your simpler query using the same, safer approach:
$_GET["tag"]='#nba'; // $_GET is from a query string
$fulltag = preg_replace("/[^a-zA-Z0-9_]/", '', $_GET["tag"]); //trying to isolate this problem
$pdo = new PDO(/* your connection details */);
$sql = 'SELECT * FROM status WHERE data LIKE CONCAT("%#", :fullTag, "%") LIMIT 12';
$stmt = $pdo->prepare($sql);
$stmt->execute([':fullTag' => $fulltag]);

PHP: Include an SQL query containing $variables

I really dislike writing SQL queries within my PHP.
Given the following example piece of PHP:
script.php
$name = 'Bill'
$query = "SELECT * FROM a_table WHERE name='$name'";
I'd like to instead write the sql query in it's own file and include (or otherwise) get the contents into my script:
query.sql
SELECT * FROM a_table WHERE name='$name'
script.php
// This doesn't work obviously
$query = '"'.include('query.sql').'"';
Note that I'd like to be able to reference PHP variables within the SQL query (e.g: $name is setup declared in script.php but used as part of the query).
nice and simple solution:
$sql = file_get_contents("query.sql");
And to reference variables, I suggest using PDO where you reference like this
$query = $db->query( "SELECT x FROM x WHERE x = :example")
$query->execute(array("example"=>$value));
...But you can do something similar to this in mysqli, etc.
query.sql:
SELECT * FROM a_table WHERE name=:name
script.php:
$query = file_get_contents('path/to/query.sql');
Then bind the parameters and execute the query.
See How can I prevent SQL-injection in PHP? for why you should bind variables instead of concatenating them into your query string.

Can I use name of the column as parameter in PDO?

I'm trying to execute this:
$colparam = 'abcd';
$stmt = $db->prepare("SELECT DISTINCT ? AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute(array($colparam));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
and it's not working (no errors, just empty array as result).
Instead this works fine:
$stmt = $db->prepare("SELECT DISTINCT abcd AS kol FROM katalog ORDER BY kol ASC");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
So is there any catch with the use of parameter as a name of the column in PDO?
No, you can't use parameter replacements for any database objects (tables, columns, etc.) in MySQL.
When you think about what a prepared statement actually is, this makes complete sense. As how can MySQL prepare a query execution plan when it does not even know the database objects involved.
I certainly wish that more documentation would actually cover what a prepared statement actually does (beyond it's obvious use for parametrization).
Here is link to MySQL prepared statement documentation for more reading:
https://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html

Using PDO in PHP to count all from database and the 'WHERE' is a variable that has to be cleaned

I'm trying to count all of the rows from an item list where the id matches a user input. I am switching all of my code from mysql to PDO as I have learned it is much better.
The code below is what I found to work in my situation.
$id = '0';
$sql="SELECT count(*) FROM item_list WHERE item_id = $id";
$data=$connMembers->query($sql)->fetchcolumn();
echo $data;
However, It is not safe for a live site due to sql injections.
I want to know how can I change it to work whare it sanatizes the user input.
I would prefer using a prepare and execute functions so the variables are kept seperately.
So is there something I can do?
This is where you start binding parameters. I prefer to do it using ? and one array for inputs.
Assuming $connMembers is your PDO object:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ?";
$input=array($id); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
To add more variables to your sql, just add another ? to the query and add the variable to your input.
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = ? AND item_name=?";
$input=array($id, $name); //Input for execute should always be an array
$statement=$connMembers->prepare($sql);
$statement->execute($input);
$data=$statement->fetchObject();
var_dump($data);
OR you can use bindParam:
$sql="SELECT COUNT(*) FROM item_list WHERE item_id = :itemID";
$statement=$connMembers->prepare($sql);
$statement->bindParam(':itemID', $id);
/*Here I am binding parameters instead of passing
an array parameter to the execute() */
$statement->execute();
$data=$statement->fetchObject();
var_dump($data);

How to create a prepared statement in PHP with a formula involving columns in the where clause?

I want to create prepared stmt such as
"SELECT id,latitude,longitude
FROM sometable WHERE
(3437.74677 * ACOS(SIN(latitude_radians) * SIN(?) +
COS(latitude_radians)*COS(?) * COS(longitude_radians - ?))) <= ?";
in PHP. Where clause is a function of column values and bind variables
but how should I bind the values. Or is this even a legal prepared stmt?
Thanks in advance,
-v-
I don't see any problem here.
See:
PHP Prepared Statements.
Extremely minimal sample:
$stmt = $dbh->prepare( $QUERY );
$stmt->execute( $arguments_array )
Sorry for being unclear.
As I understand following is an example of PHP prepared stmt,
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name'])))
Now the where clause is always a simple, column = ? AND column2 = ?. In my case though its function and it didnt work when assigned values to the bind variables. I will regenerate the error again and post it.
I was wondering then if it is even legal to have a function of column names and bind variables in the where clause.

Categories