mysql multiple queries with php - php

I am trying to have a search result for someones name exploded then the first name and last name each search against each field 'first' and 'last'.
But need to leave room what if someone search for first last midle name like = $who = James David Smith it will exploded it and search each of the names against the first column and the last column. Incase the user inputs the name lastname first or adds a middle name.
Here is what i have so far but im stuck. Help. Please.
<?
$search = explode(' ', $who);
$limit=verify($get['page'])?" limit ".($get['page']*10).",10":" limit 10";
$q="select * from users where (first IN('%$search[]%') or last IN('%$search[]%') or full_name LIKE '%".$get['who']."%') AND (city LIKE '%".$get['where']."%' or province LIKE '%".$get['where']."%') order by province";
$rows=get_recordset($q);
if(count($rows)){
foreach($rows as $row){
echo $q;
?>

I am not sure I got you but if what you mean is :
When you have 3 names then - check all names against all three fields (first,last,fullname).
When you have only 2 names then - check first name against first field and last name against last field
then this should get it done:
$search = explode(' ', $who);
if (count($search) >2) { // in case we do got a middle name -
$whereNameStringsArr = array();
foreach ($search as $val) {
$whereNameStringsArr[] = " first LIKE '%$val%'
OR last LIKE '%$val%'
OR full_name LIKE '%$val%' ";
}
$whereNameClause = implode(" OR ",$whereNameStringsArr);
} else { // in case we don't got a middle name
$whereNameClause = " first LIKE '%{$search[0]}%'
OR last LIKE '%{$search[1]}%' ";
}
$limit=verify($get['page'])?" limit ".($get['page']*10).",10":" limit 10";
$q="select * from users where ($whereNameClause)
AND (city LIKE '%".$get['where']."%' or province LIKE '%".$get['where']."%')
order by province
$limit";
$rows=get_recordset($q);
....
Of course - make sure you validate all data you get from user's input

So why not do a fuzzy search? When you explode the data, do something like this:
$name = $_POST['name'] // John Michael Smith
$first_name = substr($name, 0, strrpos($name, ' ')); //Returns everything before last space, ie John Michael
$last_name = strstr($name, ' '); //Returns everything after first space, ie John Michael
Now you just run the mysql query but set it to look for anything that contains the above values (substring search) using LOCATE:
$results = mysql_query("SELECT * FROM names
WHERE LOCATE(firstname, '$first_name') > 0 OR
LOCATE(lastname, '$last_name') > 0
ORDER BY lastname
I'll assume you know what to do with the results.
Quick Update, If you are worried about users entering in Last Name First Name Middle, or what have you, you could always use the above but do a locate on the entire string:
$results = mysql_query("SELECT * FROM names
WHERE LOCATE(firstname, '$name') > 0 OR
LOCATE(lastname, '$name') > 0
ORDER BY lastname
This will check both columns for any instances of any of the string. You should probably (after sanitizing the string, as was rightly suggested already) also remove any commas (but not hyphens) in case someone enters last,first or what have you. replace them with spaces and then reduce all multi-spaces to one space to be double sure.
Sorry about that. Here is the way to split the names (by blanks). There as a problem with my substr syntax:
$name = $_POST['name'] // John Michael Smith
$first_name = substr($name, 0, strrpos($name, ' ')); //Returns everything before last space, ie John Michael
$last_name = strstr($name, ' '); //Returns everything after first space, ie John Michael

Related

Mysql search like 2 words order

I would like to ask about an issue i'm facing.
I have the full name in 1 column stored, example: "John Doe".
But on perform a search for example:
SELECT * FROM client WHERE name LIKE '%Doe John%';
Result: 0 Rows.
If i switch to the exact match store in database it found a row.
SELECT * FROM client WHERE name LIKE '%John Doe%';
Result: 1 Row.
My question is, how to do to search in database without taking the order of word.
In OOP framework the code is:
$like = 'Doe John';
$this->db->select('*')->from('client')->like('name', $like)->get();
Also i tested this but i got the same result:
$this->db->select('*')->from('client');
if($this->containTwoWords($like)) {
$explode = explode(' ', $like);
foreach($explode as $exploded){
$this->db->like('name', $exploded);
}
} else {
$this->db->like('name', $like);
}
$this->db->get();
function containTwoWords($like){
if(strpos($like, ' ') !== false) {
return true;
}
return false;
}
If somebody passed trough this and has better solution i appreciate the sharing !.
One option for your example case would be to check for the first and last names separately:
SELECT * FROM client WHERE name LIKE '%Doe%' AND name LIKE '%John%'
If you have exhausted such tricks with the LIKE operator, then you can look into using MySQL's full text search capabilities.
Try something like this:
<?php
$search_term = 'john doe abc';
$keywords = explode(" ", preg_replace("/\s+/", " ", $search_term));
foreach($keywords as $keyword){
$wherelike[] = " name LIKE '%$keyword%' ";
}
$where = implode(" and ", $wherelike);
$query = "select * from client where $where";
echo $query;
//select * from client where name LIKE '%john%' and name LIKE '%doe%' and name LIKE '%abc%'
?>
Try this name like '%John%' and name like '%Doe%'
If you are wanting to explode the $like variable into first/last name (and you always expect 2 names, separated by a space), then this should work for you.
PHP has the built-in explode() method which does exactly what you are asking.
$like = "John Doe";
$name = explode(" ", $like);
// This created a 0-based array, meaning the first item as split
// by the space between John and Doe is given the array index of 0.
// $name[0] = John
// $name[1] = Doe
So in practice with MySQL that could be used as the following:
$query = "SELECT * FROM client WHERE name LIKE '%" . $name[0] . "%' AND name LIKE '%" . $name[1] . "%'";
For more information on the explode() function, check out the PHP manual at: http://php.net/manual/en/function.explode.php
Hope this helps!

Php mysql match (multiple) words in multiple columns with spaces

I am trying to figure out how and what function i need for my query, still not sure on using Like, concat or what part etc.
My situation is as such
1.) I have multiple columns(Country, City, State, Location)
2.) Only 1 search input
3.) Search input can be 1 word, or multiple words also ignore spacing(e.g. "Center City or CenterCity or Center City Philadelphia) etc
And it will return the rows that matches the words from the different columns.
Below is my attempt, but it is not returning anything at the moment. Thanks for your time
Php:
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
include 'connect.php';
if($_POST)
{
$searchaddress = ($_POST['searchaddress']);
$result=mysqli_query($con,"SELECT *
FROM Listing WHERE CONCAT(country,state,city,Location) LIKE '%$searchaddress%' AND Status='Open'") or die( mysqli_error($con));
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Without knowing your exact data and what $searchaddress is like, it is hard to tell why it fails.
You are talking about ingoring whitespaces, but just pass in a single searchtag - and the expression LIKE '%something something else%' will not ignore whitespaces.
If you want to have the least amount of results with all given words matching, you should put in more effort and use a or/and combination of searchtags / columns. You can do this programmatically.
Assuming, you have 2 keywords entered: Center Detroid, you basically want to generate the searchquery:
FROM Listing WHERE
(
country LIKE '%Center%' OR
state LIKE '%Center%' OR
city LIKE '%Center%' OR
Location LIKE '%Center%'
)
AND
(
country LIKE '%Detroid%' OR
state LIKE '%Detroid%' OR
city LIKE '%Detroid%' OR
Location LIKE '%Detroid%'
)
To achieve that, you need to know two things:
The fieldnames you want to search in.
The keywords.
Then, the following snippet will generate the where part as required:
$search = "Detroid City Center";
$keywords = explode (" ", $search);
$columns = array("country", "state", "city", "location");
$andParts = array();
foreach ($keywords AS $keyword){
$orParts = array();
foreach($columns AS $column){
$orParts[] = $column . " LIKE '%" . mysql_real_escape_string($keyword) . "%'";
}
$andParts[]= "(" . implode($orParts, " OR ") . ")";
}
$and = implode ($andParts, " AND ");
echo $and;
The example given in the array would produce
(
country LIKE '%Center%' OR
state LIKE '%Center%' OR
city LIKE '%Center%' OR
location LIKE '%Center%'
)
AND
(
country LIKE '%City%' OR
state LIKE '%City%' OR
city LIKE '%City%' OR
location LIKE '%City%'
)
AND
(
country LIKE '%Detroid%' OR
state LIKE '%Detroid%' OR
city LIKE '%Detroid%' OR
location LIKE '%Detroid%'
)
This will Match ANY row, where Center, City or Detroid is appearing AT LEAST ONCE in ONE of all (search-)fields per row.
Updated answer for searching each word in the address fields:
$searchaddress = "some address to find";
$address_parts = explode(" ", trim($searchaddress));
$sql_parts = array();
foreach($address_parts as $part) {
$sql_parts[] = 'full_address LIKE "%'.$part.'%"';
}
$query = 'SELECT *, CONCAT(country,state,city,Location) AS full_address FROM Listing WHERE `Status` = "Open" HAVING '.implode(' OR ', $sql_parts);

PHP need help to filter a loggfile

So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";

error on query , trying to make a search by keywords

i have a variable and an user_name i want to search on a string(function_description) of the user_name for it
whats wrong with this :
$function_keywords = mysql_real_escape_string($_POST['function_keywords']);
if($function_keywords=="" || empty($function_keywords)){
redirect("show.php?functions=PHP");
}
//trim whitespace from the stored variable
$trimmed = trim($function_keywords);
//separate key-phrases into keywords
$trimmed_keywords = explode(" ",$trimmed);
// Build SQL Query for each keyword entered
foreach ($trimmed_keywords as $trimm){
// MySQL "MATCH" is used for full-text searching.
//this code is ebv weird , should check out soon!
$query = "SELECT *
FROM functions
WHERE isEnabled=1 AND isPrivate=0
AND function_description LIKE '{$trimm}'
AND user_name='{$user_name}'
";
// Execute the query to get number of rows that contain search kewords
$results=mysql_query ($query,$connection);
as far as "like" syntax goes you have to use the '%' symbol. if you query for
select * from table where column like '%yourkeyword%'
then it returns any rows with 'yourkeyword' inside the table column.
your statement will be true only if the column = 'yourkeyword'
That's highly inefficient. If someone puts in 5 keywords, you'd be running the search 5 times and getting 5 sets of results. Try something more along these lines:
$words = $_POST['function_keywords'];
if ($words == '') {
... abort ...
}
$parts = trim(explode(' ', $words));
$clauses = array();
foreach($parts as $part) {
$clauses[] = "function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause = implode(' OR ' , $clauses);
$sql = "SELECT .... WHERE (isEnabled=1) AND (isPrivate=1) AND (user_name='$user_name') AND ($clause)";
$result = mysql_query($sql) or die(mysql_error());
This'll build up a long series of or statements for each keyword specified, and run the whole thing as a single query.
To see if the function_description contains the keyword you need to use '%' which stands for anything much the way '*' does in unix. Try function_description LIKE '%{$trimm}%'

php - Insert data from checkbox array into MySQL

I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:
<div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:
regid | psc_1 | psc_2 | psc_3 | ...
My code:
if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = #each ($boxes)) {
$camp_string .= "'$camp',";
}
}
// The above to create a comma separated string
$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma
$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.
I'm not sure what I'm missing.
--
Update#1 (in reference to a comment below)
if(!empty($_POST['camps'])) {
$box=$_POST['camps'];
while (list ($key,$val) = #each ($box)) {
$camp_totals += $campcost[$val];
echo "$campdesc[$val] - $$campcost[$val]";
}
}
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:
// print_r($_POST);
array(
'regID' => 1,
'camp_filmore' => 1,
'camp_greenwald' => 1
'camp_idunno' => 1
);
From there it's fairly simple to build your query:
$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
"VALUES (" . implode(array_values($_POST), ", ").")";
You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.
A nice trick to remove the trailing comma would be.
$camp_string = rtrim($camp_string,',');
Anyway your query is not formated correctly.
INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')
You cannot have single quotes in the first bracket
I think you should be looking at implode and you can easily add addition strings to it...
so e.g.
$comma_seperated = implode(',', $boxes);
$subscribed = $regid . ',' . $comma_seperated;

Categories