SQL search using PHP arrays - php

How to search multiple fields in a MySQL database with a PHP array.
For example, search fields like place_name, admin_name1, and admin_name2 using an array of ["Cambridge","Massachusetts","US"] with using the wildcard %
Below is the exact structure of database

Imagining your array index names are the same as your table column names:
$query = "select * from tableName";
$arrCount = count($arrName);
$i=1;
if($arrCount) > 0){
$query .= " where";
foreach($arrName as $key->$val){
$query .= $key." LIKE '%".$val."%'";
if($i <= $arrCount)
$query .= " AND";
$i++;
}
}
Then run the query!

$array = ["Cambridge","Massachusetts","US"];
$list = implode(",", $array);
Then select:
... WHERE place_name IN($list) OR admin_name1 IN($list) OR admin_name2 IN($list)

Try this
$fields = array("place_name", "admin_name1", "admin_name2");
$kwd = array("Cambridge","Massachusetts","US");
$condition = array();
$n = 0;
foreach($fields as $field){
$condition[] .= $field." LIKE '%".$kwd[$n]."%'";
$n++;
}
$condition = implode(" AND ", $condition);
echo $qry = "SELECT * FROM `table` WHERE ( ".$condition." )";

Related

Construct SELECT WHERE query with array_keys and array_values in PHP

I was able to use array_keys and array_values to do an INSERT for MySQL:
$columns = implode(", ", array_keys($cmd_array));
$escaped_values = array_map( $dbc->real_escape_string, array_values($cmd_array));
$values = implode(", ", $escaped_values);
$query = "INSERT INTO cmd ($columns) VALUES ($values)";
Is there a feature to do the same thing for SELECT WHERE like this?
$query = "SELECT * FROM cmd WHERE ($columns) = ($values)";
You have to specify more than one condition using the AND or the OR operators.
So you can do this with a simple loop
$select_query = "SELECT * FROM cmd WHERE ";
$temp_array = array();
foreach($cmd_array as $key=>$val){
$temp_string = $key ." = ".$val;
array_push($temp_array, $temp_string);
}
$select_query .= implode(" AND ", $temp_array);

PHP SQL Query for autocomplete

I have a MySqL DB with a table of Properties NAMES(can be more then one word) and I want to run a query to get results for the user text inputs to use for an autocomplete field.
The query I currently use is:
$query = "SELECT * FROM table WHERE LOWER(name) LIKE '%$value%' LIMIT 7";
But it is not good enough.
I tried splitting the input $value but for some reason is not working:
$values = explode(" ", $value);
$str = "";
for($i = 0; $i < count($values); ++$i)
{
if( $i == 0)
$str .= "LOWER(name) LIKE '%&$values[$i]%' ";
else
$str .= "AND LOWER(name) LIKE '%$values[$i]%' ";
}
$query = "SELECT * FROM table WHERE ". $str . " LIMIT 7";
Do you have any suggestions?
TX in advance.
Do OR instead of AND in your query:
$str .= "OR LOWER(name) LIKE '%$values[$i]%' ";

Search more then one MySql table in Mysql Database PHP

I have a database have 20 tables I want to search all of these I got stuck that how can I search this and solve this query help is very appreciated. Like:
table1
table2
table3
table4
and so one. This is my script.
<?php
if(isset($_GET["search"]))
{
$condition = '';
//$query = explode(" ", $_GET["search"]);
$query = explode(" ", $_GET["search"]);
foreach($query as $text)
{
$condition .= "`title` LIKE +'%".mysqli_real_escape_string($connect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM countries2 WHERE " . $condition;
$result = mysqli_query($connect, $sql_query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row["title"].'</td></tr>';
}
}
else
{
echo '<label>Data not Found</label>';
}
}
?>
Try with this
sql_query = "SELECT * FROM `countries`,`countries2` WHERE " . $condition;
i have noticed that you are making a search directory or something like this.
you may use FULLTEXT SEARCH with operators and Stemming
after this your query will look like this.
implement as per your requirement ;).
(SELECT * FROM table1 WHERE(col1,col2,clo3) AGAINST(."$search".) IN NATURAL LANGUAGE MODE)

How can I query to mysql with ARRAY in condition

A have names of rows in array
$arr = array(fir, seco, third);
how can I query mysql like:
$query = "SELECT * FROM $table where fir=0 and seco=0 and third=0";
but using array.
and
$query = "update $table SET fir='$ma', seco='$ma', third='$ma'";
but using array.
For search you can fire below query -
$str = implode(",", $arr);
$query = "SELECT * FROM $table where 0 IN ($str)";
But for update you have to use query what you have written.
easy,
$arr = array(fir, seco, third);
for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and " + arr[i] + "=" + $ma;
}
This is what I would do...
$fir = $arr[0];
$seco = $arr[1];
$third = $arr[2];
$query = "UPDATE $table SET $fir = '$ma', $seco = '$ma', $third = '$ma'";
Not sure if there is a more optimal answer, but you could use a for loop to create the SQL statement:
<?php
$arr = array(fir, seco, third);
$query = "SELECT * FROM $table where ";
$count = count($arr);
for($i=0;$i<$count;$i++){
$query .= ($i==$count-1) ? "$arr[$i]=0" : "$arr[$i]=0 and ";
}
echo $query;
?>
Echoes SELECT * FROM $table where fir=0 and seco=0 and third=0. You can do the same with the UPDATE SQL statement.
Update
Also, you could implode the array, like in Suresh Kamrushi's answer, and use the following code:
<?php
$arr = array(fir, seco, third);
$str = implode(',',$arr);
$query_one = "SELECT * FROM $table WHERE ($str) = (0,0,0)";
echo $query_one;
?>
The UPDATE query would still need a for loop though, I think.

Checking for empty fields in mysql table

I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...

Categories