I have multiple ids separated by + in one field of a row in a table
Like : (123+21654+412+12387)
I need Only EXACT MATCHES, (e.g.: only "123" and not "123 & 12387")
My code is like this:
$var = $value['id'];
$result = mysqli_query($this->dbh, "SELECT id FROM table
WHERE id REGEXP '[[:<:]]$var[[:>:]]' ");
I have a problem with using a variable in REGEXP.
in case of :
$result = mysqli_query($this->dbh, "Select id FROM table
WHERE id REGEXP '^$id|[\+]$id' ");
it works, but it does not return only exact matches
PHP tip: "Interpolation" works these ways:
"...$var[...]..." treats that as an array lookup for $var[...].
Without [, $var is assumed to be a scalar.
"...{$var}[...]..." is what you need
This last example has braces {} to tell PHP to evaluate what is inside without being concerned about what follows. More common usage:
$var = 'abc';
// I want to generate "abc123"
$bad = "$var123"; // looks for variable 'var123'
$good = "{$var}123; // correctly yields "abc123"
Your second attempt can be fixed thus:
REGEXP '(^|\+)$id(\+|$)'
meaning:
At the beginning or after a +,
Find $id (after interpolating),
And stop with a + or the end of the string.
I'll go with :
$sql = "SELECT id FROM table WHERE id='123' OR id LIKE '123+%' OR id LIKE '%+123' OR id LIKE '%+123+%'";
The first condition will apply if you only have the value, the second if the field starts with the value, the third if the field ends with the value and the fourth if the value is in the middle of the field.
Related
I have an array in php containing strings, which I want to use in a query with Red Bean MySQL in the following manner:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
The problem is that the list is not being evaluated correctly no matter how I set the values in the array string, and the names abc, def, ghi are returned in the result. I've tried the following:
$someString = '\'abc\',\'def\',\'ghi\''
$someString = 'abc\',\'def\',\'ghi'
$someString = 'abc,def,ghi'
running the query in the SQL server manually works and I don't get those values returned, but running it within the php code with redbean is not working, and it seems that the list is not being interpreted correctly syntax-wise.
Can anyone shed some light on the matter?
Thanks to RyanVincent's comment I managed to solve the issue using positional parameters in the query, or more specifically, the R::genSlots function.
replaced the following:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
with:
$someArray = array('abc', 'def', 'ghi');
R::getAll("select * from table where name not in (". R::genSlots($someArray) .")", $someArray);
This creates a $someArray length positions for parameters in the query, which are then filled with the values in the second parameter passed to the getAll function.
Notice that in this case I used a set content array (3 variables) but it will work dynamically with any length array you will use.
Furthermore, this can also work for multiple positions in the query, for example:
$surnameArray = array('smith');
$arr1 = array('john', 'pete');
$arr2 = array('lucy', 'debra');
$mergedVarsArray = array_merge($surnameArray,$arr1);
$mergedVarsArray = array_merge($mergedVarsArray,$arr2);
R::getAll("select * from table where surname != ? and name in (." R::genSlots($arr1).") and name not in (". R::genSlots($arr2) .")", $mergedVarsArray);
This code will effectively be translated to:
select * from table where surname != 'smith' and name in ('john','pete') and name not in ('lucy', 'debra')
Each '?' placed in the query (or generated dynamically by genSlots() ) will be replaced by the correlating positioned item in the array passed as parameter to the query.
Hope this clarifies the usage to some people as I had no idea how to do this prior to the help I got here.
I have a form for users to enter some information. After the form being submitted, it should query a database with the values that the user entered.
My problem here is that if some of the values that the user entered are null, it should remove from the query.
This is my code:
if(isset($_POST['submit']))
{
include("../includes/header.php");
include ("../scripts/db/connect.php");
//Gets variables from $_POST
$negocio = $_POST['negocio'];
$imovel = $_POST['imovel'];
$distrito = $_POST['distrito'];
$concelho = $_POST['concelho'];
$freguesia = $_POST['freguesia'];
$query = "SELECT * FROM imoveis WHERE negocio = $negocio and imovel = $imovel and distrito = $distrito and concelho = $concelho and freguesia = $freguesia";
}
Imagine if $negocio, $imovel, $concelho and $freguesia are equal to null, the query should be:
$query = "SELECT * FROM imoveis WHERE distrito = $distrito;
How can I do this?
Generate your query string dynamcilly depending on which value are set
or not null, and than use that query
Run this code in a seperate file you will understand the point, after removing or adding comment to any variable, ($name,$street, $address or $qualification )
// you will see query will change depending on the set variable,
//I am using these name you can use any name for your variable
$name='my name';
//$address='some where on earth';
$street='this is my street';
//$qualification='i am very much qualified';
//now create the array only with the values which are not empty or not nul,
//I am using empty you can use null if you want with this example you can use any thing.
if(!empty($name)) $query_string_second_part[]=" AND name = '$name'";
if(!empty($address)) $query_string_second_part[]=" AND address = '$address'";
if(!empty($street)) $query_string_second_part[]=" AND street = '$street'";
if(!empty($qualification)) $query_string_second_part[]=" AND qualification = '$qualification'";
//hand type the first part for the query
$query_string_First_Part= "SELECT * FROM myTableName WHERE";
//Implode the array, if you want to see how it look like use echo,
$query_string_second_part= implode(" ", $query_string_second_part);
//as you can see we are adding AND with every value, so we need to remove the first AND
//with one space
//Make sure you give space in the second parameter. else it wont work means "" not correct but " " is correct
//Hint --> use one space in between the double qoutes
$query_string_second_part= preg_replace("/AND/", " ", $query_string_second_part, 1);
//Join the first and second part together to create a full query
$query_string=$query_string_First_Part.$query_string_second_part;
echo ($query_string);//see how our query look like at the moment
You can add an input null check to each clause. So for example where you do this:
distrito = $distrito
You might instead do this:
(distrito = $distrito or $distrito IS NULL)
or perhaps:
(distrito = $distrito or $distrito = '')
Depending on the data types, the actual input being used to build the query, etc. Might take some tweaking and debugging when manually building a query like this (I suspect using prepared statements with query parameters will make this cleaner, as well as more secure), but the idea is the same either way.
Basically you're instructing it to match the row based on the value, or match the row based on the lack of value. So for any given clause, if the supplied value is null/empty, then all rows match and the clause becomes moot.
I'm building a webpage that retrives data depending on a URL parameter.
There are two possible parameters.
1: id which is retrieved using $_GET['id']
2: name which is retrieved using $_GET['name']
When I am retrieving data using the id parameter it works like a charm since id is always a numerical value and never alphabetical text.
But when attempting to retrieve data using the name parameter I get no results.
The name parameter is checking the database for an article with the articles title being the parameter.
For example the name parameter in a URL would look like so:
http://example.com/safetyarticles/view.php?name=9-clues-to-solving-this-parameter-issue
And in the database the articles name would be: 9 Clues To Solving This Parameter Issue
I've already written some lines to remove the dashes in my url parameter to spaces and then capitalize each word to match the article name, but I'm not getting any results.
This is the code I have written:
$conn = getConnected("safetyArticles");
if(isset($_GET['id'])) {
$articleID = $_GET['id'];
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_id = $articleID");
$article = mysqli_fetch_array($articleQuery);
}
else if(isset($_GET['name'])) {
$articleName = $_GET['name'];
$articleName = preg_replace("/[\-]/", " ", $articleName); // Replace dashes in URL parameter with spaces
$articleName = ucwords($articleName); // Uppercase first letter of each word of URL parameter
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = $articleName");
$article = mysqli_fetch_array($articleQuery);
}
To my knowledge replacing the dashes with spaces and capitalizing each word should make the article_name in the database and $articleName match.
I did add a line of echo $articleName just to see what the output was and the result was 9 Clues To Solving The Mystery Of The Pilot Car which matches the title in the database but the results are not being pulled.
I copied this directly out of the database just to show that the titles are indeed the same: 9 Clues To Solving The Mystery Of The Pilot Car.
I'm at a loss since everything is matching up as it should.
you need '' around the variables in the query:eg '$articleName':
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");
$articleName in your query needs to be quoted like this : '$articleName'. eg
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");
I have pre parameters determining what is passed into my query. In one case I want to search for ALL UUIDs, and in another case I want to search for specific UUID numbers. I would like to do this in one query statement instead of breaking it into two seperate calls (like below)
example 1:
$uuidtosearchfor = "1234";
$query = "SELECT ID,name,UUID FROM table where active = 1 AND UUID ='$uuidtosearchfor'";
exmaple 2:
$query = "SELECT ID,name,UUID FROM table where active = 1";
so instead I want this:
if(rule1)
$uuidtosearchfor = "*"; // return everything
else
$uuidtosearchfor = "2134"; // return everything
$query = "SELECT ID,name,UUID FROM table where active = 1 AND UUID = '$uuidtosearchfor' ";
If you use LIKE instead of =, you can use % as wildcard. But LIKE isn't exactly the same as =.
With = you could construct the query as UUID=UUID. The downside is, you cannot use prepared statements and have to take care about escaping the parameter yourself.
Actually, I don't see how any of these makes your life easier. I'd rather construct the query such that the condition is not added if you want to match all uuids.
There's a mysql database that stores ids and names, when users are creating names with a form they can create existent names since unique ids are the ids such as:
d49f2c32f9107c87c7bb7b44f1c8f297 name
2fa9c810fbe082900975f827e8ed9408 name
what i want to do is saving the second "name" -> "name(1)" when inserting into database.
So far what I've got is this as the idea
lets say the name entered is 'name'
$input = 'name';
select the name we want to check from mysql database
mysql_query(SELECT * FROM `table` WHERE `name` = '$input');
if the result exists, then insert as $input.'(1)'
my question is what if name exists, and name(1) also exists, then how can i add the name(2) there...
You could return the number of people with that name in the database, then add 1 to that number.
SELECT COUNT(id) FROM table WHERE name LIKE '$input(%)');
$i = 1;
$sourceName = $name;
while( sql "SELECT COUNT(*) FROM table WHERE name = '$name'" ) {
$name = $sourceName.' ('.$i.')';
$i++;
}
At this point you have the final $name (with $i counting the iteration)
Something like this should do the trick:
SELECT * FROM table WHERE name = '$input' OR name LIKE '$input(%)'
Note that for this to work, you'd need to escape any percent signs in $input in the LIKE clause, otherwise they'll be treated as wildcards.
Use a regex that checks for integers between two parentheses at the end of the string. If there exists an integer, add 1 to it.
You could also attempt to do it the other way around, make name field unique and try to input it in a while loop, if it fails add ($i) and do $i++ every iteration.
//edit:
The problem with using solutions that do a like comparison is that you will get false positives, for instance $hi% will also count hippie. Which gives you unnecessary (1) additions!