how can i search data in php using explode by sql query? - php

My database has row with a column like
data1+data2+data3+data4
How can i search specific value by sql query in php?
For example data2?
The +s separate each data point.

Why don't you try something like below:
SELECT (data1+data2+data3+data4) AS total
FROM Table
WHERE total LIKE '%YOUR_QUERY%'
Now you can use the index total

$lcSearchVal = "data1+data2+data3+data4";
$lcSearchVal = explode( '+', $lcSearchVal );
$sql = 'SELECT * FROM tablename WHERE (';
$data_array = array();
foreach( $lcSearchVal as $lcSearchWord )
{
$data_array[] = 'fieldname LIKE "%'.$lcSearchWord.'%"';
}
$sql .= implode(' OR ', $data_array).')';
print $sql;

Related

How to search for multiple keywords using sql search

I have a current SQL search query that lets users enter keywords to search for my SQL database. At the moment, the search will work with multiple words, but will show all results for either keyword. If you type in "Ford Mustang" it will show all results that have either "Ford" or "Mustang", but I need it to only show results that show both "Ford" and "Mustang".
What I have tried is below
public function getProductByName($name){
$stmt = $this->pdo->prepare('SELECT * FROM tbl_products WHERE name REGEXP :names');
$names = "[[:<:]](" . str_replace(" ", "|", $name) . ")[[:>:]]";
$stmt->execute(array('names' => $names));
return $stmt;
}
maybe this what you're looking for
select * from example where name like "%mustang%ford%"
You can write the query
select * from tbl_products where name like "%Mustang%" and name like "%ford%";
PHP code
//you may split search string like
$searchArray = explode(' ', $name);
//for loop for preparing the query
$query = 'SELECT * FROM tbl_products WHERE ';
$searchParams = array();
$conditions = [];
for($searchArray as $searchStr){
$conditions[] = 'name like ?';
$searchParams[] = "%$searchStr%";
}
//attach the conditions
$query .= implode(" and ", $conditions);
//execute the query
$stmt = $this->pdo->prepare($query);
$stmt->execute($searchParams);

MySqli query like any values in a PHP array

I have a PHP array containing values and I want to query the database to find any results where the ItemName contains any of the values in the array.
$current_item = 'Big Fancy Red Car';
$words = explode(' ',$current_item); // Array of words to search
And the query:
SELECT ID FROM store_accessories WHERE ItemName LIKE '%$words%'
How do I select the ID of any items in the table whose ItemName contains any of the values in the $words array?
You can do it like this:
First explode the value into an array:
$terms = explode(' ', $search_term);
Loop the array to add the LIKE
foreach ($terms as $term) {
$term = mysql_real_escape_string($term);
$likes[] = "field LIKE '%$term%'";
}
Add to the query:
$sql = "select * from table where";
$sql .= implode(' OR ', $likes);
You can get the LIKE like this directly, also substituting ' with '' and escaping _ and %:
$field = "ItemName";
$like = "$field LIKE '%".str_replace(
array("'" , "_" , "%" , " " ),
array("''", "\\_", "\\%", "%' OR $field LIKE '%"),
$currentItem)."%'";

Variable sql query depending on number of search parameter

I need to do a sql query in php for search some entries (so using WHERE). But the field used to search could be of variable number.
I have a page with a search form, with 4 Field. It sends via POST the fields to a search.php that make a query:
$gomme_sql = $data->query("SELECT * FROM table WHERE parameter1 = '$_POST['name1']' AND parameter2 = '$_POST['name2']' ORDER BY id ASC");
But I don't know which field are filled. So, if I don't enter anything in field1 from the search form, I shouldn't have parameter1 = '$_POST['name1']' in the WHERE query.
Have you any idea how to obtain this?
Thank you
You can check the post data before appending that clause to the query in a way like this:
edit: adding additional check:
$sql="select something from someTable ";
if(!empty($_POST['name1']) || !empty($_POST['name2'])) // add as many as you like
{
$sql.=" where ";
if(!empty($_POST['name1']))
{
$sql.="parameter1= $_POST['name1']";
}
// etc etc...
}
$sql.=" ORDER BY id ASC";
and so on.
Having said that, please, please use prepared statements with this sort of input from the user. This is SUPER open to sql injection. Please do read this: How can I prevent SQL injection in PHP?
You can write generic sql select function like this , if you need more complex SQL just modify it.
<?php
function sqlSelect($table, $sel, $wh = '', $groupby = '', $order = '', $add = '') {
$tb = $table;
if (is_array($table)) {
$tb = implode(',', $table);
}
if ($wh) {
if (is_array($wh)) {
$w = array();
foreach ($wh as $k => $v) {
$v = mysqli_real_escape_string($v);
if (is_null($v))
$w [] = "$k=null ";
else
$w [] = "$k ='$v'";
}
$wh = 'where ' . implode(' and ', $w);
}else {
$wh = "where $wh";
}
}
if ($groupby)
$groupby = "group by $groupby";
if ($order)
$order = "order by $order";
$sql = "select $sel from $tb $wh $groupby $order $add ";
return $sql;
}
//set _GET as this is console test
$_GET['name1']='Bob';
$where = array(
'name1'=>$_GET['name1']
);
echo sqlSelect('sometable' , '*' , $where) ."\n";
// select * from sometable where name1 ='Bob'
//or some complex stuff
echo sqlSelect('persons', "age,status" , array('name'=>'Maria' , 'likes'=>'PHP') , null, 'age' , 'limit 20');
//select age,status from persons where name ='Maria' and likes ='PHP' order by age limit 20

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Create SQL statement in PHP function using an Array

I am creating a PHP function that will take some values, one of which is an array, that I need to use in a MySQL query.
I am creating the array as follows:
$newsArray = createArticleArray(array(2,20,3),5);
Then the function looks something like this (cut down for readability)
function createArticleArray($sectionArray = array(1),$itemsToShow)
{
$SQL = "
SELECT
*
FROM
tbl_section
WHERE
(tbl_section.fld_section_uid = 2 OR tbl_section.fld_section_uid = 20 OR tbl_section.fld_section_uid = 3)
ORDER BY
tbl_article.fld_date_created DESC LIMIT 0,$itemsToShow";
}
The section tbl_section.fld_section_uid = 2 OR tbl_section.fld_section_uid = 20 OR tbl_section.fld_section_uid = 3 is where I need to use the array values.
Basically I need to loop through the values in the array making up that part of the query, however I am having a little problem on how to show or not show the "OR" bits of it as there might be only 1 value or as many as I need.
I was thinking of something like this:
foreach($sectionArray as $section)
{
$sqlString = $sqlString . "tbl_section.fld_section_uid = $section OR";
}
but I don't know how to work out if to put the "OR" in there.
Use implode.
$conditionParts = array();
foreach($sectionArray as $section){
$conditionParts[] = "tbl_section.fld_section_uid = $section";
}
$sqlString .= implode(' OR ', $conditionParts);
This solution answers your question and show you how to use the implode function, but for your specific case you should really use the IN operator.
$sqlString .= "tbl_section.fld_section_uid IN(".implode(',', $sectionArray).")";
One solution is to put an extraneous 0 at the end to consume the final "OR" without any effect. The query parser will just remove it: A OR B OR C OR 0 is turned into A OR B OR C.
Another solution is to use implode to insert the OR:
$sqlString = "tbl_section.fld_section = "
. implode($sectionArray," OR tbl_section.fld_section_uid = ");
Of course, the correct solution is just to use IN:
"WHERE tbl_section.fld_section_uid IN(".implode($sectionArray,',').")";
The query can be made simpler and easier to generate if you use WHERE <column> IN (value1,value2,...) syntax.
Use PHP's implode to produce the (value1,value2,...) part:
$SQL .= ' WHERE tbl_section.fld_section_uid IN (' . implode(',', $array) . ') ';
Yields something like this:
SELECT
...
WHERE tbl_section.fld_section_uid IN (2,20,3)
...
Use PDO's prepare method: http://uk3.php.net/manual/en/pdo.prepare.php
$statement = $pdo->prepare("
SELECT
*
FROM
tbl_section
WHERE
(tbl_section.fld_section_uid = ? OR tbl_section.fld_section_uid = ? OR tbl_section.fld_section_uid = ?)
ORDER BY
tbl_article.fld_date_created DESC LIMIT 0,$itemsToShow");
$statement->execute( $sectionArray );
function createArticleArray($sectionArray = array(), $itemsToShow) {
$conditions = array();
for ($i = 0, $s = count($sectionArray); $i < $s; ++$i) {
$conditions[] = 'tbl_section.fld_section_uid = ' . (int) $sectionArray[$i];
}
$SQL = 'SELECT * FROM tbl_section WHERE ' . implode(' OR ', $conditions) . ' ORDER BY tbl_article.fld_date_created DESC LIMIT 0, ' . (int) $itemsToShow;
}

Categories