I have a website that has a built in search function. It allows the users to search for keywords from within the main page header. When a user searches any keyword, the result is always:
There are no results matching your query.
In order to find any item, the user must go to the advanced search options and enter the keyword in the search box, select the checkbox for "Search item title and description" and select "Both" from the drop down box for "Listed In".
I cannot figure out how to automatically set the main page search box to search each of these options.
Below is the code that I have for the search function. Any help would be GREATLY APPRECIATED:
<?php
session_start();
define ('IN_SITE', 1);
include_once ('includes/global.php');
include_once ('includes/class_formchecker.php');
include_once ('includes/class_custom_field.php');
include_once ('global_header.php');
$option = $db->rem_special_chars($_REQUEST['option']);
$option = (empty($option)) ? 'auction_search' : $option;
$template->set('option', $option);
$item_details = $db->rem_special_chars_array($_POST);
$template->set('item_details', $item_details);
$header_search_page = header5(GMSG_ADVANCED_SEARCH);
$template->set('header_search_page', $header_search_page);
if ($_REQUEST['search_empty'] == 1)
{
$template->set('no_results_message', '<p align="center" class="errormessage">' . MSG_NO_RESULTS_QUERY . '</p>');
}
(string) $search_options_menu = null;
$search_options_menu .= display_link(process_link('search', array('option' => 'auction_search')), MSG_AUCTION_SEARCH, (($option = 'auction_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'seller_search')), MSG_SELLER_SEARCH, (($option = 'seller_search') ? false : true)) . ' | ';
$search_options_menu .= display_link(process_link('search', array('option' => 'buyer_search')), MSG_BUYER_SEARCH, (($option = 'buyer_search') ? false : true));
if ($setts['enable_stores'])
$template->set('search_options_menu', $search_options_menu);
switch ($option)
{
case 'auction_search':
$search_options_title = MSG_AUCTION_SEARCH;
$custom_fld = new custom_field();
$custom_fld->new_table = false;
$custom_fld->field_colspan = 2;
$custom_fld->box_search = 1;
$custom_sections_table = $custom_fld->display_sections($item_details, 'auction', false, 1, 0);
$template->set('custom_sections_table', $custom_sections_table);
$tax = new tax();
$template->set('country_dropdown', $tax->countries_dropdown('country', $item_details['country'], null, '', true));
//$template->set('state_box', $tax->states_box('state', $item_details['state'], $item_details['country']));
break;
case 'seller_search':
$search_options_title = MSG_SELLER_SEARCH;
break;
case 'buyer_search':
$search_options_title = MSG_BUYER_SEARCH;
break;
case 'store_search':
$search_options_title = MSG_STORE_SEARCH;
break;
}
$template->set('search_options_title', $search_options_title);
$template_output .= $template->process('search.tpl.php');
include_once ('global_footer.php');
echo $template_output;
?>
This issue after doing research was the result in a standard setting for MySQL. Minimum search length had to be longer than 3 characters. A search length of 3 characters or less yielded no search results.
Related
I've found on several pages of my site that content retrieved from the database appears to be being cached.
Example:
I have a page which uses the following query
SELECT c.ID, c.name FROM member_coupons AS m LEFT JOIN coupons as c on c.ID = m.couponID WHERE m.userID = 'ANONYMOUS' ORDER BY c.ID
If I run the query in phpMyAdmin, I get the expected results
On the website it is correct as well.
I then fill out the form on the same page, selecting anything on the drop downs and submit. This brings you to a confirmation screen, with a link back to the original screen.
PhpMyAdmin shows me the expected results.
But the website is still showing both options until I refresh
- before refresh
The javascript that is called by the page on the submit is:
$("#submit").click(function() {
var text = "&coupon=" + $("#coupons").val();
var text = text + "&card1=" + $("#card1").val();
var text = text + "&card2=" + $("#card2").val();
var text = text + "&card3=" + $("#card3").val();
var text = text + "&card4=" + $("#card4").val();
$.get("ajax.php?action=couponSwap" + text, function(data, status) {
$('#content').html(data);
});
});
and the associated function
function couponSwap($pdo, $get, $user) {
$coupon = $get['coupon'];
switch($coupon) {
case "1RNORMAL":
$cards[] = $user->addRandomCard(1, 'normal');
break;
case "2RNORMAL":
$cards[] = $user->addRandomCard(2, 'normal');
break;
case "1RSPECIAL":
$cards[] = $user->addRandomCard(1, 'special');
break;
case "2RSPECIAL":
$cards[] = $user->addRandomCard(2, 'special');
break;
case "1CNORMAL":
$cards[][] = $user->addCard($get['card1']);
break;
case "2CNORMAL":
$cards[][] = $user->addCard($get['card1']);
$cards[][] = $user->addCard($get['card2']);
break;
case "1CSPECIAL":
$cards[][] = $user->addCard($get['card3']);
break;
case "2CSPECIAL":
$cards[][] = $user->addCard($get['card3']);
$cards[][] = $user->addCard($get['card4']);
break;
}
if( count( $cards ) > 0 ){
foreach ($cards as $cardArray) {
foreach ($cardArray as $card) {
echo '<img src="'.$card["card"]->showImage().'" alt="'.$card["card"]->getName().'"/> ';
$names[] = $card["card"]->getName();
$insertIDs[] = $card['ID'];
}
}
$names = (isset($names)) ? implode(", " , $names) : 'ERROR';
$user->addLog(date("Y-m-d"), "Coupon Swap: " . $names, $insertIDs);
}
$sql = "DELETE FROM member_coupons WHERE couponID = :couponID AND userID = :userID LIMIT 1";
$q = $pdo->prepare($sql);
$q->bindValue(':couponID', $coupon);
$q->bindValue(':userID', $user->getID());
$q->execute();
echo '<p>Swap more coupons</p>';
}
Also seeing issues where the site is thinking a user is logged out even when they are logged in.
Cookies are set using
$expire = time() + (7 * 24 * 60 * 60);
setcookie("cardHoarder", $row['ID'], $expire, '/');
Checking if a user is logged in uses the following code
$loggedIn = (isset($_COOKIE['cardHoarder'])) ? '1' : '0';
This is included in the config file which is included on all the php files on the site. Its being treated as though the cookies aren’t set even though I can see them.
Can also see the issue on the following page - link here - If you browse to this page, select the randomiser link in the header, select another link then go back to the randomiser, the same images show
No errors are being reported on the site. Can anyone point me towards what else to look at
I made language php code which working fine. I request the translations from different like en.php, de.php.
In en.php i have one array:
$language = Array('homepage' => 'Site Home','contact' => 'Contact Us');
I use $_SESSION for get the language en, de, hu and the others. I get the language files with this code:
$sql = mysql_query("SELECT * FROM languages ORDER BY langID");
$count = mysql_num_rows($sql);
if ($count) {
while ($ds = mysql_fetch_array($sql)) {
switch ($_SESSION['language']) {
case $ds['tag']:
include_once('language/' . $ds['tag'] . '.php');
break;
default:
include_once('language/en.php');
break;
}
}
}
But I would like to change array for mysql database. In my DB i have a table with:
translatesID
tag(its now the 'en' or can be other like 'de')
key(what i want to be the array like 'homepage')
value(which would be the 'Site Home')
In index.php I get the 'Site Home' with the following php code:
<?php echo $language['homepage']; ?>
My question is which Mysql request or PHP code can solve my request?
Problem solved with this code:
$language = array();
$sql = mysql_query("SELECT * FROM translates WHERE '" . $_SESSION['language'] . "' = tag");
while($row = mysql_fetch_array($sql)) {
$language[$row['key']] = $row['value'];
}
Im using this code from google api
I am getting all of the goals names and number
But I cant see a way to get the goal completed amount
This is what I get:
Account ID = xxx
Web Property ID = xxx
Internal Web Property ID = xxx
Profile ID = xxx
Goal Number = 1
Goal Name = Open User (MT Register)
Goal Value = 0
Goal Active = 1
Goal Type = URL_DESTINATION
Created = 2012-07-22T10:20:02.183Z
Updated = 2012-08-15T12:43:06.045Z
Goal URL = /04_thankyou.php
Case Sensitive =
Match Type = REGEX
First Step Required = 1
Destination Goal Steps
Step Number = 1
Step Name = abc
Step URL = /01_insert_phone.php
Step Number = 2
Step Name = abcd
Step URL = /02_progress.step
Step Number = 3
Step Name = abcde
Step URL = /03_insert_pincode.php
This is the code:
function getEventDetailsHtml(&$details) {
$html = '<h4>Event Goal</h4><pre>' .
'Use Event Value = ' . $details->getUseEventValue();
// Get all the event goal conditions.
$conditions = $details->getEventConditions();
foreach ($conditions as &$condition) {
$html .= "Event Type = $condition->getEventType()";
$eventType = $condition->getType();
if ($condition->getType() == 'VALUE') {
// Process VALUE.
$html .= "Comparison Type = $condition->getComparisonType()" .
"Comparison Value = $condition->getComparisonValue()";
} else {
// Process CATEGORY, ACTION, LABEL.
$html .= "Match Type = $condition->getMatchType()" .
"Expression = $condition->getExpression()";
}
}
return $html . '</pre>';
}
function getVisitNumPagesDetailsHtml(&$details) {
$html = '<h4>Visit Num Pages Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getVisitTimeOnSiteDetailsHtml(&$details) {
$html = '<h4>Visit Time On Site Goal</h4>';
$html .= <<<HTML
<pre>
Comparison Type = {$details->getComparisonType()}
Comparison Value = {$details->getComparisonValue()}
</pre>
HTML;
return $html;
}
function getUrlDestinationDetailsHtml(&$details) {
$html .= <<<HTML
<pre>
Goal URL = {$details->getUrl()}
Case Sensitive = {$details->getCaseSensitive()}
Match Type = {$details->getMatchType()}
First Step Required = {$details->getFirstStepRequired()}
</pre>
HTML;
$html .= '<h4>Destination Goal Steps</h4>';
$steps = $details->getSteps();
if (count($steps) == 0) {
$html .= '<p>No Steps Configured</p>';
} else {
foreach ($steps as &$step) {
$html .= <<<HTML
<pre>
Step Number = {$step->getNumber()}
Step Name = {$step->getName()}
Step URL = {$step->getUrl()}
</pre>
HTML;
}
}
return $html;
}
require_once 'google_api.php';
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
try {
$goals = $analytics->management_goals
->listManagementGoals('25788360',
'UA-25788360-20',
'~all');
} catch (Exception $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
$html = '';
$items = $goals->getItems();
foreach ($items as &$goal) {
$html .= "
<pre>
Account ID = {$goal->getAccountId()}
Web Property ID = {$goal->getWebPropertyId()}
Internal Web Property ID = {$goal->getInternalWebPropertyId()}
Profile ID = {$goal->getProfileId()}
Goal Number = {$goal->getId()}
Goal Name = {$goal->getName()}
Goal Value = {$goal->getValue()}
Goal Active = {$goal->getActive()}
Goal Type = {$goal->getType()}
Created = {$goal->getCreated()}
Updated = {$goal->getUpdated()}
</pre>";
// Now get the HTML for the type of goal.
switch($goal->getType()) {
case 'URL_DESTINATION':
$html .= getUrlDestinationDetailsHtml(
$goal->getUrlDestinationDetails());
break;
case 'VISIT_TIME_ON_SITE':
$html .= getVisitTimeOnSiteDetailsHtml(
$goal->getVisitTimeOnSiteDetails());
break;
case 'VISIT_NUM_PAGES':
$html .= getVisitNumPagesDetailsHtml(
$goal->getVisitNumPagesDetails());
break;
case 'EVENT':
$html .= getEventDetailsHtml(
$goal->getEventDetails());
break;
}
echo $html;
}
It seems like you are using the Management API. This is meant for management purposes only. Getting and setting goals.
If you want data from goals as well you want to be looking at the Core Reporting API.
The available data for goals can be found here:
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/goalconversions
The implementation guide can be found here:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
I did not provide a full implementation example seeing that you already know how to setup the use of a Google API.
Good luck with you quest!
EDIT:
Added an example on how to use it:
<?php
$client = new apiAnalyticsService();
function queryCoreReportingApi() {
$optParams = array( //OPTINAL SETTINGS
'dimensions' => '', //A comma-separated list of Multi-Channel Funnels dimensions. E.g., 'mcf:source,mcf:medium'. (string)
'sort' => '', //A comma-separated list of dimensions or metrics that determine the sort order for the Analytics data. (string)
'filters' => '', //A comma-separated list of dimension or metric filters to be applied to the Analytics data. (string)
'start-index' => '', //An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter. (integer, 1+)
'fields' => '', //Selector specifying which fields to include in a partial response.
'max-results' => '25'); //The maximum number of entries to include in this feed. (integer)
return $service->data_mcf->get(
$id, //Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID. (string)
'2010-01-01', //Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD. (string)
'2010-01-15', //End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD. (string)
'ga:totalConversions', //A comma-separated list of Multi-Channel Funnels metrics. E.g., 'mcf:totalConversions,mcf:totalConversionValue'. At least one metric must be specified. (string)
$optParams);
}
I currently have a php page that grabs information from a database and produces HTML with data attributes that are filled in by from the MySQL query. The database is going to be used to search, with many different options for searches.
What I need help with is knowing a way so to organize how the many variables are handled. It's a really big mess of code, and even with all the comments I put it gives me a headache trying to figure out how to add another variable to the search.
All the variables, except for the LIMIT to which row and how many results, are optional. So if someone leaves everything except that blank, I still want it to function as well as if they meticulously filled in all the fields.
Here's what I have, with 6 variables.
<?php
$product_size = "(".$_GET['size']." BETWEEN productsizeDOWN AND productsizeUP)"; // This code sets the variable to input into the MySQL string based on the URL
$product_size_check = $_GET['size']; // the _checks check are used to see if the value is or isn't empty using if statements below
$manufacturer = $_GET['manufacturer'];
$product_manufacterer_check = $_GET['manufacturer']; // _check
$product_invisible = "(hideproduct = '".$_GET['invisible']."')"; // Checks if product is hidden
$product_invisible_check = $_GET['invisible']; // _check
$product_instock_check = $_GET['instock']; // _check
$product_limit0 = $_GET['startat']; // This is the first number after LIMIT; the row to start in.
$product_limit1 = $_GET['results']; // This is how many results to load.
$manufacturer_array = explode(",", $manufacturer); // The manufacturer comes in as "Nike,Addidas,Rebok" and is turned into an array
$manufacturer_imploded = implode("' OR productmanufacturer = '", $manufacturer_array); // Puts it back together with "OR productmanufacturer =" between each name.
$product_manufacterer = ("(productmanufacturer = '".$manufacturer_imploded."')"); // formats it so it can be directly inserted into MySQL string with a WHERE in front.
if($product_invisible_check == ""){
$product_invisible = "";
}else{$where = "WHERE ";}; //Useless code that I havn't deleted that I tried to use when I searched the entire database
if($product_size_check == ""){
$product_size = "";
}else{$where = "WHERE ";};
if($product_manufacterer_check == ""){
$product_manufacterer = "";
}else{$where = "WHERE ";};
if($product_instock_check == "N"){
$product_instock = "(stockstatus <= '0' AND donotallowbackorders = 'Y') AND "; // Checks if product is in stock (Allowing backordering OR stock >1)
$where = "WHERE ";
}
elseif($product_instock_check == "Y") {
$product_instock = "(stockstatus > '0' OR donotallowbackorders = 'N') AND ";
$where = "WHERE ";
}
else {
$product_instock = "";
};
$sql="Select * FROM ioa7pd_Products WHERE ".$product_instock.$product_size."AND".$product_manufacterer_and.$product_manufacterer."".$product_invisible." LIMIT ".$product_limit0.", ".$product_limit1; // The end result of it all.
echo $sql;
?>
When the URL is
test.php?size=5&manufacturer=Nike,Addidas,Rebok&invisible=N&instock=Y&startat=0&results=30
the resulting SQL query is
Select * FROM ioa7pd_Products WHERE (stockstatus > '0' OR donotallowbackorders = 'N') AND (5 BETWEEN productsizeDOWN AND productsizeUP)AND(productmanufacturer = 'Nike' OR productmanufacturer = 'Addidas' OR productmanufacturer = 'Rebok')(hideproduct = 'N') LIMIT 0, 30
But I plan to add more options to the search.
My main question is simply: What way can I organize this to make it simple to add more variables? Tiered if statements?
Travesty has been helping me with my code and has really been great in organizing it.
Here is the current code. It needs to be secure to prevent injection.
// Database connection
$con = mysql_connect("[CENSORED]","[CENSORED]","[CENSORED]")
or die("Could not connect: " . mysql_error());
mysql_select_db("[CENSORED]") or die('Could not select database');
// Begin organization of URL variables into MYSQL Query
$get_size = $_GET['size'];
$get_manufacturer = $_GET['manufacturer'];
$get_invisible = $_GET['invisible'];
$get_instock = $_GET['instock'];
$get_sex = $_GET['sex'];
$get_startat = $_GET['startat'];
$get_results = $_GET['results'];
if ($get_size != ""){
$all_selectors[] = "(".$get_size." BETWEEN productsizeDOWN AND productsizeUP)"; // Add to array if size is not blank.
};
if ($get_manufacturer != ""){
$manufacturer_exploded = explode(",", $get_manufacturer);
$manufacturer_imploded = implode("' OR productmanufacturer = '", $manufacturer_exploded);
$all_selectors[] = ("(productmanufacturer = '".$manufacturer_imploded."')");
};
if ($get_invisible != ""){
$all_selectors[] = "(hideproduct = '".$get_invisible."')";
};
if($get_instock == "N" or $get_instock == "n"){
$all_selectors[] = "(stockstatus <= '0' AND donotallowbackorders = 'Y')";
}elseif($get_instock == "Y" or $get_instock == "y") {
$all_selectors[] = "(stockstatus > '0' OR donotallowbackorders = 'N')";
};
if ($get_startat != "" or $get_results != ""){
$number_results = "LIMIT ".$get_startat.", ".$get_results;
} else {
$number_results = "LIMIT 0, 15";
};
// All variables are now in an array, except "startat" and "results"
$all_selectors0 = "WHERE ".implode(" AND ", $all_selectors);
// Create SQL query
$sql="Select * FROM sadsads_Products ".$all_selectors0." ".$number_results;
I would do something more like this. It's not tested and probably not 100% complete...you may need to do some further customization, particularly with adding more special cases to the switch statement, but this will make adding more variables much easier:
REMOVED OLD EXAMPLE, SEE UPDATED EXAMPLE BELOW
One key thing to note is that you aren't sanitizing your database inputs. Your code is vulnerable to SQL injection. My example above helps to solve that, but this code isn't fully tested, so you should ensure that all user input is sanitized before using it in any query.
If your field names don't match up with your MySQL columns (which it looks like they don't), then you can fix them with an associative array:
$columns = array(
// [form field] => [mysql column]
'size' => 'product_size',
'manufacturer' => 'product_manufacturer',
'invisible' => 'hideproduct'
// ...
);
And then in your switch statement, do something more like this:
$whereClause[] = "{$columns[$key]} = '{$value}'";
FINAL UPDATE:
DOCUMENTED SAMPLE - has plenty of comments and extra stuff to make it work on Codepad
EXACT WORKING CODE - you should be able to copy and paste this (and add your DB credentials) and it should work:
$con = mysqli_connect("[CENSORED]", "[CENSORED]", "[CENSORED]") or die("Could not connect: ". mysqli_error());
mysqli_select_db("[CENSORED]") or die("Could not select database");
$columns = array(
'size' => 'product_size',
'manufacturer' => 'product_manufacturer',
'invisible' => 'hideproduct'
);
$whereClause = array();
$limit = array("startat" => 0, "results" => 15);
foreach ($_GET as $key=>$value) {
$key = mysqli_real_escape_string($key);
if (is_array($value)) {
for ($i = 0; $i < count($value); $i++) {
$value[$i] = mysqli_real_escape_string($value[$i]);
}
} else {
$value = mysqli_real_escape_string($value);
}
switch ($key) {
case 'size':
$whereClause[] = "({$value} BETWEEN productsizeDOWN AND productsizeUP)";
break;
case 'startat':
case 'results':
$limit[$key] = $value;
break;
case 'instock':
$whereClause[] = "(stockstatus ". ($value == 'N' ? "<=" : ">") ." '0' ". ($value == 'N' ? "AND" : "OR") ." donotallowbackorders = '". ($value == 'N' ? "Y" : "N") ."')";
break;
default: {
if (is_array($value)) {
$whereClause[] = "{$columns[$key]} IN ('". implode("', '", $value) ."')";
} else {
$whereClause[] = "{$columns[$key]} = '{$value}'";
}
}
}
}
$sql = "SELECT * FROM ioa7pd_Products". (empty($whereClause) ? "" : " WHERE ". implode(" AND ", $whereClause)) ." LIMIT {$limit['startat']}, {$limit['results']}";
echo $sql;
after
else {
$product_instock = "";
};
do:
$limit = '';
if( !empty($product_limit0) && !empty($product_limit1) )
$limit = " LIMIT $product_limit0, $product_limit1";
$sql="Select * FROM ioa7pd_Products WHERE ".$product_instock.$product_size."AND".$product_manufacterer_and.$product_manufacterer."".$product_invisible." $limit"; // The end result of it all.
echo $sql;
If you have separate params in $_GET, you would have to traverse with multiple if statements. you can pass the params as an array into $_GET, with numeric keys, that would help a bunch.
Are there any APIs that can extract moods from a string (for use in PHP but can be implemented in any language)?
If one doesn't exist, how would I go about building a classifier, presumably something related to machine learning, where I extract words with known positive/negativity.
I would suggest AlchemyAPI. They have pretty simple APIs ( which shouldn't be difficult to use. For your specific case, look into here
Using the above suggestion of AlchemyapI, here is a really simple system based on Facebook statuses'
$id = CURRENT USER ID;
$message = array(); //the users posts with scores
$status = $fb->fql("SELECT status_id, message FROM status WHERE uid=$id LIMIT 10");
foreach($status as $stat) {
$message = file_get_contents("http://access.alchemyapi.com/calls/text/TextGetTextSentiment"
."?outputMode=json&apikey=MYAPIKEY"
."&text=".urlencode($stat['message']));
$data = json_decode($message); //get reply
$messages[] = array("status"=>$stat['message'], "score"=>($data->docSentiment->type!="neutral") ? $data->docSentiment->score : 0); //save reply
}
$user = $fb->api("/".$id); //query the user
$content .= "<h3>".$user['name']."</h3>";
$total = 0;
$count = 0;
foreach($messages as $message) {
$total += $message['score'];
if($message['score']!=0) $count++;
}
$content .= 'Has an average rating of '.$total/$count.' <meter min="-1" max="1" value="'.$total/$count.'"></meter><br /><br />';
foreach($messages as $message) {
$content .= '<b>'.$message['status'].'</b> '.$message['score'].'</br>'
.'<meter ' //class="'.($message['score'] == 0 ? "yellow" : $message['score'] < 0 ? "red" : "green").'" '
.'value="'.$message['score'].'" min="-0.5" max="0.5" optimum="0">'.$message['score'].' out of -1 to 1</meter><br /><br />';
}