Showing posts with label PROGRAMMING. Show all posts
Showing posts with label PROGRAMMING. Show all posts

Friday, September 7, 2012

Mysql error 1093 - Can't specify target table for update in FROM clause

Mysql error 1093 - Can't specify target table for update in FROM clause

Q : 

I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries:

SELECT * FROM story_category WHERE category_id NOT IN (
SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id);


I tried to delete them excuting:
DELETE FROM story_category WHERE category_id NOT IN (
SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id);

but I get the next error:

#1093 - You can't specify target table 'story_category' for update in FROM clause

How can I overcome this?

: Solution :


In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at: 
http://dev.mysql.com/doc/refman/5.6/en/update.html

You will need to stop using the nested subquery and execute the operation in two parts, or alternatively use a simple where clause.

Below is from Baron Schwartz, published at Nabble:

However, you can do multi-table updates like this:UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col


If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance:
UPDATE tbl SET col = (
SELECT ... FROM (SELECT.... FROM) AS x);

The nested subquery in the FROM clause creates an implicit temporary table, so it doesn't count as the same table you're updating.

You can Also Try 

Solution 2 : 



The inner join in your subquery is unnecessary. It looks like you want to delete the entries in story_category where the category_id is not in the category table.
Instead of this:


DELETE FROM story_category WHERE category_id NOT IN (SELECT DISTINCTcategory.id FROM category INNER JOINstory_category ONcategory_id=category.id);


Do this:
DELETE FROM story_category WHERE category_id NOT IN (SELECT DISTINCTcategory.id FROM category);




Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India


Monday, September 3, 2012

How do I check a checkbox with jQuery or JavaScript?


How do I check a checkbox with jQuery or JavaScript?

 
jQuery 1.6+


: Solution : 

Use the new .prop() function:
$(".myCheckbox").prop("checked", true);
$(".myCheckbox").prop("checked", false);


jQuery 1.5 and below

The .prop() function is not available, so you need to use .attr().

To check the checkbox (by setting the value of the checked attribute) do $('.myCheckbox').attr('checked','checked')



and for un-checking (by removing the attribute entirely) do $('.myCheckbox').removeAttr('checked')


Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.checked = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.


if (this.checked) 
// Assuming an event handler on a checkbox




:D
Steel facing probs ? let me know by comments !

Know More About :
PHP Freelancing India


Saturday, September 1, 2012

How to format a JSON date?

How to format a JSON date? Problems with Json Date ?


jsonDate :
         /Date(1224043200000)/



Solution : 
var date = new Date(parseInt(jsonDate.substr(6)));


 
The substr function takes out the "\/Date(" part, and the parseInt function gets the integer and ignores the ")\/" at the end. The resulting number is passed into the Date constructor.

Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India



Friday, August 31, 2012

Get query string values in JavaScript

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how, and if not what plugin do you recommend?
You don't need jQuery for that purpose you can use the pure JavaScript


function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}


Cheers ! 
Hope you got the Ans ! 
still having probs ? let me know by comments ! 



Know More About :

Thursday, August 30, 2012

Testing if something is hidden with jQuery, Check Form Element is hidden



Testing if something is hidden with jQuery, Check Form Element is hidden



In jQuery, suppose you have an element of some kind that you're hiding and showing, using .hide(),.show() or .toggle(). How do you test to see if that element is currently hidden or visible on the screen?


$(element).is(":visible") 




Hope you got the Ans !
still having probs ? let me know by comments !




Know More About :
PHP Freelancing India 

Tuesday, August 28, 2012

How to get select radiobutton value using its name in jQuery? Getting the value of a selected radio button out of a radio group in jQuery.

How to get select radiobutton value using its name in jQuery? 

Getting the value of a selected radio button out of a radio group in jQuery.



Just want to point out that Jeff's answer might suit others because it can be used to get the value from anywhere, not just within a click handler for the radio button. here is preety simple solution. 

$('input:radio[name=theme]:checked').val();



:D 
Steel facing probs ? let me know by comments ! 




Know More About :
PHP Freelancing India 


Sunday, July 15, 2012

What should every programmer know about web development?

Hi Googler,
Feeling Good while  writing for Web Development. :) 

Lets get in to the topic. What matters a good programmer needs to care about.

Technology:

  • Understand HTTP and things like GET, POST, sessions, cookies, and what it means to be "stateless".
  • Write your XHTML/HTML and CSS according to the W3C specifications and make sure they validate. The goal here is to avoid browser quirks modes and as a bonus make it much easier to work with non-standard browsers like screen readers and mobile devices.
  • Understand how JavaScript is processed in the browser.
  • Understand how JavaScript, style sheets, and other resources used by your page are loaded and consider their impact on perceived performance. It may be appropriate in some cases to move scripts to the bottom of your pages.
  • Understand how the JavaScript sandbox works, especially if you intend to use iframes.
  • Be aware that JavaScript can and will be disabled, and that AJAX is therefore an extension, not a baseline. Even if most normal users leave it on now, remember that NoScript is becoming more popular, mobile devices may not work as expected, and Google won't run most of your JavaScript when indexing the site.
  • Learn the difference between 301 and 302 redirects (this is also an SEO issue).
  • Learn as much as you possibly can about your deployment platform.
  • Consider using a Reset Style Sheet.
  • Consider JavaScript frameworks (such as jQuery, MooTools, Prototype, Dojo or YUI 3), which will hide a lot of the browser differences when using JavaScript for DOM manipulation.
  • For XML processing and HTML DOM updates, consider XSLT 2.0 running within a JavaScript processor app (such as Saxon-CE) - this can interoperate with JS and handle user-events (with matching templates) also.
  • Taking perceived performance and JS frameworks together, consider using a service such as theGoogle Libraries API to load frameworks so that a browser can use a copy of the framework it has already cached rather than downloading a duplicate copy from your site.
  • Don't reinvent the wheel. Before doing ANYTHING search for a component or example on how to do it. There is a 99% chance that someone has done it and released an OSS version of the code.


Bug fixing


  • Understand you'll spend 20% of your time coding and 80% of it maintaining, so code accordingly.
  • Set up a good error reporting solution.
  • Have a system for people to contact you with suggestions and criticisms.
  • Document how the application works for future support staff and people performing maintenance.
  • Make frequent backups! (And make sure those backups are functional) Ed Lucas's answer has some advice. Have a restore strategy, not just a backup strategy.
  • Use a version control system to store your files, such as Subversion, Mecurial or Git.
  • Don't forget to do your Acceptance Testing. Frameworks like Selenium can help.
  • Make sure you have sufficient logging in place using frameworks such as log4j, log4net or log4r. If something goes wrong on your live site, you'll need a way of finding out what.
  • When logging make sure you're capture both handled exceptions, and unhandled exceptions. Report/analyse the log output, as it'll show you where the key issues are in your site.

  • Lots of stuff omitted not necessarily because they're not useful answers, but because they're either too detailed, out of scope, or go a bit too far for someone looking to get an overview of the things they should know. If you're one of those people you can read the rest of the answers to get more detailed information about the things mentioned in this list. If I get the time I'll add links to the various answers that contain the things mentioned in this list if the answers go into detail about these things. Please feel free to edit this as well, I probably missed some stuff or made some mistakes.


SEO (Search Engine Optimization)


  1. Use "search engine friendly" URLs, i.e. use example.com/pages/45-article-title instead ofexample.com/index.php?page=45
  2. When using # for dynamic content change the # to #! and then on the server$_REQUEST["_escaped_fragment_"] is what googlebot uses instead of #!. In other words,./#!page=1 becomes ./?_escaped_fragments_=page=1. Also, for users that may be using FF.b4 or Chromium, history.pushState({"foo":"bar"}, "About", "./?page=1"); Is a great command. So even though the address bar has changed the page does not reload. This allows you to use ? instead of #! to keep dynamic content and also tell the server when you email the link that we are after this page, and the AJAX does not need to make another extra request.
  3. Don't use links that say "click here". You're wasting an SEO opportunity and it makes things harder for people with screen readers.
  4. Have an XML sitemap, preferably in the default location /sitemap.xml.
  5. Use <link rel="canonical" ... /> when you have multiple URLs that point to the same content, this issue can also be addressed from Google Webmaster Tools.
  6. Use Google Webmaster Tools and Bing Webmaster Tools.
  7. Install Google Analytics right at the start (or an open source analysis tool like Piwik).
  8. Know how robots.txt and search engine spiders work.
  9. Redirect requests (using 301 Moved Permanently) asking for www.example.com to example.com(or the other way round) to prevent splitting the google ranking between both sites.
  10. Know that there can be badly-behaved spiders out there.
  11. If you have non-text content look into Google's sitemap extensions for video etc. There is some good information about this in Tim Farley's answer.


Performance


  • Implement caching if necessary, understand and use HTTP caching properly as well as HTML5 Manifest.
  • Optimize images - don't use a 20 KB image for a repeating background. php.
  • Learn how to gzip/deflate content (deflate is better).
  • Combine/concatenate multiple stylesheets or multiple script files to reduce number of browser connections and improve gzip ability to compress duplications between files.
  • Take a look at the Yahoo Exceptional Performance site, lots of great guidelines including improving front-end performance and their YSlow tool. Google page speed is another tool for performance profiling. Both require Firebug to be installed.
  • Use CSS Image Sprites for small related images like toolbars (see the "minimize HTTP requests" point)
  • Busy web sites should consider splitting components across domains. Specifically...
  • Static content (i.e. images, CSS, JavaScript, and generally content that doesn't need access to cookies) should go in a separate domain that does not use cookies, because all cookies for a domain and its subdomains are sent with every request to the domain and its subdomains. One good option here is to use a Content Delivery Network (CDN).
  • Minimize the total number of HTTP requests required for a browser to render the page.
  • Utilize Google Closure Compiler for JavaScript and other minification tools.
  • Make sure there’s a favicon.ico file in the root of the site, i.e. /favicon.ico. Browsers will automatically request it, even if the icon isn’t mentioned in the HTML at all. If you don’t have a/favicon.ico, this will result in a lot of 404s, draining your server’s bandwidth.


Security






Interface and User Experience


Hope this post will be helpful a lot.
For more Please check: http://programmers.stackexchange.com


Ads:

Monday, September 19, 2011

Search for patterns in text using regular expressions


Hi Googler,
Few times i was in need to find some pieces of code to do some stuff. Searching for some pattern in text can be easy, and this class i made makes it look neat. In this article some terms will be used, like regular expressions. This article is not going to show how to work with regular expressions ( in future text: regEx ).
I will give you few useful resources to find out more if you are not familiar with regEx:
Search for patterns in text using regular expressions
Regular Expressions 

Class construction : 

This class is going to be pretty simple. It is going to have only six methods including constructor in which will some initialization happen. This class is going to have two setter methods, one for set text in which will search stuff happen, and one for pattern setting. One of methods will be search method which does not take any parameters. This class is basically heart of this class. It initializes search inside haystack text. There are also going to be two methods to return data. One to return array of results, and one to return string representation of search result. Class also contains three protected properties which are part of mechanism. I am not going to dissect every method separately because they are well explained with in-code comments and provided class documentation. Here is class source code.
--------------------------------------------------------------------------------
/**
* This class is used to do a search over needle in a haystack
* @author Bhavin Rana
*/
class SearchPattern {
/**
* This is haystack, subject of search
* @access protected
* @var string
*/
protected $_haystack;
/**
* This is needle, pattern of search
* @access protected
* @var string
*/
protected $_needle;
/**
* This is array of all matches of search
* @access protected
* @var array
*/
protected $_matches;
/**
* This is constructor method
*/
public function __construct(){
// Inizialize _matches as array type
$this -> _matches = array();
}
/**
* This is setter of haystack property
* @param string $haystack
* @access public
*/
public function setHaystack( $haystack ){
// Check if parameter is string and not empty
if( is_string( $haystack ) && !empty( $haystack ) ){
// Set haystack property
$this -> _haystack = $haystack;
}
}
/**
* This is setter of needle property
* @param string $needle
* @access public
*/
public function setNeedle( $needle ){
// Check if parameter is string and not empty
if( is_string( $needle ) && !empty( $needle ) ){
// Set haystack property
$this -> _needle = $needle;
}
}
/**
* This method is used to do search over needle in a haystack
* @access public
*/
public function search(){
// Search in haystack for needles
// Output matches into array
preg_match_all( $this -> _needle, $this -> _haystack, $this -> _matches );
}
/**
* This method returns result array
* @access public
* @return array
*/
public function toArray(){
// Return array
return $this -> _matches;
}
/**
* This method returns result string
* Every result item is formated to a new row
* @access public
* @return string
*/
public function toString(){
// Initialize output string variable
$output = "";
// Foreach match
foreach( $this -> _matches[0] as $match ) $output .= $match . "<br/>";
// Finally, return stringž
return $output;
}
}
Within download package is provided very simple example code for you to see what can be achieved with this small, but powerful class.

Download source code, documentation and example package

Download Now



hope this post helped, let me know via comments 
if any questions.


Know More About :
PHP Freelancing India

Wednesday, September 14, 2011

Open-source project ports Android apps to iOS




A new open-source project entitled “In The Box” hopes to make the job of porting Android applications over to Apple’s iOS platform much easier by providing tools that can take a ready-coded Android app, execute and test it on different iOS devices and then submit the binary to Apple’s App Store.
In The Box operates by taking the Dalvik virtual machine from Google’s Android operating system and allows it to run alongside tools provided for iOS apps, requiring little or no changes to the code to get the apps in the App Store.
Currently, the process is a complicated one – the project requires a decent amount of technical knowledge and an understanding of both the Android SDK and iOS development applications. The official website includes a video of a demonstration app, but only shows how to port a simple “Hello World” application, not a dedicated Android Market title.
Whether Apple would approve such apps remains to be seen and we imagine there could be issues with specific functions and hardware support. But, as it stands, there seems to be a bonafide way to be able to get Android apps ported over to iOS.

for projects mail me on:
bhavinrana07[@]gmail.com


Sunday, July 17, 2011

[PHP] What is the difference between sort & asort in php ?



Many times developers are not aware with the core functions of PHP. PHP have sort and asort built in array functions. You may or may not be aware with these functions. But when you will face a PHP interview than you may be asked for this question. What is the difference between sort & asort in php ? From the name itself, you can say it will sort an array elements but you may not be aware with the exact difference.
sort() function will sort an array by values and array keys will be automatically reset.
asort() function will sort an array by values and array keys will be the same as per original array.
<?php
$fruits = array(“lemon”, ”orange”, ”banana”, ”apple”);
sort($fruits);
foreach ($fruits as $key => $val) {
echo ”fruits[" . $key . "] = ” . $val . ”\n”;
}
?>
o/p:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>
o/p:
c = apple
b = banana
d = lemon
a = orange

CakePHP PaginatorHelper-Sorting problem solved


Hello Friends,
CakePHP provide its own Pagination helper using which you can easily add paging and sorting functionality in your CakePHP application. Using this helper class for one model, all instruction is given in below link. If you works with more than one model. means using belongsTo or hasManyrelation and getting records from more than one table than paging is as simple as one table. But for sorting, you might face some problem. This can be solved by adding Model name before field name. Look at below syntax.

$paginator->sort(‘Title’, ‘Category.title’); ?>
If you find any problem in this than let me know by comment.

Integrate WordPress Blog into CakePHP Application


Hello Friends,
I have worked on CakePHP application like Customer Relationship Management (CRM),Content Management Systems(CMS),Online bidding application and many more. After working on CakePHP application, Our company’s head decided to make organization’s website into CakePHP and assigned the project to me. It has not great functionality. Its a simple CMS website. But the concern is to use WordPress Blog along with CakePHP application as it is used for posting some business news.
For integrating blog along with CakePHP application, you can simply install blog in /blog directory inside main CakePHP directory. Now you just need to write couple of .htaccess rules which i had written below. Please find .htaccess file in main CakePHP folder(root).
RedirectMatch temp ^/blog/wp-admin$ http://www.example.com/blog/wp-admin/
RewriteRule blog$ /blog/ [L]
RewriteRule blog/wp-admin$ /blog/wp-admin/ [L]
If you find any problem in this than let me know by comment.

How to use OR in find method – CakePHP


Hello Friends,
When any developer is working with any web application, he/she will constantly interact with the Select Query. As i am working with CakePHP, i also need to use Select Query often. For Select Query in CakePHP, you can use find method of Model which gives you the data as per conditions given in find method. If you write more than one conditions in conditions array passed in find method than by default it will take OR clause and make a query string with “AND“. If you want to do OR operation or any other operation than you need to mention that in find method. Look at below syntax.
 <?php
$this->Post->find(‘all’, array(‘conditions’ => $conditions));
$conditions = array(“id”=>”5″,”name”=>”abc”);
//Above condition will make a select query with AND.(WHERE id=5 AND name=’abc’)
$conditions = array(“OR”=>array(“id”=>”5″,”name”=>”abc”));
// If you define “OR” as per above statement than the query will be WHERE id=5 OR name=’abc’
?>
If you find any problem in this than let me know by comment.

Set Meta Tags (SEO Tags) in CakePHP



Set Meta Tags (SEO Tags) in CakePHP

Hello Friends,

In my previous post, i show you the way how to set Page Title Tag in CakePHP. But setting Meta keywords and Meta Description is not the same way as Meta Title. .Also Meta Keyword and Meta Description is important part of Search Engine Optimization. Refer to below syntax to set Meta tags in CakePHP.


Set Meta Tags in CakePHP



<?php
       echo $html->meta(‘keywords’,'enter any meta keyword here’);
?>

//
Output <meta name=”keywords” content=”enter any meta keyword here”/>

<?php
       echo $html->meta(‘description’,'enter any meta description here’);
?>

//Output <meta name=”description” content=”enter any meta description here”/>


Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India


301 Redirect old dynamic URLs to new static URLs using .htaccess


Hello Friends,
Today i faced a situation where i need to redirect dynamic URL of my shopping cart to static url. I have changed the Dynamic URL(with query string , ? and &) to static one in my sunshop shopping cart. But still if i will open dynamic url with query string than it shows the content. This is a big issue with search engine as they will consider this dynamic page and static page as two different page and duplicate content issue araise.
Redirect 301 rule in .htaccess (which is below) is common rule everybody knows.
Using .htaccess
redirect 301 http://www.domain.com/about-us.html http://www.domain.com/about.html
Using PHP
<?php
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location: http://www.domain.com/about.html” );
?>
What i want is to redirect dynamic urls(with query string , ? and &) to static page. For e.g. If i want to redirect http://www.domain.com/content.php?a=1&b=2 to http://www.domain.com/content.html than look at the below htaccess rules.
RewriteCond %{HTTP_HOST} ^domain.com
RewriteCond %{QUERY_STRING} ^a=1&b=2$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/content.html [R=301,L]
Add the above three lines and change the domain name and query string as per your need. Now whenever you will enter http://www.domain.com/content.php?a=1&b=2 , it will redirect to http://www.domain.com/content.html. So now Search engine will consider both as one page and duplicate content issue will not araise.
To know more about programming,JavaScript issues,jQuery,Expression Engine,MYSQL database,php info,php editor,programming php,Open-source,php help and php script , subscribe to our feed by entering email address below. 

You will get updates via email about every tutorial posted on this site . It will not take more than a sec.
[PHP Freelancing India]








:D

About

Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner