Dynamic content being cached - php

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

Related

Hide individual sections of a RSFormPro form when submission limit has been reached

I use RsForm Pro on Joomla CMS, and there I have created a form. In my form, I have 5 sections with a checkbox. I want to display individual sections up to a certain limit (let's say a max of 20 users), after the submission limit has been reached the form section needs to be disabled.
I found a limit for submit form, but if 20 users submit only one section in the form (not for checkbox), another 4 can't be available for other users. In other words, I don't want to disable all sections unless all sections have reached there limit.
This is code for limit submit form:
// Define the maximum number of submissions. For this example we'll use 25.
$max = 25;
// Get a database connection.
$db = JFactory::getDbo();
// Setup the query. This query counts the number of submissions for the current form.
// $formId contains the ID of the current form.
$db->setQuery("SELECT COUNT(`SubmissionId`) FROM #__rsform_submissions WHERE `FormId`='".(int) $formId."'");
$submissions = $db->loadResult();
if ($submissions >= $max) {
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!.';
}
EDIT SOLVED:
$limit25 = 25;
$limit21 = 21;
$limit20 = 20;
$db = JFactory::getDbo();
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 11th'");
$first_submission_value = $db->loadResult();
if ($first_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-11th { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 13'");
$secont_submission_value = $db->loadResult();
if ($second_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-13 { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'Bus_Blockchain_March 18'");
$third_submission_value = $db->loadResult();
if ($third_submission_value >= $limit25) {
echo '<style>.rsform-block-bus-blockchain-march-18 { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA'");
$fourth_submission_value = $db->loadResult();
if ($fourth_submission_value >= $limit20) {
echo '<style>.rsform-block-evening-qa { display:none;}</style>';
}
$db->setQuery("SELECT COUNT(`FieldName`) FROM `nqm2i_rsform_submission_values` WHERE `nqm2i_rsform_submission_values`.`FieldName` = 'evening_QA_2'");
$fifth_submission_value = $db->loadResult();
if ($fifth_submission_value >= $limit21) {
echo '<style>.rsform-block-evening-qa-2 { display:none;}</style>';
}
if(
$first_submission_value >= $limit25
&& $secont_submission_value >= $limit25
&& $third_submission_value >= $limit25
&& $fourth_submission_value >= $limit20
&& $fifth_submission_value >= $limit21
) {
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
}
I see that you have edited your question to reveal your solution. Rather than to ask you to post your solution as an answer (which you should have done), I'll do you one better -- I've taken the time to refactor your code, implement Joomla's query building methods, make it more efficient, cleaner, more direct, and easier to manage.
Most importantly, because all of the database interactions can be performed with a single query, they should be.
Because your field names seamlessly relate to your classnames, a "lookup array" or "mapping array" will allow my snippet to reliably deliver your desired results dynamically. You will never need to adjust more than $formId and $field_maxes.
Code: (tested locally with my own rsform pro table)
$formId = 3; // or whatever the correct formId value is
$field_maxes = [
'Bus_Blockchain_March 11th' => 25,
'Bus_Blockchain_March 13' => 25,
'Bus_Blockchain_March 18' => 25,
'evening_QA' => 20,
'evening_QA_2' => 21
];
$classes_to_hide = []; // initiate as empty array
$formLayout = ''; // initiate as empty string
$db = JFactory::getDbo();
$quoted_fields = implode(',', $db->q(array_keys($field_maxes))); // create quoted comma-separated values
$query = $db->getQuery(true)
->select("FieldName, COUNT(1) AS " . $db->qn("Count"))
->from("#__rsform_submission_values")
->where([
"FormId = " . (int) $formId,
"FieldName IN ($quoted_fields)"
])
->group("FieldName")
->order("FIELD ($quoted_fields)");
// if you wish to see the rendered query, uncomment the next line (do not show to public)
// JFactory::getApplication()->enqueueMessage("<div>" . $query->dump() . "</div>", "notice");
try // listen for syntax errors
{
$db->setQuery($query);
if (!$results = $db->loadAssocList()) // declare and check for empty result set
{
echo "No Results in Form";
}
else
{
foreach ($results as $row) // iterate rows
{
if ($row['Count'] >= $field_maxes[$row['FieldName']]) { // if fieldname has reached limit
$classes_to_hide[] = ".rsform-" . str_replace(['_', ' '], '-', $row['FieldName']);
}
}
if ($tally = sizeof($classes_to_hide)) // declare and check if not empty
{
echo "<style>" , implode(", ", $classes_to_hide) , " {display:none;}</style>"; // apply css styling to one or more designated classes
if ($tally == sizeof($field_maxes)) // if all fieldnames are full
{
$formLayout = 'Sorry, we have no more spaces on this time. Please wait next registration. Thank you!';
}
}
}
}
catch (Exception $e)
{
JFactory::getApplication()->enqueueMessage("Query Syntax Error", "error");
// if you have a syntax error and wish to see the message, uncomment the next line (do not show to public)
//JFactory::getApplication()->enqueueMessage($e->getMessage(), "error");
}

PHP Suggest Jobs within Location set by user field

Got a strange problem here on my little project, I have an account area that people can set a location so we can suggest job openings within the area they live in.
EDIT: Code indented - Sorry
The locations that do not work are "Maidstone" & "Medway". These locations are all stored in the database, When another user adds a job they can set the location the job is in and that will then add that job to the database under "State" String.
Other Locations such as Canterbury do work and the jobs that are listed under the Canterbury location show up on the users account as they should.
This php works for every location other then 2 of them which is really strange.
<?php
class SJB_Classifieds_SuggestedJobs extends SJB_Function
{
public function execute()
{
$tp = SJB_System::getTemplateProcessor();
$count_listing = SJB_Request::getVar('count_listing', 10, null, 'int');
$current_user = SJB_UserManager::getCurrentUser();
$properties = $current_user->getProperties();
foreach ($properties as $property) {
if ($property->getType() == 'location') {
$fields = $property->type->child;
$childProperties = $fields->getProperties();
foreach ($childProperties as $childProperty) {
if (in_array($childProperty->getID(), array('State'))) {
$value = $childProperty->getValue();
switch ($childProperty->getType()) {
case 'list':
if ($childProperty->getID() == 'State') {
$displayAS = $childProperty->display_as;
$displayAS = $displayAS?$displayAS:'State';
$listValues = SJB_StatesManager::getStatesNamesByCountry(false, true, $displayAS);
}
else
$listValues = $childProperty->type->list_values;
foreach ($listValues as $values) {
if ($value == $values['id'])
$phrase[strtolower($childProperty->getID())] = $values['caption'];
}
break;
default:
$phrase[strtolower($childProperty->getID())] = $value;
break;
}
}
}
}
}
$phrase = array_diff($phrase, array(''));
$phrase = implode(" ", $phrase);
$listing_type_id = "Job";
$request['action'] = 'search';
$request['listing_type']['equal'] = $listing_type_id;
$request['default_listings_per_page'] = $count_listing;
$request['default_sorting_field'] = "activation_date";
$request['default_sorting_order'] = "DESC";
$request['keywords']['relevance'] = $phrase;
$searchResultsTP = new SJB_SearchResultsTP($request, $listing_type_id, array('field'=>'keywords', 'value'=>$phrase));
$tp = $searchResultsTP->getChargedTemplateProcessor();
$tp->display('suggested_jobs.tpl');
}
}
Not sure if my problem is due to the PHP that tells which jobs to display.
Could someone just skip though the PHP and let me know if anythings wrong? I really want to work this out on my own however I'm alittle lost and if i can find out that the PHP is fine then I can figure it out some where else :)
Thanks!

Passing parameters to a function in yii

I am new to yii. I've created a custom in button in CGridView that has a class of CButtonColumn. I'm just wondering how can I pass parameters that I can add to my php function in my model.
This is my custom button in the table
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
'click'=>$model->approveRegistrants("$user_id, $category", array("id"=>$data->user_id , "category"=>$data->category),
)
)
)
and this is my function is
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
your issue is that you are bypassing the controller fully here.
buttons column is configured with the following parameters
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)
See CButtonColumn for details.
As you can see click has to be a js function that will be called on clicking the button. You can rewrite your button like this
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(),
// Alternative -1 Url Method -> will cause page to change to approve/id
'url'=>'array("approve","id"=>$data->id)',
// Alternative -2 Js method -> use 1,2 not both
'click'=>'js:approve()',
)
)
)
in your CGridView configuration you add
array(
....
'id'=>'gridViewID', //Unique ID for grid view
'rowHtmlOptionsExpression'=> 'array("id"=>$data->id)',
)
so that each row has the unique ID, ( you can do the same to a button, but it slightly more difficult as $data is not available there)
in your js function you can do this.
<script type="text/javascript">
function approve(){
id = $(this).parent().parent().attr("id");
<?php echo CHtml::ajax(array( // You also can directly write your ajax
'url'=>array('approve'),
'type'=>'GET',
'dataType'=>'json',
'data'=>array('id'=>'js:id'),
'success'=>'js:function(json){
$.fn.yiiGridView.update("gridViewID",{});
// this will refresh the view, you do some other logic here like a confirmation box etc
}'
));?>
}
</script>
Finally your approve action
class YourController extend CController {
......
public function actionApprove(){
id = Yii::app()->request->getQuery('id');
$dataModel = MyModel::model()->findByPk($id); // This is the model has the $user_id, and $category
....
$OtherModel->approve($dataModel->user_id,$dataModel->category) // if approve is in the same model you can self reference the values of category and user_id directly no need to pass as parameters.
// Do some logic based on returned value of $otherModel->approve()
// return the values from the approve() function and echo from here if required back to the view, directly echoing output makes it difficult to debug which function and where values are coming from .
Yii::app()->end();
}

PHP Search Script Enhancement

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.

Most effective way of data collection?

Let's first get to an important note about my situation:
I have 1 table in my MySQL database with approx 10 thousand entries
Currently, when collecting information from table #1. I collect a total of 20 - 24 rows per page.
Example being:
Q1 : SELECT * FROM table WHERE cat = 1 LIMIT 0,25
R1: id: 1, name: something, info: 12
The PHP file that does these queries, is called by the jquery ajax function, and creates an XML file that that jquery function reads and shows to the user.
My question here is. How do i improve the speed & stability of this process. I can have up to 10 thousand visitors picking up information at the same time, which makes my server go extremely sluggish and in some cases even crash.
I'm pretty much out of idea's, so i'm asking for help here. Here's an actual presentation of my current data collection (:
public function collectItems($type, $genre, $page = 0, $search = 0)
{
// Call Core (Necessary for Database Interaction
global $plusTG;
// If Search
if($search)
{
$searchString = ' AND (name LIKE "%'.$search.'%")';
}
else
{
$searchString = '';
}
// Validate Query
$search = $plusTG->validateQuery($search);
$type = $plusTG->validateQuery($type);
$genre = $plusTG->validateQuery($genre);
// Check Numeric
if((!is_numeric($genre)))
{
return false;
}
else
{
if(!is_numeric($type))
{
if($type != 0)
{
$typeSelect = '';
$split = explode(',',$type);
foreach($split as $oneType)
{
if($typeSelect == '')
{
$typeSelect .= 'type = '.$oneType.' ';
}
else
{
$typeSelect .= 'OR type = '.$oneType.' ';
}
}
}
}
else
{
$typeSelect = 'type = ' . $type . ' ';
}
//echo $typeSelect;
$limit = ($page - 1) * 20;
if(($type != 0) && ($genre != 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND genre = '.$genre.' AND ('.$typeSelect.')'.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND genre = '.$genre.' AND ('.$typeSelect.')'.$searchString);
}
elseif(($type == 0) && ($genre != 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND genre = '.$genre.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND genre = '.$genre.$searchString);
}
elseif(($type != 0) && ($genre == 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1 AND ('.$typeSelect.')'.$searchString.'ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1 AND ('.$typeSelect.')'.$searchString);
}
elseif(($type == 0) && ($genre == 0))
{
$items = $plusTG->db->query('SELECT * FROM dream_items WHERE active = 1'.$searchString.' ORDER BY name LIMIT '.$limit.',20');
$total = $plusTG->db->query('SELECT COUNT(*) as items FROM dream_items WHERE active = 1'.$searchString);
}
$this->buildInfo($items->num_rows, $total->fetch_assoc());
while($singleItem = $items->fetch_assoc())
{
$this->addItem($singleItem);
}
}
return true;
}
The build info call & add item call are adding the items to the DOMXML.
This is my javascript (domain and filename filtered):
function itemRequest(type,genre,page, search)
{
if(ajaxReady != 0)
{
ajaxReady = 0;
$('#item_container').text('');
var searchUrl = '';
var searchLink;
var ajaxURL;
if(search != 0)
{
searchUrl = '&search=' + search;
searchLink = search;
ajaxURL = "/////file.php";
}
else
{
searchLink = 0;
ajaxURL = "////file.php";
}
$.ajax({
type: "GET",
url: ajaxURL,
data: "spec=1&type="+type+"&genre="+genre+"&page="+page+searchUrl,
success: function(itemListing){
$(itemListing).find('info').each(function()
{
var total = $(this).find('total').text();
updatePaging(total, page, type, genre, searchLink);
});
var items = $(itemListing).find('items');
$(items).find('item').each(function()
{
var itemId = $(this).find('id').text();
var itemType = $(this).find('type').text();
var itemGenre = $(this).find('genre').text();
var itemTmId = $(this).find('tm').text();
var itemName = $(this).find('name').text();
buildItem(itemId, itemType, itemGenre, itemTmId, itemName);
});
$('.item_one img[title]').tooltip();
},
complete: function(){
ajaxReady = 1;
}
});
}
Build item calls this:
function buildItem(itemId, itemType, itemGenre, itemTmId, itemName)
{
// Pick up Misc. Data
var typeName = nameOfType(itemType);
// Create Core Object
var anItem = $('<div/>', {
'class':'item_one'
});
// Create Item Image
$('<img/>', {
'src':'///'+typeName+'_'+itemTmId+'_abc.png',
'alt':itemName,
'title':itemName,
click:function(){
eval(typeName + 'Type = ' + itemTmId);
$('.equipped_item[name='+typeName+']').attr('src','//'+typeName+'_'+itemTmId+'_abc.png');
$('.equipped_item[name='+typeName+']').attr('alt',itemName);
$('.equipped_item[name='+typeName+']').attr('title',itemName);
$('.equipped_item[title]').tooltip();
recentEquipped(typeName, itemTmId, itemName);
updateSelfy();
}
}).appendTo(anItem);
// Favs
var arrayHack = false;
$(favEquips).each(function(){
if(arrayHack == false)
{
if(in_array(itemTmId, this))
{
arrayHack = true;
}
}
});
var itemFaved = '';
if(arrayHack == true)
{
itemFaved = 'activated';
}
$('<div/>',{
'class':'fav',
'id':itemFaved,
click:function(){
if($(this).attr('id') != 'activated')
{
$(this).attr('id','activated');
}
else
{
$(this).removeAttr('id');
}
itemFav(itemTmId, typeName, itemName);
}
}).appendTo(anItem);
$(anItem).appendTo('#item_container');
}
If anyone could help me improve this code, it'd be very much appreciated.
add an index to your table for cat column
figure out what the bottleneck is, if it is your XML then try json,
if it is your network, try enabling gzip compression
I agree with Zepplock, it is important to find out where the bottleneck is - if not, you're only guessing. Zepplock's list is good but I would also add caching:
Find out where the bottleneck is.
Use indexes in your db table.
Cache your query results
Find the Bottleneck.
There are number opinions and ways to do this... Basically when your site is under load, get the time it takes to complete each step in the process: The DB queries, the server-side processes, the client side processes.
Use Indexes.
If your DB is slow chances are you can get a lot of improvement by optimizing your queries. A table index may be in order... Use 'EXPLAIN' to help identify where indexes should be placed to optimize your queries:
EXPLAIN SELECT * FROM dream_items WHERE active = 1 AND (name LIKE "%foo%") ORDER BY name LIMIT 0,20;
(I bet an index on active and name would do the trick)
ALTER TABLE `dream_items` ADD INDEX `active_name` (`active` , `name`);
Also try to avoid using the wildcard '*'. Instead only ask for the columns you need. Something like:
SELECT `id`, `type`, `genre`, `tm`, `name` FROM `dream_items` WHERE...
Cache Your Results.
If the records in the DB have not changed then there is no reason to try an re-query the results. Use some sort of caching to reduce the load on your DB (memcached, flat file, etc..). Depending on the database class / utilities you're using it may already be capable of caching results.

Categories