How to make one variable out of this? - php

Best,
I'm bussy making a website, but one thing holds me up..
I have to make a real long search query, and i have made this PHP code:
if($_GET['genre']) {
echo 'SELECT * FROM movies WHERE `genre1` = ';
foreach($_GET['genre'] as $genre)
{
$genres = array( "Actie", "Animatie", "Avontuur", "Documentaire", "Drama", "Erotiek", "Familie", "Fantasy", "Film", "Horror", "Komedie", "Misdaad", "Muziek", "Mystery", "Oorlog", "Roadmovie", "Romantiek", "Sciencefiction", "Thriller", "Western" );
if (!in_array($genre, $genres))
{
header('location: ?error=1');
}
echo " '".$genre."' OR `genre2` = '".$genre."'"; if(end($_GET['genre']) !== $genre)
{
echo ' OR `genre1` = ';
}
}
echo " AND `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
else
{
echo "SELECT * FROM movies WHERE `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
On a URL like this:
127.0.0.1/querygenerator.php?genre%5B3%5D=Avontuur&genre%5B4%5D=Documentaire&genre%5B6%5D=Erotiek&year1=1900&year2=2014
And it outputs something like this:
SELECT * FROM movies WHERE `genre1` = 'Avontuur' OR `genre2` = 'Avontuur' OR `genre1` = 'Documentaire' OR `genre2` = 'Documentaire' OR `genre1` = 'Erotiek' OR `genre2` = 'Erotiek' AND `year` > '1900' AND `year` < '2014';
So, my question is, how can i make one PHP variable out this whole, so I can run the query?
I can do this with file_get_contents but that's not so safe, I guess..
Thanks!
- Karim

Just concatenate to a string rater than echoing:
if($_GET['genre']) {
$sql = 'SELECT * FROM movies WHERE `genre1` = ';
foreach($_GET['genre'] as $genre) {
$genres = array( "Actie", "Animatie", "Avontuur", "Documentaire", "Drama", "Erotiek", "Familie", "Fantasy", "Film", "Horror", "Komedie", "Misdaad", "Muziek", "Mystery", "Oorlog", "Roadmovie", "Romantiek", "Sciencefiction", "Thriller", "Western" );
if (!in_array($genre, $genres)) {
header('location: ?error=1');
die();
}
$sql = $sql . " '".$genre."' OR `genre2` = '".$genre."'";
if(end($_GET['genre']) !== $genre) {
$sql = $sql . ' OR `genre1` = ';
}
}
$sql = $sql . " AND `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
} else {
$sql = "SELECT * FROM movies WHERE `year` > '".$_GET['year1']."' AND `year` < '".$_GET['year2']."';";
}
echo $sql;

Related

Can not insert php data to mysql using for()

i try to insert the data with php to mysql by checking the value if it exists then it will update if no then it will insert, but it fail i use for () what is wrong with my script?
if(isset($_POST['submit'])){
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
if (empty($fieldA)) {
echo 'fieldA cannot empty';
}
else
{
for ($i=1; $i<= $nomer; $i++) {
$query = mysql_query("SELECT * FROM tb1 ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
$get1 = mysql_fetch_assoc($query);
$get2 = mysql_num_rows($query);
if ($get2 != 0) {
mysql_query("UPDATE tb1 SET kd_kelas = '2' ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
} else {
mysql_query("INSERT INTO tb1(fieldA, fieldB, ".
"fieldC, fieldD) VALUES ".
"('$fieldA', '$fieldB', ".
"'$fieldC', '$fieldD')");
}
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}
All the methods related with mysql_* is deprecated now. Use mysqli_*.
And try this snippet:
if (isset($_POST['submit']) && !empty($_POST['fieldA'])) {
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
for ($i = 1; $i <= $nomer; $i++) {
$sql = sprintf("SELECT * FROM tb1 WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
$updateSql = sprintf("UPDATE tb1 SET kd_kelas = '2' WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
mysqli_query($link, $updateSql);
}
else {
$insertSql = sprintf("INSERT INTO tb1(fieldA, fieldB,fieldC, fieldD) VALUES ('%s','%s','%s','%s')", $fieldA,
$fieldB, $fieldC, $fieldD);
mysqli_query($link, $insertSql);
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}
here $link is the connection string
$link = mysqli_connect('localhost', 'root', 'password', 'database');

search by multiple field. sometimes by one field and sometimes more than one field

I have search form. in here multiple field. sometimes I will form submit with one field, sometimes form submit with two and sometimes multiple field value.
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql = mysql_query("select * from project_list where projectName='$projectName'");
}
if (!empty($clientId))
{
$searchSql = mysql_query("select * from project_list where client_id='$clientId'");
}
if (!empty($departmentId))
{
$searchSql = mysql_query("select * from project_list where department_id='$departmentId'");
}
if (!empty($statusName))
{
$searchSql = mysql_query("select * from project_list where status='$statusName'");
}
}
these query only for search by single field.
how to make query that performs searching by one or multiple field value
is it possible??
Use Concatenation in query Variable
$searchSql ="select * from project_list where 1=1 ";
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
if (!empty($projectName))
{
$searchSql. = " AND projectName='$projectName'";
}
if (!empty($clientId))
{
$searchSql. = " AND client_id='$clientId'";
}
if (!empty($departmentId))
{
$searchSql. = " AND department_id='$departmentId'";
}
if (!empty($statusName))
{
$searchSql. = " AND status='$statusName'";
}
}
$result=mysql_query($searchSql);
NOTE:mysql_query() has been deprecated in PHP 5.5 and removed in PHP 7. Kindly update to use mysqli library of PDO.
You can build an increntale query
<code>
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
$my_sql = "select * from project_list ";
$my_where = "";
if (!empty($projectName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "projectName='$projectName'";
}
if (!empty($clientId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "client_id='$clientId'";
}
if (!empty($departmentId))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "department_id='$departmentId'";
}
if (!empty($statusName))
{
if ($my_where = ""){
$my_sql .= "where ";
} else {
$my_sql .= "and ";
}
$my_sql .= "status='$statusName'";
}
}
Here I used column id as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null";
Code
<?
if (isset($_POST['search'])) {
$projectName = $_POST['pName'];
$clientId = $_POST['s_by_clientName'];
$departmentId = $_POST['s_by_department'];
$statusName = $_POST['s_by_status'];
// Here I used coloumn 'id' as primary key & auto-increment. Change it as per your column name.
$query = "SELECT * FROM project_list WHERE id is not null"
if (!empty($projectName))
{
$query. = " AND projectName='".$projectName."'";
}
if (!empty($clientId))
{
$query. = " AND client_id='".$clientId."'";
}
if (!empty($departmentId))
{
$query. = " AND department_id='".$departmentId."'";
}
if (!empty($statusName))
{
$query. = " AND project_list='".$statusName."'";
}
$searchSql = mysql_query($query);
}

PHP MySQL search with multiple criteria

I have a search form in a website and would like to have several search terms which is input by the user to perform db search, terms as below:
Keywords
Property For (Sale, Rent...)
Property Type (Apartment, Terrace House...)
State
Min Price
Max Price
Here is script to perform search with above term's input
public function get_property_list_by_search($start, $per_page, $keyword, $prop_for, $min, $state, $ptype, $max, $mysqli)
{
if(empty($start) && empty($per_page))
{
return 0;
}
$start = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($start));
$per_page = preg_replace('/[^0-9]/', '', $mysqli->real_escape_string($per_page));
$keyword = $mysqli->real_escape_string(stripslashes($keyword));
$prop_for = $mysqli->real_escape_string(stripslashes($prop_for));
$state = $mysqli->real_escape_string(stripslashes($state));
$ptype = $mysqli->real_escape_string(stripslashes($ptype));
$min_price = self::num_clean($mysqli->real_escape_string($min));
$max_price = self::num_clean($mysqli->real_escape_string($max));
$t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
if(isset($keyword) && !empty($keyword)){
$t1 = " AND `proj_title` LIKE '%".$keyword."%' OR `proj_addr` LIKE '%".$keyword."%' OR `proj_area` LIKE '%".$keyword."%'";
}
if(isset($prop_for) && !empty($prop_for)){
$t2 = " AND `proj_for`='".$prop_for."'";
}
if(isset($state) && !empty($state)){
$t3 = " AND `state`='".$state."'";
}
if(isset($ptype) && !empty($ptype)){
$t4 = " AND `proj_cat`='".$ptype."'";
}
//min & max
if((isset($min_price) && !empty($min_price)) && (isset($max_price) && !empty($max_price))){
$t5 = " AND `price` BETWEEN '".$min_price."' AND '".$max_price."'";
}
//min only
if(!empty($min_price) && empty($max_price)){
$t5 = " AND `price` >= '".$min_price."'";
}
//max only
if(empty($min_price) && !empty($max_price)){
$t5 = " AND `price` <= '".$max_price."'";
}
$sql = $mysqli->query("SELECT * FROM `project` WHERE `status`='1' ".
$t1." ".$t2." ".$t3." ".$t4." ".$t5." ".
"ORDER BY `posted_date` DESC LIMIT ".$start.", ".$per_page);
if($sql->num_rows > 0){
return $sql;
}else{
return false;
}
}
The query output will something like:
SELECT * FROM `project`
WHERE `proj_title` LIKE '%keywords%'
OR `proj_addr` LIKE '%keywords%'
OR `proj_area` LIKE '%keywords%'
AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
(Datatype for price is DECIMAL(10,2), it stored value like 250000.00)
However, the returned results is not like expected (not accurate), its also will come out a result with price more than 600000 and project category which is out of '8' which is not fancy for the end user to searching in the website.
is there any way to refine on the query to perform more specific?
Instead of taking these variables you should use ".=" operator.
/* $t1 = '';
$t2 = '';
$t3 = '';
$t4 = '';
$t5 = '';
*/
$q = "SELECT * FROM `property` WHERE `status`='1' ";
// You need to enclose all **OR** logical tests in parenthesis.
// Moreover most of the usages of isset function are useless,
// as your are initializing many variables
if($keyword && !empty($keyword)){
$q .= " AND (`p_title` LIKE '%".$keyword."%' OR `address` LIKE '%".$keyword."%' OR `area` LIKE '%".$keyword."%')";
}
if($prop_for && !empty($prop_for)){
// If you are using double quotes you really don't need handle to concatenation.
$q .= " AND `p_for`='$prop_for'";
}
if($state && !empty($state)){
$q .= " AND `state`='$state'";
}
if($ptype && !empty($ptype)){
$q .= " AND `p_category`='$ptype'";
}
//min only
if($min_price && !empty($min_price)){
$q .= " AND `price` >= '".$min_price."'";
}
//max only
if($max_price && !empty($max_price)){
$q .= " AND `price` <= '$max_price'";
}
// When you are not using OFFSET keyword,
//the first number after LIMIT keyword should be the number of records
$q .= " ORDER BY `posted_date` DESC LIMIT $per_page , $start;";
$sql = $mysqli->query($q);
You're going to need parentheses.
SELECT * FROM `project` WHERE (`proj_title` LIKE '%keywords%' OR `proj_addr` LIKE '%keywords%' OR `proj_area` LIKE '%keywords%') AND `proj_for`='Sale' AND `state`='Somewhere' AND `proj_cat`='8' AND `price` BETWEEN '250000' AND '600000'
Without the parentheses it just has to match one of the criteria before the last OR.
if(isset($_SESSION['login']))
{
echo "<div align=\"right\"><strong> Home |
Signout|
Profile</strong></div>";
}
else
{
echo " ";
}
$con= mysql_connect("localhost","root","");
$d=mysql_select_db("matrimonial",$con);
$gender=$_POST['gender'];
$age1=$_POST['age1'];
$age2=$_POST['age2'];
$city=$_POST['city'];
$subcast=$_POST['subcast'];
$result=mysql_query("select * from matri where gender='$gender' and age between '$age1' and '$age2' and city='$city' and subcast='$subcast'");
if($gender && !empty($gender))
{
$result .= " AND `gender`='$gender'";
}
if($age1 && !empty($age1)){
$result .= " AND `age`='$age1'";
}
if($age2 && !empty($age2)){
$result .= " AND `age`='$age2'";
}
if($city && !empty($city)){
$result .= " AND `city`='$city'";
}
if($subcast && !empty($subcast)){
$result .= " AND `subcast`='$subcast'";
}
$result .= " select * from ";
$sql = $mysql->query($result);
how to run this code
On the price difference you should do a if the price if between the 2 values else only 1 value.

PHP search to match all if the term is empty

I have written a simple search algorithm for my advanced search of my website.
There are several categories that the advanced search helps the user to limit his/her search. %$variable% is the matching that I use. I want the database to return every possible matches if the title is empty...what should be added/removed to/from this code?
if(isset($_POST['type']) && $_POST['type'] != 0)
{
$type = $_POST['type'];
if($wh == true)
{
$statement .= " AND `type` = '$type' ";
}
else
{
$wh = false;
$statement .= " WHERE `type` = '$type' ";
}
}
if(isset($_POST['sex']) && $_POST['sex'] != 0)
{
$sex = $_POST['sex'];
if($wh == true)
{
$statement .= " AND `sex` = '$sex' ";
}
else
{
$wh = false;
$statement .= " WHERE `sex` = '$sex' ";
}
}
if(isset($_POST['start']) && $_POST['start'] != 0)
{
$start = $_POST['start'];
if($wh == true)
{
$statement .= " AND `start` > '$start' ";
}
else
{
$wh = false;
$statement .= " WHERE `start` > '$start' ";
}
}
if($wh==true)
{
$statement .= " $branch_sentence AND( `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%') ORDER BY stars DESC ";
}
else
{
$statement .= " WHERE `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%' ORDER BY stars DESC ";
}
// echo $statement;
if($transorder = $site_db->query($statement))
{
$i=0;
while($row_obj = $transorder->fetch_object())
{
$item[$i]['id'] = $row_obj->id;
$item[$i]['pic_main'] = $row_obj->pic_main;
$item[$i]['title'] = $row_obj->title;
$item[$i]['province'] = $row_obj->province;
$item[$i]['stars'] = $row_obj->stars;
$i++;
}
}
}
}
What's wrong with:
if (empty($_POST['title']))
{
$statement = "SELECT id, pic_main, title, province, stars FROM "; // Incomplete b/c I don't know your table name from the question.
}
?

joomla k2 tag cloud random

I am trying to use K2 Tool's tag cloud function on my joomla website but the only setting I can pick is by X Popular Tags which doesn't actually specific what makes the tag popular.
So I am trying to make it so that the tag cloud works as X Random instead. So everytime the page/module is reloaded, X say 20 would display 20 randomly chosen tags.
I look through the module's code and found the function in helper.php but I don't understand how the code select the tags. My guess is if I want to change it to use X random instead of X popular, I would need to change the query for $query?
function tagCloud(&$params) {
$mainframe = &JFactory::getApplication();
$user = &JFactory::getUser();
$aid = (int) $user->get('aid');
$db = &JFactory::getDBO();
$jnow = &JFactory::getDate();
$now = $jnow->toMySQL();
$nullDate = $db->getNullDate();
$query = "SELECT i.id FROM #__k2_items as i";
$query .= " LEFT JOIN #__k2_categories c ON c.id = i.catid";
$query .= " WHERE i.published=1 ";
$query .= " AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." ) ";
$query .= " AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )";
$query .= " AND i.trash=0 ";
if(K2_JVERSION=='16'){
$query .= " AND i.access IN(".implode(',', $user->authorisedLevels()).") ";
}
else {
$query .= " AND i.access <= {$aid} ";
}
$query .= " AND c.published=1 ";
$query .= " AND c.trash=0 ";
if(K2_JVERSION=='16'){
$query .= " AND c.access IN(".implode(',', $user->authorisedLevels()).") ";
}
else {
$query .= " AND c.access <= {$aid} ";
}
$cloudCategory = $params->get('cloud_category');
if(is_array($cloudCategory)) {
$cloudCategory = array_filter($cloudCategory);
}
if ($cloudCategory) {
if(!is_array($cloudCategory)){
$cloudCategory = (array)$cloudCategory;
}
foreach($cloudCategory as $cloudCategoryID){
$categories[] = $cloudCategoryID;
if($params->get('cloud_category_recursive')){
$children = modK2ToolsHelper::getCategoryChildren($cloudCategoryID);
$categories = #array_merge($categories, $children);
}
}
$categories = #array_unique($categories);
JArrayHelper::toInteger($categories);
if(count($categories)==1){
$query .= " AND i.catid={$categories[0]}";
}
else {
$query .= " AND i.catid IN(".implode(',', $categories).")";
}
}
if(K2_JVERSION == '16') {
if($mainframe->getLanguageFilter()) {
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND c.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") ";
}
}
$db->setQuery($query);
$IDs = $db->loadResultArray();
$query = "SELECT tag.name, tag.id
FROM #__k2_tags as tag
LEFT JOIN #__k2_tags_xref AS xref ON xref.tagID = tag.id
WHERE xref.itemID IN (".implode(',', $IDs).")
AND tag.published = 1";
$db->setQuery($query);
$rows = $db->loadObjectList();
$cloud = array();
if (count($rows)) {
foreach ($rows as $tag) {
if (#array_key_exists($tag->name, $cloud)) {
$cloud[$tag->name]++;
} else {
$cloud[$tag->name] = 1;
}
}
$max_size = $params->get('max_size');
$min_size = $params->get('min_size');
$max_qty = max(array_values($cloud));
$min_qty = min(array_values($cloud));
$spread = $max_qty - $min_qty;
if (0 == $spread) {
$spread = 1;
}
$step = ($max_size - $min_size) / ($spread);
$counter = 0;
arsort($cloud, SORT_NUMERIC);
$cloud = #array_slice($cloud, 0, $params->get('cloud_limit'), true);
uksort($cloud, "strnatcasecmp");
foreach ($cloud as $key=>$value) {
$size = $min_size + (($value - $min_qty) * $step);
$size = ceil($size);
$tags[$counter]-> {'tag'} = $key;
$tags[$counter]-> {'count'} = $value;
$tags[$counter]-> {'size'} = $size;
$tags[$counter]-> {'link'} = urldecode(JRoute::_(K2HelperRoute::getTagRoute($key)));
$counter++;
}
return $tags;
}
}

Categories