Connecting to and using a MySQL-database in Python is easy. Here’s a full example code with comments:
# MySQLdb needs to be installed
# 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
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...']
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! =)
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:
But you can also add a 4th parameter to
$.post(). See this example:
$.post(url, data, callback, 'json');
This will do the same trick.
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
Here’s the problem fixed (
background set): http://jsfiddle.net/mzk3X/1/
I recently ran into a situation where I had to combine
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
//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
refreshPositions set to true the positions will be updated every time the mouse is moved.