Deleting records from database using flask/mysqldb


I am trying to make a view, insert, update and delete on a single page. As for now, I am able to do a view and insert. However, when I am trying to delete records based on the id, however I cant seem to capture the id and thus my delete function was unable to run. When I tried to press the delete for a record, it just shows that url cant be found.

from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'myproject'

mysql = MySQL(app)

@app.route('/', methods=['GET', 'POST'])
def select():
   cur = mysql.connection.cursor()
   cur.execute("SELECT * FROM people")
   selectall = cur.fetchall()
   return render_template('index.html', dbhtml = selectall)

@app.route('/insert', methods = ['GET','POST'])
def insert():
   name = request.form['name']
   email = request.form['email']

   cur = mysql.connection.cursor()
   cur.execute("INSERT INTO people (name, email) VALUES (%s, %s)", (name, email))

   return redirect('/')

@app.route('/delete/<int:id>', methods = ['GET','POST','DELETE'])
def delete(id):
   cur = mysql.connection.cursor()
   cur.execute("DELETE FROM people WHERE id=%s", (id))

   return redirect('/')

if __name__ == '__main__':


<form action="{{url_for('insert')}}" method="POST">

  <div class="form group">

    <input type="text" class="form-control" name="name" required="1">


  <div class="form group">

    <input type="text" class="form-control" name="email" required="1">


  <div class="form group">

    <button class="btn btn-primary" type="submit">Insert Data</button>




  <table align="center">
    <tr align="center">
    {% for row in dbhtml %}
      <td><a href="/delete/{{id}}">Delete</a></td>
      <td><a href="#">Update</a></td>
    {% endfor %}


you have to send the id, as you can see the id is row[0] not "id"

<td><a href="/delete/{{row[0]}}">Delete</a></td>

i dont know if this correct or not, i think delete method must be wrapped in a form

<form method="POST" action=..url_delete>
   <td><buttin type=submit>Delete</button></td>

and change the cur.execute to

 cur.execute("DELETE FROM people WHERE id={}".format(id))

Answered By – Eric Kong

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published