Instead of PHP In, How can I do And? - php

I'm looking at an application where we can tag items. Currently, if we search for more than 1 tag, then results with content for with either tag appears. it is inclusive rather than exclusive. This is the code which causes it:
//app/content/Search/Mysql/Query.php:232
$tagWhere = array( $itemsOnlyTagSearch . \GDP\Db::i()->in( 'index_item_index_id', $tagIds ) );
For example, if I search for the tags "windows" and "ios" then content with windows OR iOS tagged come back.
I want to update that line of code so only content with BOTH "windows" and "ios" tagged come back. How can I do that?

What library are you using to construct your queries?
Right now, your query is something like
SELECT * FROM TABLE_NAME WHERE index_item_index_id in (id1, id2)
where id1 and id2 refers to the tagIds.
You need to modify your query to use multiple where column = value expressions, e.g.
SELECT * FROM TABLE_NAME WHERE index_item_index_id = id1 AND index_item_index_id = id2)
It depends on your ORM / Query Class how to construct such SQL query in PHP.

Related

How can I replace column name with the comments given in table's field definition

I want to change the column name with a descriptive name, like in my table I have a field name "job_title",
I want to replace this heading with "what is your job title", and job_description with "Describe your job description"
For accomplishing this task I can use Aliasing but I want to change the column names dynamically instead of hard code.
I have described these questions in the comments section of the individual field of the table and I am trying to fetch these comments from the database and display comments of the field as the column heading but couldn't accomplish it.
This is my PHP code:
$sql_getcolumns="select * interview_col_comments where table_name ='interview'";
$result = $mysqli->query($sql_getcolumns);
echo "<table>";
echo "<tr>";
while($row = mysqli_fetch_array($result))
{
echo "<th>".$row[0]."</th>";
}
echo "";
I also tried to find a way in the PhpMyAdmin interface if I labeled column names and retrieve labels using a query in PHP
but didn't find this option in the SQL interface.
Is there another Approach using PHP, or SQL Which I can use to give columns of the table descriptive names?
One approach can be make an array in php like below.
<?php $comment=[
'job_title' => "what is your job title",'job_description'=>"Describe your job description"];
echo "<th>".$comment[$row[0]]."</th>";
?>'
Another approach can be make a another table with column description in mysql and replace on run time.
id|column_id|description
1|job_title|"what is your job title"
2|job_description|"Describe your job description"
What you are looking for is called "localization".
There are many ways to do that.
I usually ALSO prefer to keep this information tightly wired to the database I'm working with, so what I did is:
I used the Database Column's Comment field to provide meta-information.
For example, a columns comment can look like this:
#required #de=Vertragsnummer #en=Contract_Number #search
Now, using the following query, I can retrieve the comments, and build a ColumnMetadataObject out of the information using some regex / string operations.
SELECT
c.`TABLE_NAME`,
c.`COLUMN_NAME`,
c.`COLUMN_COMMENT`,
t.`TABLE_COMMENT`
FROM
information_schema.columns c left join
information_schema.TABLES t ON
c.TABLE_NAME = t.TABLE_NAME and
c.TABLE_SCHEMA = t.TABLE_SCHEMA
where
c.`table_schema` = 'MyDatabase'
After parsing the information and providing the required Meta-Data-Objects, My header output just looks like this:
<?=$db->getColumnMetdata('contractNumber')->getHeader($_SESSION["user_language"]));?>
Code in between can vary in complexity. My ColumnMetadata also contains other information like required, searchable, length, possible foreign keys, and much more. That part would be up to you - just for localize headers, an associative Array would work as well. something like :
["de"] => {
"table1.contractNumber" => "Vertragsnummer"
"table1.Id" => "Id"
}

How to use wildcard in PHP query

I have a table filter feature in PHP club membership webpage. I made it so the user can filter the table and choose which members to display in a table. For example, he can choose the country or state where the member is from then hit display. I am using a prepared statement.
The problem is, I need to use wildcards to make the coding easier. How do I use a wildcard in PHP MySQL query? I will use wildcards for example if the user does NOT want specific country but instead he wants to display all members from all countries.
I know not specifying the WHERE country= will automatically select any countries but I already constructed it so each controls like the SELECT control for country already has a value like "CA" or "NY" and "*" if the user leaves that control under "All Countries". This value when submitted is then added to the query like:
$SelectedCountry = $_POST["country"];
sql .= " WHERE country=" . $SelectedCountry;
But the problem is using WHERE country=* doesn't seem to work. No errors, just doesn't work. Is "*" the wildcard in PHP MySQL?
The * is not a wildcard in SQL when comparing with the = operator. You can use the like operator and pass a % to allow for anything.
When doing this the % should be the only thing going to the bind. $Bind_country = "'%'"; is incorrect because the driver is already going to quote the value and escape the quotes. So your query would come out as:
WHERE country ='\'%\''
The = also needs to be a like. So you want
$bind_country = '%';
and then the query should be:
$sql = 'select * from table where country like ?';
If this were my application I would build the where part dynamically.
Using * in WHERE clause is not right. You can only give legit value. For example:
// looking for an exact value
SELECT * FROM table WHERE column = 'value'
// you can also do this when looking for an exact value
// it works even if your $_POST[] has no value
SELECT * FROM table WHERE column = 'value' OR '$_POST["country"]' = ''
// looking for a specific or not exact value
// you can place % anywhere in value's place
// % denotes the unknown characters of the value
// it works also even if your $_POST[] has no value
// results will not be the same when you're using AND or OR clause
SELECT * FROM table WHERE column LIKE '%val%'
I think below link can solve your problem.
Just have a look and choose what you need.
Thanks.
http://www.w3schools.com/sql/sql_wildcards.asp

MySQL Query- Issue while using like operator

I have a table names and in that table there is a field info data is like this:
ID info
1 'alpha,romeo,ciera,delta'
2 'testing,temp,total'
I am trying to create a select query.
select * from names where info like '%$var%'
$var is data from php.
Problem is i want exact match. If i use above query and in $var if
data is rome then it also return row of romeo.
one more example-
data in table is testing,temp,total
user input data is test then it also return testing
i tried
select * from names where info like '$var%'
and
select * from names where info like '%$var'
but it didn't return data as i expected.
Please advise how can i achieve this.
Note- : This is an example i am not using mysql as its depreciated. I am using mysqli
Append , at begin and end of your target search string.
And then make sure your source string also has those ,
SQL Fiddle Demo
select *
from names
where concat( ',', info , ',') like
concat( '%,', $var, ',%')
The problem is this wont use any index. You should go for FULL TEXT search
Problem is i want exact match. If i use above query and in $var if data is rome then it also return row of romeo.
Don't use the LIKE operator, use exact match operator =
select * from names where info = '$var'
Use , in your query to use it as a delimiter and use multiple conditions to account for the "edge cases".
SELECT *
FROM names
WHERE
info LIKE '%,$var,%' OR
info LIKE '$var,%' OR
info LIKE '%,$var' OR
info = '$var'
If you have rows with info column:
alpha,romeo,ciera,delta
testing,temp,total
rome
foo,test,bar
berlin,paris,madrid,london,rome
venice,milano,rome,firence
black,crome
rome,fome,mome,kome,kome
Query with $var as "rome" will select:
rome
berlin,paris,madrid,london,rome
venice,milano,rome,firence
rome,fome,mome,kome,kome
But not:
alpha,romeo,ciera,delta
black,crome

Regex Replace in MySql Select query

I have this SQL query:
SELECT * FROM pages WHERE page_title = 'paul_mccartney'
But often in page_title the value is like 'paul_mccartney (musician)'. And in this case I get NULL back. I had the idea to regex replace everything which is between ( and ) including the ():
SELECT * FROM pages WHERE REPLACE(REGEXP('/\([^\*].*\)/U'), '', page_title) = 'paul_mccartney'
But it doesn't work. Is my idea possible or not? And how?
Although your question is about using RegEx but have you looked into MySQL fulltext search functions?
https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
https://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html
Using the following tutorials if you have a row that is like this:
Id title
1 paul_mccartney (musician)
Using the example SQL provided will return a result:
SELECT * FROM articles
WHERE MATCH (title) AGAINST ('paul_mccartney' IN BOOLEAN MODE)
You could try a LIKE and see how that works:
SELECT * FROM pages WHERE page_title LIKE '%paul_mccartney%'

MySQL select only using first word of variable

I am using php and mySQL. I have a select query that is not working. My code is:
$bookquery = "SELECT * FROM my_books WHERE book_title = '$book' OR book_title_short = '$book' OR book_title_long = '$book' OR book_id = '$book'";
The code searches several title types and returns the desired reference most of the time, except when the name of the book starts with a numeral. Though rare, some of my book titles are in the form "2 Book". In such cases, the query only looks at the "2", assumes it is a "book_id" and returns the second entry in the database, instead of the entry for "2 Book". Something like "3 Book" returns the third entry and so forth. I am confused why the select is acting this way, but more importantly, I do not know how to fix it.
If you have a column in your table with a numeric data type (INT, maybe), then your search strategy is going to work strangely for values of $book that start with numbers. You have discovered this.
The following expression always returns true in SQL. It's not intuitive, but it's true.
99 = '99 Luftballon'
That's because, when you compare an integer to a string, MySQL implicitly does this:
CAST(stringvalue AS INT)
And, a cast of a string beginning with the text of an integer always returns the value of the integer. For example, the value of
CAST('99 Luftballon' AS INT)
is 99. So you'll get book id 99 if you look for that search term.
It's pointless to try to compare an INT column to a text string that doesn't start with an integer, because CAST('blah blah blah' AS INT) always returns zero. To make your search strategy work better, you should consider omitting OR book_id = '$book' from your search query unless you know that the entirety of $book is a number.
As others mention, my PHP allowed both numerical enties and text entries from the browser. My query was then having a hard time with this, interpreting some of my text entries as numbers by truncating the end. Thus, my "2 Book" was being interpreted as the number "2" and then being queried to find the second book in the database. To fix this I just created a simple if statement in PHP so that my queries only looked for text or numbers. Thus, in my case, my solution was:
if(is_numeric($book)){
$bookquery = "SELECT * FROM books WHERE book_id = '$book'";
}else{
$bookquery = "SELECT * FROM books WHERE book_title = '$book' OR book_title_short = '$book' OR book_title_long = '$book'";
}
This is working great and I am on my way coding happily again. Thanks #OllieJones and others for your questions and ideas which helped me see I needed to approach the problem differently.
Not sure if this is the correct answer for you but it seems like you are searching for only exact values in your select. Have you thought of trying a more generic search for your criteria? Such as...
$bookquery = "SELECT * FROM my_books WHERE book_title LIKE '".$book."' OR book_title_short LIKE '".$book."' OR book_title_long LIKE '".$book."' OR book_id LIKE '".$book."'"
If you are doing some kind of searching you might even want to ensure the characters before the search key are found as well like so....
$bookquery = "SELECT * FROM my_books WHERE book_title LIKE '%".$book."' OR book_title_short LIKE '%".$book."' OR book_title_long LIKE '%".$book."' OR book_id LIKE '%".$book."'"
The % is a special char that looks for allows you to search for the chars you want to search for PLUS any characters before this that aren't in the search criteri... for example $book = "any" with a % before hand in the query like so, '%".$book."'"`` would return bothcompanyand also the wordany` by itself.
If you need to you can add a % to the end also like so, `'%".$book."%'"`` and it would do the same for the beginning and end of the search key

Categories