Get Value into an Array on Form Submission - php

Currently i am getting the value like this...
$property_buildingorlocation = ($_GET['buildingorlocation']);
Some times the user will input......
buildingname, areaname, cityname (array size to be 3)
arename, cityname (array size to be 2)
cityname (array size to be 1)
hence there will be 2 commas, 1 comma or no comma.
I want to get the data into array, either dynamically set the size of the array depending on number of inputs or commas (sizes mentioned above)
next if array size is 3, then i want to search in three mysql columns (of choice) with an and operator
if array size is 2 then i want to search in two mysql columns (of choice) with an and operator
if array size is 1 then search in 1 mysql column
i know i am pushing it with such an open question, but i need help... i have been at it since morning can't figure it out....

Put data into array
$searchparams=explode(',',$property_buildingorlocation);
$searchparams=('trim',$searchparams);
Count number of elements
$searchparamscount=count($searchparams);
Do your logic using switch
switch ($searchparamscount) {
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
}

Finally ended up using the logic below... it is working.
if (!empty($property_buildingorlocation)) {
$searchparams = array_map('trim', explode(',', $property_buildingorlocation));
$searchparamscount=count($searchparams);
// If Property Buildingname, Areaname and City are given
if ($searchparamscount == 3) {
$wheres[] = 'property_buildingname LIKE :property_buildingname AND property_areaname LIKE :property_areaname AND property_city LIKE :property_city';
$params[':property_buildingname'] = $searchparams[0];
$params[':property_areaname'] = $searchparams[1];
$select7 = $con->prepare("SELECT city_id, city_name from tbl_city WHERE city_name LIKE (:property_city)");
$select7->setFetchMode(PDO::FETCH_ASSOC);
$select7->bindParam(':property_city', $searchparams[2], PDO::PARAM_STR);
$select7->execute();
while($data7=$select7->fetch()){
$searchparams[2] = $data7['city_id'];
}
$params[':property_city'] = $searchparams[2];
// If Property Areaname and City are given
} else if ($searchparamscount == 2) {
$wheres[] = 'property_areaname LIKE :property_areaname AND property_city LIKE :property_city';
$params[':property_areaname'] = $searchparams[0];
$select7 = $con->prepare("SELECT city_id, city_name from tbl_city WHERE city_name LIKE (:property_city)");
$select7->setFetchMode(PDO::FETCH_ASSOC);
$select7->bindParam(':property_city', $searchparams[1], PDO::PARAM_STR);
$select7->execute();
while($data7=$select7->fetch()){
$searchparams[1] = $data7['city_id'];
}
$params[':property_city'] = $searchparams[1];
}
// If Property City is given
else if ($searchparamscount == 1) {
$wheres[] = 'property_city LIKE :property_city';
$select7 = $con->prepare("SELECT city_id, city_name from tbl_city WHERE city_name LIKE (:property_city)");
$select7->setFetchMode(PDO::FETCH_ASSOC);
$select7->bindParam(':property_city', $searchparams[0], PDO::PARAM_STR);
$select7->execute();
while($data7=$select7->fetch()){
$searchparams[0] = $data7['city_id'];
}
$params[':property_city'] = $searchparams[0];
}
}

Related

MYSQL select display matching and non matching records

I have a list of strings all separated by a new line. I need to match these strings with the value in a column in one single table. The problem is I need to display non-matching records as a defined value, example "not found" so the output remains the same length as the input and the results all remain in the same order.
Example Input
apple
orange
pear
banana
Desired Output
apple exists
orange not found
pear exists
banana exists
Is it possible to assign a custom value to records not found as well as display records found in a single statement?
Info seems to suggest I can create a statement using IFNULL to return non-matching records, I have experimented with this but to no avail.
<?php
// Wrap strings for select statement
$strings = $_POST['mystrings'];
$regex = '~<[^>]+>(*SKIP)(*FAIL)|\b\w+\b~';
$strings_wrapped = preg_replace($regex, "'\\0',", $strings);
$strings_prepared = substr($strings_wrapped, 0, -1);
// Statement
$select = "select * from table where specific_row in ($strings_prepared)";
// Connect
$connect = mysqli_query($con, $select);
// Retrieve rows
while ($row=mysqli_fetch_array($connect)) {
$column1 = $row['column1'];
$column2 = $row['column2'];
$column3 = $row['column3'];
$column4 = $row['column4'];
$column5 = $row['column5'];
// Display results
$results = "$column1-$column2-$column3-$column4-$column5\n";
echo $results;
}
?>
The matching rows are returned without error. I just don't know how to display the non-matching rows as well.
This is the approach you can use:
// Statement
$select = "select * from table where specific_row in ($strings_prepared)";
// Connect
$connect = mysqli_query($con, $select);
// Retrieve rows
$founded = [];
while ($row = mysqli_fetch_array($connect)) {
$founded[$row['specific_row']] = $row['column1']; // or whatever
}
foreach ($strings_prepared as $string) {
if (!empty($founded[$string])) {
echo 'found';
} else {
echo 'NOT found';
}
}
You can use a subquery to create a derived table containing the names you want to search for, and join that with the table.
SELECT a.value, IF(b.specific_row IS NULL, 'not found', 'exists') AS found
FROM (
SELECT 'apple' AS value
UNION
SELECT 'orange'
UNION
SELECT 'pear'
UNION
SELECT 'banana'
) AS a
LEFT JOIN table AS b ON a.value = b.specific_row

How to get name from id in array using query?

I had array values as cause
Ex: $cause = $_REQUEST['cause'];
ie., $cause = 2,3,4
How to get that array value cause name from query
My table name is 'cp_cause'
How to get the 2,3,4 cause name from the above table.
My sample query model in thinkphp is
$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id = '".$cause."'");
i want the name of labour, health, women
If I get it right: you get comma separated Ids and want to query this?
SELECT * FROM cp_cause WHERE id IN (2, 3, 4)
PHP:
$cpCauses = $GLOBALS['db']->getAll("select * from cp_cause where id in('".$cause."')");
The result should be a list, containing the matching rows. But we do not know, what your getAll-Method returns!
Example: if result is an array, you can iterate:
foreach($cpCauses as $cause) {
echo $cause['cause_name'];
}
You need to create string like '2','3','4' for checking with MySql in clause.
For e.g.
<?php
$cause = array();
$cause[] = '2';
$cause[] = '3';
$cause[] = '4';
$sql_where = array();
foreach($cause as $values){
$sql_where[] = "'".$values."'";
}
$sql_where = implode(",",$sql_where);
$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id in '".$sql_where."'");
?>

update a table with an array just with one query

I have a table like this:
I receive an array like this:
$data = array(
array('m_id'=>1,'d_id'=>101,'available'=>0),
array('m_id'=>1,'d_id'=>102,'available'=>1),
array('m_id'=>1,'d_id'=>103,'available'=>1),
array('m_id'=>1,'d_id'=>104,'available'=>0),
array('m_id'=>1,'d_id'=>105,'available'=>0)
);
My question is how I can update the table just with one query like this:
$query = "UPDATE tbl_name SET available='".$data[0]['available']."'" WHERE conditon1";
I mean update table once instead of 5 query.
In pure MySQL, you could use a CASE expression in the UPDATE to handle this:
UPDATE tbl_name
SET available = CASE WHEN d_id = 101 THEN 0
WHEN d_id = 102 THEN 1
WHEN d_id = 103 THEN 1
WHEN d_id = 104 THEN 0
WHEN d_id = 105 THEN 0 END
WHERE d_id IN (101, 102, 103, 104, 105)
If, on the other hand, you wanted to iterate over your array of arrays and then issue UPDATE statements, you could try the following:
foreach ($data as $entry) {
$query = "UPDATE tbl_name SET available=".$entry['available']." WHERE d_id=".$entry['d_id'];
// execute $query ...
}
Possible duplicate of this one. In a nutshell - you need to use either CASE conditional or INSERT ... ON DUPLICATE KEY UPDATE construct.
Based on the data you have provided, where all rows reference the same columns, and always update the same column, you can create a simple CASE expression:
/* Mostly untested */
function update_array ($data)
{
if (empty ($data))
return NULL;
if (count ($data) === 1) {
/* Simple query for single update */
$mi = $data[0]['m_id'];
$di = $data[0]['d_id'];
$av = $data[0]['available'];
$sql = <<<_
UPDATE `tbl_name`
SET `available` = $av
WHERE `m_id`= $mi AND `d_id`= $di
_;
} else {
/* CASE WHEN query for multiple updates */
$sql = "UPDATE `tbl_name`\n SET `available` = \n CASE ";
foreach ($data as $d) {
$mi = $d['m_id'];
$di = $d['d_id'];
$av = $d['available'];
$sql .= "WHEN `m_id`=$mi AND `d_id`=$di THEN $av\n ";
}
/* Never forget the ELSE clause! */
$sql .= "ELSE `available`\n END\n";
}
return $sql;
}
This test program:
$data = array(
array('m_id'=>1, 'd_id'=>101, 'available'=>0),
array('m_id'=>1, 'd_id'=>102, 'available'=>1),
array('m_id'=>1, 'd_id'=>103, 'available'=>1),
array('m_id'=>1, 'd_id'=>104, 'available'=>0),
array('m_id'=>1, 'd_id'=>105, 'available'=>0)
);
echo update_array ($data);
outputs:
UPDATE `tbl_name`
SET `available` =
CASE WHEN `m_id`=1 AND `d_id`=101 THEN 0
WHEN `m_id`=1 AND `d_id`=102 THEN 1
WHEN `m_id`=1 AND `d_id`=103 THEN 1
WHEN `m_id`=1 AND `d_id`=104 THEN 0
WHEN `m_id`=1 AND `d_id`=105 THEN 0
ELSE `available`
END
Note:
Never forget the ELSE clause in a CASE WHEN update. If you do, then all the non-matching rows will be overwritten with a blank value.
This code blindly assumes that the data contains the expected indexes, and that the data is of the appropriate type.
Some say that you should include a WHERE clause to limit the number of rows to be updated for performance reasons. I haven't seen any data to back this up, but if it is a concern, then a simple improvement might be to narrow it down using the d_id column. Just add the follow at the end of the CASE WHEN query:
$ids = array_column ($data, 'd_id');
$sql .= ' WHERE `d_id` IN (' . implode (', ', $ids) . ")\n";
You still need the ELSE in the CASE expression because this WHERE clause is not guaranteed to exclude all the unwanted rows. Writing a complete WHERE clause will probably be much more complicated, depending on the exact nature of your data.

Search query and ordering by matches with my sql

Hi am currently stuck here, been doing research on how to write a mysql statement for a flexible search for products and order them by relevance on a project am working on have seen a few but wasn't helpful please i need help on how to make it work, my current method doesn't work, here it is.
User types in search field and submits "iPad 3rd Generation".
My script breaks the string into words like so.
$termsExploded = array_unique(explode(' ', $term));
No i use php to create an sql query based on the number of words found.
$i = 0;
foreach ($termsExploded as $word) {
if (strlen($word)>1) {
if ($i == 0) {
$where_query = $where_query." name LIKE '%".$word."%'";
}
else{
$where_query = $where_query." OR name LIKE '%".$word."%'";
}
$i++;
}
}
The where query variable now looks like this.
name Like '%ipad%' Or name Like '%3rd%' Or name Like '%Generation%'
Now search for the products ids like so.
$IDs = "SELECT DISTINCT id FROM store_items WHERE".$where_query;
I now create a second where query based on the IDs returned like so
$where_query_s = null;
$i = 0;
foreach ($IDs as $result) {
$returnID = $result->id;
if ($i == 0) {
$where_query_s = $where_query_s." id = ".$returnID."";
}
else{
$where_query_s = $where_query_s." OR id = ".$returnID."";
}
$i++;
};
Now i select the products again based on the distinct IDs returned like so
$items = "SELECT * FROM store_items WHERE".$where_query_s;
Now this works to get the products but how can i sort it based on best match?
Assuming you want to order by the number of matches then build up another string as follows:-
ORDER BY IF(name Like '%ipad%', 1, 0) + IF(name Like '%3rd%', 1, 0) + IF(name Like '%Generation%', 1, 0) DESC
But this will be slow, and takes no account of indexing to improve performance nor of plural / singular (ie, it someone searches for 'flies' it won't rank 'fly' properly).
To put that more into code:-
$where_query = array();
$order_query = array();
foreach ($termsExploded as $word)
{
if (strlen($word)>1)
{
$where_query[] = " name LIKE '%".$word."%'"
$order_query[] = " IF(name Like '%".$word."%', 1, 0)"
}
}
$IDs = "SELECT DISTINCT id FROM store_items WHERE ".implode(' OR ', $where_query)." ORDER BY ".implode(' + ', $order_query)." DESC";
Arrange for your query to look like this:
select field1, field2, etc, count(*) records
from store_items
where blah blah blah
group by field1, field2, etc
order by records desc
If the table is MyISAM based or if it is InnoDB and the version is Mysql 5.6 or greater, then you can use full text search (see http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html)
effectively you want a query similar to
SELECT * FROM store_items WHERE MATCH (name) AGAINST ('iPad 3rd Generation')
ORDER BY MATCH (name) AGAINST ('iPad 3rd Generation')

How to separate the rows depending of the column's value witin two tables in CodeIgniter?

I have two tables: markers and markers_types.
markers
id, type_id, lat, lng
1 1 42.000 2.500
2 1 41.000 2.400
3 2 40.000 2.300
markers_types
id, name, image
1 TYPE1 type1.png
2 TYPE2 type2.png
How can I retrieve the rows from the DB correctly, so for example, if first row from markers have column type_id set to 1, I want to output an image from corresponding ID from the others table markers_types where markers.type_id is equal to markers_types.id ? Sorry for dumb question, but can't get it.
Here is my map_model.php:
class Map_model extends CI_Model{
...
function get_coordinates(){
$this->db->select('*');
$this->db->from('markers');
$query = $this->db->get();
if($query->result() < 1)
return false;
else{
$results = $query->result();
return $results;
}
}
}
And here is my app/controllers/map.php:
$dbresults = $this->map_model->get_coordinates();
foreach($dbresults as $item){
$marker = array();
$marker['position'] = $item->lat.','.$item->lng;
$marker['icon'] = base_url().'assets/img/ico/'.$item->image; // <-- I need to output here correct type image
$marker['infowindow_content'] = $item->description;
$this->googlemaps->add_marker($marker);
}
How can I mix them, so it will output appropriate image depending on the marker's type ?
I'am complete newbie at MySQL, so pls sorry in advance for that kind of basic question, I tried but didn't succeed to find out the right answer.
$query = $this->db->query("SELECT * FROM markers LEFT JOIN marker_types ON markers.type_id = markers_types.id");
// RETURNS AN ARRAY
$query->result_array();

Categories