Ok Guys i need your Help One More Time Please if you can??
I have a list of drop down options as a set of filter criteria.
When each is selected, it adds it to a query string and appends an equals (=) to the selection, so if i select Large, the query would be where size = large.
I have one selection called impacted, but when a user selects impacted, i dont want the query to append = to, i want it to become where impacted LIKE 'click', so that it will search anywhere in the database column impacted.
If it remains at = to, it will only bring back a selection where there is only ONE impacted system that is stored against a lesson exactly = to the selection.
SELECT p.project_id
, p.project_name
, p.department
, p.size
, p.programme
, l.captured_by
, l.stage
, l.type
, l.impacted
, l.depts_inv
, l.lesson_title
, l.lesson_learned
, l.lesson_added
FROM ll_project p
JOIN ll_lessons l
ON l.project_id = p.project_id
AND l.impacted = 'Click';
This is how it currently pulls the code in but if someone has made a selection against the impacted filter i want the query not to add = before it but 'contains' or 'like' if you know what i mean.
Here is the full code.
<?php
//Set all Variables pulled from POST of previous page
$pid = $_POST['project_id'] ;
$psize = $_POST['projectSize'] ;
$pdepts = $_POST['depts'] ;
$lstage = $_POST['stage'] ;
$ltype = $_POST['type'] ;
$impacted = $_POST['impacted'] ;
//Create Column Variable to hold Values in an array linked to the database columns
$columns = array('project_id'=>'ll_project.project_id','projectSize'=>'size','depts'=>'department','stage'=>'ll_lessons.stage','type'=>'ll_lessons.type','impacted'=>'ll_lessons.impacted');
$sqlString = null;
//Check all POSTED data is pulling through - Should be 6
//echo "Total Number Of Captured Post Variables is:";
//echo count($_POST);
$number = 0;
$queryStr = "";
$preStr = array();
//For Every POSTED Value Set the Name as Key and the Value against Each
foreach ($_POST as $key => $val ) {
if (!empty($_POST[$key])){
if(!is_array($_POST[$key]))
//Escape the VALUE by surrounding it with Quotes as it is a string the value would not be picked up on the query.
$currentStr = $columns[$key]." = '".mysql_real_escape_string($val)."'";
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
//set the Query String that i want to return from the Database and set the join on the BSKYB NUMBERS on both Tables
$queryStr = "SELECT ll_project.project_id, ll_project.project_name, ll_project.department, ll_project.size, ll_project.programme, ll_lessons.captured_by, ll_lessons.stage, ll_lessons.type, ll_lessons.impacted, ll_lessons.depts_inv, ll_lessons.lesson_title, ll_lessons.lesson_learned, ll_lessons.lesson_added FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ".implode(' AND ',$preStr);
The answer is so!
if ($key == 'impacted') {
$currentStr = $columns[$key] . " LIKE '%" . mysql_real_escape_string($val) . "%'";
} else {
$currentStr = $columns[$key] . " = '" . mysql_real_escape_string($val) . "'";
}
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
Thanks for checking it out Strawberry :)
Related
hi i am new to php mysql. I have created a form where the user can search the database, and the result depends on how the user fills in the form. form has 6 search fields. where user can choose / fill any of one or more fields to make his search. i have coded it as follows
php
<?php require_once('Connections/osrc.php'); ?>
<?php
$maxRows_search_result = 10;
$pageNum_search_result = 0;
if (isset($_GET['pageNum_search_result'])) {
$pageNum_search_result = $_GET['pageNum_search_result'];
}
$startRow_search_result = $pageNum_search_result * $maxRows_search_result;
mysql_select_db($database_osrc, $osrc);
$propertyid = $_POST['propertyid'];
$offered = $_POST['offered'];
$property_type = $_POST['property_type'];
$beds = $_POST['beds'];
$city = $_POST['city'];
$locality = $_POST['locality'];
$query_search_result = "SELECT * FROM osrc_data WHERE propertyid LIKE '%$propertyid%' OR offered LIKE '%$offered%' AND property_type LIKE '%$property_type%' AND beds LIKE '%$beds%' AND city LIKE '%$city%' AND locality LIKE '%$locality%' ";
$query_limit_search_result = sprintf("%s LIMIT %d, %d", $query_search_result, $startRow_search_result, $maxRows_search_result);
$search_result = mysql_query($query_limit_search_result, $osrc) or die(mysql_error());
$row_search_result = mysql_fetch_assoc($search_result);
if (isset($_GET['totalRows_search_result'])) {
$totalRows_search_result = $_GET['totalRows_search_result'];
} else {
$all_search_result = mysql_query($query_search_result);
$totalRows_search_result = mysql_num_rows($all_search_result);
}
$totalPages_search_result = ceil($totalRows_search_result/$maxRows_search_result)-1;
?>
now when user It works but it shows all rows in database table.
for example user fills up three fields beds, city, locality and rest of three are blank.
search result page shows all rows in data base with all records.
pls help me to correct my codes. Thanks in advance
First, I agree with #VaaChar, you should be using mysqli or even better yet PDO.
You will have determine IF a value has been placed in a field and if so use it in your query. If no value was placed in the field ignore it in your query.
Something like this...
$sqlid = "";
$sqloffered = "";
$sqltype = "";
$sqlbeds = "";
$sqlcity = "";
$sqllocality = "";
if(isset($propertyid)) {
$sqlid = " propertyid LIKE '%$propertyid%'";
}
if(isset($propertyid) && isset($offered)) {
$sqloffered = " OR offered LIKE '%$offered%'";
}
if(!isset($propertyid) && isset($offered)) {
$sqloffered = " offered LIKE '%$offered%'";
}
if(isset($property_type)) {
$sqltype = " AND property_type LIKE '%$property_type%'";
}
if(isset($beds)) {
$sqlbeds = " AND beds LIKE '%$beds%'";
}
if(isset($city)) {
$sqlcity = " AND city LIKE '%$city%'";
}
if(isset($locality)) {
$sqllocality = " AND locality LIKE '%$locality%'";
}
$sql = "SELECT * FROM osrc_data WHERE {$sqlid}{$sqloffered}{$sqltype}{$sqlbeds}{$sqlcity}{$sqllocality} ";
When you build the sql query with (say) $propertyid empty, you get this :
.... LIKE '%%' ...,
which is like saying "anything". You must build your query only with the fields that have been filled.
I have a meal/recipe database, used for creating daily meal plans. I need to create 3 different select lists (breakfast, lunch, dinner) to display the available recipe options, for each meal_name.
As of now I'm using separate queries for each of the above, and separate builds to display the results for each list.
The query for Lunch:
// Lunch options
$sql = "SELECT plan_date,
plan_meal,
plan_recipe,
recipe_name,
recipe_serving_size
FROM recipe_plans
LEFT JOIN $table_meals ON meal_id = plan_meal
LEFT JOIN $table_recipes ON recipe_id = plan_recipe
WHERE plan_date = '".$date."'
AND meal_name = 'Lunch'
AND plan_owner = '".$user_name."'
ORDER BY recipe_name";
$rc = $DB_LINK->Execute($sql);
DBUtils::checkResult($rc, NULL, NULL, $sql);
// Scan the rows of the SQL result
while (!$rc->EOF) {
$recipeList[($rc->fields['plan_recipe'])] = $rc->fields['recipe_name'] . " (" . $rc->fields['recipe_serving_size'] . ")";
$rc->MoveNext();
}
and the build:
// Scan the fields in the SQL result row
// Print all existing Meals, and some new ones
$minShow = 1;
$maxShow = 1; // only build 1 while testing
for ($i = 0; $i < (isset($MealPlanObj->mealplanItems[$date]) && ($i < $maxShow) ? count($MealPlanObj->mealplanItems[$date]) : 0) + $minShow; $i++) {
if ($i < (isset($MealPlanObj->mealplanItems[$date]) ? count($MealPlanObj->mealplanItems[$date]) : 0)) {
// If it is an existing meal item, then set it
$meal = $MealPlanObj->mealplanItems[$date][$i]['meal']; // meal_id
$servings = $MealPlanObj->mealplanItems[$date][$i]['servings'];
$recipe = $MealPlanObj->mealplanItems[$date][$i]['id']; // recipe_id
} else {
// It is a new one, give it blank values
$meal = NULL;
$servings = $defaultServings;
$recipe = NULL;
}
// The HTML Code to build the select list for 'Lunch'
}
The above code has been duplicated for each meal_name, because that's where my limited skills have left me, lol.
The question is: rather than writing a separate select and build statement for each of the 3 conditions (breakfast, lunch, dinner), how can I write just 1, to output them all?
You already used variables to build the SQL query, so you can introduce just another variable like $meal_name. This variable you can apply to your SQL statement. Instead of:
$sql = "SELECT mplan_date,
...
AND meal_name = 'Lunch'
...
you will write then:
$meal_name = 'Lunch';
...
$sql = "SELECT mplan_date,
...
AND meal_name = '" . mysqli_real_escape_string($meal_name) . "'
...
Note the use of the function mysqli_real_escape_string(), although not absolutely necessary in this example, it's very important to escape all variables you add to an SQL statement, if you are not absolutely sure what's inside the variable. Your example code is vulnerable to SQL-injection.
After that you can go a step further and pack the code into a function:
function buildSqlQuery($meal_name, $date, $user_name)
{
$sql = "SELECT mplan_date,
...
ORDER BY recipe_name";
return $sql;
}
$sqlForBreakfast = buildSqlQuery('Breakfast', '2000-01-01', 'teddy');
$sqlForLunch = buildSqlQuery('Lunch', '2000-01-01', 'teddy');
$sqlForDinner = buildSqlQuery('Dinner', '2000-01-01', 'teddy');
I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.
Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)