MySQL in Python

Connecting to and using a MySQL-database in Python is easy. Here’s a full example code with comments:

# MySQLdb needs to be installed
import MySQLdb

# Connect to a database
db = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database')

# Create a cursor
cursor = db.cursor()

# Perform a query (returns the amount of rows affected/found)
num_rows = cursor.execute(query)

# Work with the results

# Close the connection
db.close()

If you do a SELECT-query, you can either retrieve one row or loop through all of them. Here’s an example of both:

# Fetch only one row (mostly used for e.g. "SELECT COUNT(*)")
data = cursor.fetchone()

# Loop through all rows
data = cursor.fetchall()
for row in data:
    # ...

All rows are represented as an array, without keys:

['First column', 'Another column', 'Etc...']

WordPress Theme Development – Cheatsheet

I take the chance to promote a one-pager I just published: WordPress Theme Development Cheatsheet.

It contains handy snippets for reference while making awesome WordPress themes.

Any suggestions/modifications are welcome! =)

JSON via $.post()

If you ever needed to transfer JSON to front-end with jQuery, you are probably familiar with $.getJSON(). But what if you want to send POST-input to back-end? You could always use the original method, for which $.getJSON() etc. are shortcuts for, like this:

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    data: data,
    success: callback
});

But you can also add a 4th parameter to $.post(). See this example:

$.post(url, data, callback, 'json');

This will do the same trick.

Opera Transition Bug

See this fiddle in Opera: http://jsfiddle.net/mzk3X/

You can see that the color in the animation makes a weird shift to dark. This happens if the background is set to transparent.

Here’s the problem fixed (background set): http://jsfiddle.net/mzk3X/1/

Refresh draggable positions in jQuery

I recently ran into a situation where I had to combine sortable and droppable. One issue occurred: when moving the list item (and manipulating the DOM) the droppable areas did not update. This resulted in weird behaviour.

Here’s a fiddle. If you move any list item so that a droppable item moves, you will still be able to drop to that specific element from its old position, not from the new one. I needed to refresh the droppable area position. I searched and ended up in tearing the jQuery UI source. Suddenly I found this inside the draggable:

//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event);

The problem was solved by adding the option refreshPositions for the sortable:

$('#sortable').sortable({
    refreshPositions: true
});

With refreshPositions set to true the positions will be updated every time the mouse is moved.