How to get name from id in array using query? - php

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."'");
?>

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

Sum values with same id from a list of ids

I'm totally a begginer trying to get this done. I get a list of ids from a query as 1,2,3,4... then I need to SUM the values of a column named "total" where the id includes one of the ids listed.
//Total quoted
//$array_quos = $row3['quo_list'];
$array_quos = explode(',', $row3['quo_list']);
foreach ($array_quos as $qtid => $qt)
{
$qt = $db->query("SELECT total FROM exp.quo_main WHERE quo_id = '.$qtid.' ");
$total_quoted2 += $qt;
}

PHP/SQL: Faster Way to Combine Query Results

I'm joining data from two SQL queries and I'm wondering if there is a faster way to do this as a single SQL query because there is a lot of looping involved. I've got two queries that look for different string values in the "option_name" field:
$sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";
$sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";
Then I create two arrays:
//Process the 1st SQL query data into an Array
$result_array01 = array();
$j = 0;
while($r = mysql_fetch_assoc($result01)) {
if(!empty($r['option_value'])){
//User Id and Last Login
$result_array01[$j]['user_id'] = $r['user_id'];
$result_array01[$j]['last_login'] = $r['option_value'];
$j++;
}
}
//Process the 2nd SQL query data into an Array
$result_array02 = array();
$k = 0;
while($s = mysql_fetch_assoc($result02)) {
if(!empty($s['option_value'])){
//User Id and Stripe Customer Id
$result_array02[$k]['user_id'] = $s['user_id'];
$result_array02[$k]['cust_id'] = $s['option_value'];
$k++;
}
}
And finally, I combine the arrays:
//Combine the SQL query data in single Array
$combined_array = array();
$l = 0;
foreach($result_array01 as $arr01){
// Check type
if (is_array($arr01)) {
//mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");
foreach($result_array02 as $arr02){
// Check type
if (is_array($arr02)) {
//Check if User Id matches
if($arr01['user_id'] == $arr02['user_id']){
//Create Array with User Id, Cust Id and Last Login
$combined_array[$l]['user_id'] = $arr01['user_id'];
$combined_array[$l]['last_login'] = $arr01['last_login'];
$combined_array[$l]['cust_id'] = $arr02['cust_id'];
$l++;
}
}
}
}
}
Why you doing in two different queries?
Use mysql IN('val', 'val2');
$sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date'
union all
SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
But using OR/AND will your help you in your case , I didnt see at first that you want combined same table. I didnt delete my answer to help you for another solution
Also you should use DISTINCT to avoid multiple records.
SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

Get Value into an Array on Form Submission

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];
}
}

Make hierarchy from table with PHP

I have a table in database and in this table i have added 3 columns that is i, name,parent_id.please see below.
ID | name | parent_id
1 name1 0
2 name2 1
3 name3 1
Now i want to fetch this id from database. I have created a method in PHP and fetch data one by one from database. Please see below
function getData($id)
{
$array = array();
$db = JFactory::getDBO();
$sql = "SELECT * from table_name when id = ".$id;
$db>setQuery($sql);
$fetchAllDatas = $db->getObjectList();
foreach ($fetchAllDatas as $fetchAllData)
{
if($fetchAllData->parent_id > 0)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
$this->getData($fetchAllData->parent_id);
}
else
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
}
}
return $array;
}
Now if i call this method with id 3 like
$this->getData(3); // has a parent
It will return like that
Array(
[0]=>name1
)
But i want like below
Array(
[1]=>name3,
[0]=>name1
)
I know i have redefine array if we have parent but how i manage it.
i have used array_push php function but its not work with my condition.
foreach ($fetchAllDatas as $fetchAllData)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
if($fetchAllData->parent_id > 0)
array_push($array,$this->getData($fetchAllData->parent_id));
}
return $array;
1)Because you do $array[$fetchAllData->parent_id] = $fetchAllData->name; in the if and in the else, you do this in both cases so put out of if..else.
2) Try to push the result of your second call in the original array to get what you want.
you have unique ID in your table, so if you call your query it will always return only one result. Maybe you wanted to write query this way:
$sql = "SELECT * from table_name when parent_id = ".$id;
if you want to get the result with given ID and his parent, you should add this after calling $this->fetchSharedFolder(...);
$array = array_merge($array, $this->getData($fetchAllData->parent_id));

Categories