What is the correct syntax to use MySQL functions inside a PHP string - pdo

Im building a string for a query ib mysql PDO like this:
$fields = "landlord.*, CONCAT('£', FORMAT(landlord.RatePayable, 2,'en_GB'))";
Then later executing like:
$stmt = $cnx->prepare( "SELECT ".$fields. " FROM tblPaid " ); etc ...
However when i output to the browser im getting the mysql function echoed out instead of the result of the concatenation and formatting. How do i escape the mySQL functions in order to get desired effect.

Related

How to use PDO bindParam for SphinxSearch 3?

I have recently installed SphinxSearch 3.1.1 on Ubuntu 18 and am currently creating a snippet of code using PHP 7.2. I am having trouble making bindParam work.
Here is my code:
$mytest = "hello";
$query = $conn->prepare("SELECT *, weight() FROM test WHERE MATCH('\"#title :mytest \"/1')");
$query->bindParam(':mytest', $mytest, PDO::PARAM_STR);
$query->execute();
When I try to execute it, result is empty.
However, when I try to directly put $mytest inside the statement, I get the expected result
$query = $conn->prepare("SELECT *, weight() FROM test WHERE MATCH('\"#title". $mytest ."\"/1')");
Does this mean, sphinx does not support bindParam within the MATCH() function? Or am I missing something else here.
Note from http://php.net/manual/en/pdo.prepare.php
Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters.
ie you trying to bind inside a string literal. In the practical sense PHP (or the mysql server) wll add the ' around the value to make the statement.
... In effect would end up with sphinxql query of:
SELECT *, weight() FROM test WHERE MATCH('"#title 'hellow' "/1')
which is clearly wrong!
Instead bind the whole string literal.
$query = $conn->prepare("SELECT *, weight() FROM test WHERE MATCH(:mytest)");
$query->bindParam(':mytest', '"#title '.$mytest.'"/1', PDO::PARAM_STR);
Although that looks like an invalid Sphinx 'extended syntax' query, The #field qualifer, should be outside the quorum,
$query->bindParam(':mytest', '#title "'.$mytest.'"/1', PDO::PARAM_STR);

Drupal 7 - db_select: SQL function in where condition

I need to use this condition in my select statement:
WHERE YEAR(date) = YEAR(CURDATE())
but if I do, like this:
$query = db_select('table', 't');
$query->fields('t');
$query->condition('YEAR\(date\)', 'YEAR(CURDATE())', '=');
Drupal won't have it (even if I do not escape those parenthesis - it simply ignores them) because I get an error:
Column not found: 1054 Unknown column 'YEARdate' in 'where clause':
How to overcome this error?
Hmm.. just like this, it seems:
$query->where('YEAR(date) = YEAR(CURDATE())');
The where allows for the arbitrary SQL:
The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and if it has variable content it must be added using a named placeholder. The $args array is an array of placeholders and values that will be substituted into the snippet. It is up to the developer to ensure that the snippet is valid SQL. No database-specific modifications are made to the snippet.
Hm, you could also use db_query, it allow you to write SQL queries "without Drupal".
I mean, you'll be able to add custom WHERE statements or any SQL-proper functions, like custom functions ;)
Eg.
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
Use addExpression method :
https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3AaddExpression/7.x
$query = db_select('table', 't');
$query->fields('t');
$query->addExpression('YEAR(t.date) = YEAR(CURDATE())');
$result = $query->execute()->fetchAll();
var_dump($result);

JPA native query gives incorrect output

I know this may sound silly but I've been stuck on this problem for too long!
I'm querying a PostgreSQL repository through JPA using native SQL queries. One of my queries looks like this:
#Query(value = "select * from gs where ?1 = ?2", nativeQuery = true)
public List<GsJsonStore> matchJson(String term, String value);
I'm testing the function using :
List<GsJsonStore> list = repo.matchJson("subject", "'Sub'");
The list is empty on running the query, however when I run the same query through PSQL command line using:
select * from gs where subject = 'Sub';
I get the correct output, records contatining the key-value pair are returned.
Where am I making the mistake?
You can't use parameter for column name. Your query resolves to
select * from gs where 'subject' = '''Sub'''
EDIT: just saw #pozs already posted the same in comment

SQL select query not working with variable parameter in my servelets

i'm trying to execute following line of code with my servelet in netbeans:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD =" + searchTxt);
where searchTxt is String variable.
but it says "Column 'zeeshan' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join . . . . ".
it really works fine, if i provide the hardcoded value instead of variable, as:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD= 'zeeshan'");
i'm not getting, what i'm missing?
You are missing the single quotes around the sql string you are constructing. So this should work:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD ='" + searchTxt+"'");
Please note that constructing SQL statements in this way is really dangerous, because it opens your application up for SQL injection attacks. Use bind parameters instead.
This will also allow better caching of parsed statements on many rdbms's.

Php mysql statement with set and select

I have a weird problem, when i use the query on phpmyadmin, it works. but when i use using a php script it returns an error.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I tried to troubleshoot and discovered that the problem lies with the set statement.
this is my example code.
$sql = 'set #rank=0; select * from user;';
Please help somebody.
First Run
$sql = set #rank=0;
it will store value of rank
then run:
select * from user;
In sort you need to run both queries separately .
set statement stores values. that can be used by next executing query,
like code below :
$sql ="SET #id:=0";
$Executives=$DB->exec($sql);
$sql = "SELECT #id:=#id+1 as id,pes.* FROM profile_executive_summary as pes where profile_id=".$pid;
$Executives=$DB->fetchAssoc($sql);
See what mysql_error returns after you run mysql_query('...'). That might help. In general, mysql_query only permits one query. You can't separate them by newlines or semicolons. mysqli will do it for you though.