Multiple Variable in one SQL Like - php

I searched a lot and cannot find my answer. I'm trying to include 2 variable in my like statement to match a date that wasn't formatted correctly in a database I'm working on.
I need to:
Select count(*) as ABC
from database
where active like '1'
and agent = '$Employeestringid'
AND time LIKE '%$FilterMonth_%_$queryyear'"
The part that is currently not working is: '%$FilterMonth_%_$queryyear'
I need it to work and match a date formatted like: '9:10:31 PM Fri, May 20th 2016' by only capturing MONTH and YEAR.

When interpolating your variables in the string, PHP reads the _ as part of the variable name.
You need to use {} to prevent this behavior:
$query = "Select count(*) as ABC
from database
where active like '1'
and agent = '$Employeestringid'
AND time LIKE '%{$FilterMonth}_%_{$queryyear}'";

Remove the underscores
'%$FilterMonth%$queryyear'

Related

Sum Column with Oracle 11 and PHP - what's wrong?

Trying to get a simply query going through and its not working - newbie here.
Other php files and queries do run well.
$sql = "select sum(rese_nshw) as noshows from tnht_eseo where edta_data = '19.10.01'" ;
$sumParse = oci_parse($conn, $sql);
oci_define_by_name($sumParse, "noshows", $total);
oci_execute($sumParse);
while(oci_fetch($sumParse)){
echo "noshows:". $total;
}
what's wrong ? just outputs blank.
Running the SQL query in Oracle directly, it outputs 6 as NOSHOWS for this query.
If EDTA_DATA is date (datatype), don't compare it to a string as '19.10.01' is a string. Oracle will implicitly try to convert it to appropriate date, but that doesn't have to work always. Besides 19.10.01 can be anything (2019 Oct 01, or 19 Oct 2001, or ...), depends on NLS settings.
Take control over it; see whether using date literal helps (it always has yyyy-mm-dd format):
where edta_data = date '2019-10-01'
Furthermore, if edta_data contains time component (hours, minutes, seconds), then the simplest option is to truncate it, e.g.
where trunc(edta_data) = date '2019-10-01'
but it'll prevent Oracle from using index on that column (if it exists). It can be fixed, no problem; but - first see whether anything of above helps.
You have to use Upper Case as defined here:
column_name The column name used in the query.
Use uppercase for Oracle's default, non-case sensitive column names.
Use the exact column name case for case-sensitive column names.
from: https://www.php.net/manual/en/function.oci-define-by-name.php
Then:
oci_define_by_name($sumParse, "NOSHOWS", $total);

replacing specific strings in a SELECT sql query (PLUS) if contains LIKE '%text%' replace the whole result

Replacing strings in a select query to kill off bad characters that will be harmful to folder names I am creating. That part is working well.
SELECT cust_name =
REPLACE(REPLACE([cust_name],'.',''),'/','-')
FROM work,dbo.cust cust_name
WHERE work.cust_id_bill_to = cust_name.cust_code AND
work.job_id = '44514' AND
work.sub_job_id = '11'
(THAT) Works great. BUT NOW I have one customer result who has hundreds of duplicate customer names based on stores and franchises, need only 1 customer name returned. So, have to figure out how to add code that would replace the entire result where this string is used.. mcdonald
So if the result comes back with MCDONALDS STORE#4567 I need to replace that with simply MCDONALDS.
WHERE cust_name LIKE N %mcdonald%
No matter the full text result in this case, like an if statement combined with my replace statement and a wildcard to boot? Changes the hundreds of those results to a single answer ... if it has mcdonald in it, it just gives me MCDONALDS as a result. Any ideas how to put that together. TIA. JP
You can use CHARINDEX to find a string within another string. If the result is 0, then the string is not found.
Then you could combine that with a CASE statement.
select
case when charindex('mcdonalds', cust_name) = 0
then replace(replace([cust_name],'.',''),'/','-')
else 'mcdonalds'
end as customer name
from ...

Running a MySQL query using a string in php

Answer found (syntax): The column name of my string had to be encased in backticks " ` " as they contained spaces. Note that this means that the majority of this post has no relevance to the issue. The code has been corrected in case someone wants to do something similar.
So, I am doing a foreach loop to assign a value (1/0) to non-static columns in my database (it needs to support addition/deletion/editing of columns). I am using $connectionvar->query($queryvar); to do my queries which worked fine up until now when I'm trying to use a custom built string as $queryvar in order to change the column name to a variable within the loop. I've been outputting this string through echo and it looks exactly like my functional queries but somehow doesn't run. I've attempted to use eval() to solve this but to no avail (I feel safe using eval() as the user input is radio buttons).
Here's the loop as well as my thought processes behind the code. If something seems incoherent or just plain stupid, refer to my username.
foreach($rdb as $x) { //$rdb is a variable retrieved from $_POST earlier in the code.
$pieces = explode("qqqppp", $x); //Splits the string in two (column name and value) (this is a workaround to radio buttons only sending 1 value)
$qualname = $pieces[0]; //Column name from exploded string
$qualbool = $pieces[1]; //desired row value from exploded string
$sql = 'UPDATE users SET '; //building the query string
$sql .= '`$qualname`';
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\''; //$profilename is retrieved earlier to keep track of the profile I am editing.
eval("\$sql = \"$sql\";"); //This fills out the variables in the above string.
$conn->query($sql); //Runs the query (works)
echo ' '.$sql.' <br>'; //echoes the query strings on my page, they have the exact same output format as my regular queries have.
}
}}
Here's an example of what the echo of the string looks like:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
For comparison, echoing a similar (working) query variable outside of this loop (for static columns) looks like this:
UPDATE users SET profiletext='qqq' WHERE username='Admin2'
As you can see the string format is definitely as planned, yet somehow doesn't execute. What am I doing wrong?
PS. Yes I did research this to death before posting it, as I have hundreds of other issues since I started web developing a month ago. Somehow this one has left me stumped though, perhaps due to it being a god awful hack that nobody would even consider in the first place.
You need to use backticks when referring to column names which have spaces in them. So your first query from the loop is outputting as this:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
But it should be this:
UPDATE users SET `Example Qualification 3`='1' WHERE username='Admin2'
Change your PHP code to this:
$sql = 'UPDATE users SET `'; // I added an opening backtick around the column name
$sql .= '$qualname`'; // I added a closing backtick around the column name
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\'';
Example Qualification 3 : Is that the name of your Mysql Column name ?
You shouldnt use spaces nor upper / lower case in your columnname.
Prefere : example_qualification_3
EDIT :
To get column name and Comment
SHOW FULL COLUMNS FROM users

Querying a MySQL range using LIKE

I have a ref field in my mysql table that holds values that look like '0-0-at-3267-201411041356'. The first part (0-0-at-3267-) varies in length and values and the second part (201411041356) is a date/time that references a creation date/time. Everything that this code is used for is checked to see if it falls within a certain date/time period, such as between 201409010000 and 201508312359.
Normally I can simply explode the data and then measure but for this instance it would make it too clunky. So what I want to do is use the LIKE function in my query like so LIKE '%201411041356' but I want to use it with the > and < symbols, so the full query looking something like SELECT * FROM my_table WHERE ref LIKE > '%201409010000' AND ref LIKE < '%201508312359'
Any ideas would be most welcome! BTW, this has always been the way this data has been stored and there's lots of it so changing it is not an option.
Could you use between on a substring, so something like:
SELECT * FROM my_table WHERE SUBSTRING(ref,-12) BETWEEN '201409010000' AND '201508312359'
SELECT *
FROM my_table
WHERE SUBSTRING(ref,-12) BETWEEN '201409010000' AND '201508312359'`
would work better for substracting last 12 characters.
Because You wrote that first part may have different lenght so You have strip substring starting from the end.
So Your quwery may looks like:
SELECT * FROM table
WHERE
SUBSTRING('ref', -12) > $from
AND
SUBSTRING('ref', -12) < $to
If you just want to measure by date use:
left(right(ref, 12), 8)

phpAdmin shows rows, MySQL statement doesn't?

EDIT
Provided as requested is here how the Date column looks:
Jan 15, 2014
Jan 16, 2014
Aug 10, 2014
So what i am trying to achieve, is extract every row that contains Jan 2014, so i get every row for that month in that year.
Here is my PHP code that generates the query:
$monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE 'Date' LIKE " . "'{$monthYearString}'";
echo $query_current;
The echo gives me this query: SELECT * FROM table_name_here WHERE 'Date' LIKE 'Jan%2014'
Original question
I have a very weird issue here.
If i perform a search using phpAdmin provided by my hosting site, and search for rows that are like a certain date, it conjures up this SQL statement, and it finds 3 rows:
SELECT *
FROM `table_name`
WHERE `Date` LIKE 'Jan%2014'
BUT, when I try to do the same thing either using SQL statements in phpAdmin or my own code, it shows NOTHING? How come? It is 100% the same statement. Really can't understand how I can search using the built-in phpAdmin function, and then it generates that SQL statement, and then when I try to inject it myself, it just returns 0 rows instead of 3.
Hope it makes sense.
The difference between single quotes and backticks is important here. You have quoted your column name instead of using backticks. It should be:
SELECT * FROM table_name_here WHERE `Date` LIKE 'Jan%2014'
The backtick character (see the Date column in the query above) allows you to indicate it's a name rather than a string. In this case, if you didn't have these, you would get an error because Date is a reserved word. The backtick allows you to use reserved words for table and column names.
Where as the single quote means it's a string. In the case of your query, you were essentially searching for any records where the string 'Date' contains the string 'January 2014' which isn't possible and will always return zero results.
For more information, check out this SO question: When to use single quotes, double quotes, and backticks in MySQL
Your code should look like this:
$monthYearString = $month . "%" . $year;
$query_current = "SELECT * FROM {$table_omsaetning} WHERE `Date` LIKE '{$monthYearString}'";
echo $query_current;

Categories