Frank Tocci
Frank Tocci

Reputation: 634

Python version of PHP mysql_fetch_array

I have a PHP sheet that I am trying to translate into Python. One of the functions is mysql_fetch_array. Does anyone know of a Python equivalent? As you can see, most of my code has already been translated. The exception is line 41, which is still PHP.

#send

import MySQLdb
servername = "localhost"
username = "username"
password = "password"
dbname = "some_database"
import time
today = time.strftime("%d-%m-%Y")
now = time.strftime("%H:%M:%S")

#use Django for this
field = request.GET['field']
value = request.GET['value']

conn = MySQLdb.connect(host="localhost",user="username",passwd="password",db=)
if not conn:
    print 'Could not connect: mysql_error'# . mysql_error();
#below may need editing
con_result = conn.select("some_database")
if not con_result:
    print 'Could not connect to specific database: '# . mysql_error();
datenow = today + ' ' + now
hvalue = value

sql = "INSERT INTO `DataTable`(`logdata`, `field`, `value`) VALUES (\"datenow\",\"field\",value)"
result = sql.fetchall()
if not result:
    print 'Invalid query'
print "THE DATA HAS BEEN SENT!"
conn.close()

#get
fieldToGet = request.GET['field']
sql = "SELECT * FROM `DataTable` WHERE `field` = \"fieldToGet\""
result = sql.fetchall()
if not result:
    print 'Invalid query'
print "THE DATA HAS BEEN RECEIVED!!"

while(row == mysql_fetch_array($result, MYSQL_ASSOC))

Upvotes: 0

Views: 326

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98921

The php equivalent of mysql_fetch_array in python is fetchall(), i.e.:

import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'pass', 'db');
with con:
    cur = con.cursor()
    cur.execute("SELECT * FROM `DataTable` WHERE `field` = '"+fieldToGet+"'")
    rows = cur.fetchall()
    for row in rows:
        email = row[0]
        password = row[1]

Upvotes: 1

Related Questions