pythonhtmlsqliteflasksqlite3-python

How do I pass data from my html flask to my sqlite3 database(python)


I am trying to make an app where the user put's in a couple of inputs and i need the inputs to go to my database and my other page which is results which will show it i already don't where it sends to the other page i am having a problem trying to send the data to my database and i want it to send the Phone Name and serial number to the database only.

Here Is My HTML Code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="/static/css/main.css">
        <link rel="stylesheet"  href="{{   url_for('static',filename='css/main.css')   }}">
        <script type="text/javascript" src="{{url_for('static', filename='script/result.js')}}"></script>
        <title>Fen</title>
</head>
<body>
    <section>
        <div class="form-box">
            <div class="form-value">
                <form method="GET" action="result.html">
                    <h2>Add Phone</h2>
                    <div class="inputbox">
                        <ion-icon name="mail-outline"></ion-icon>
                        <input name="Person Name" id="Name" type="text">
                        <label for="">Name</label>
                    </div>
                    <div class="inputbox">
                        <ion-icon name="mail-outline"></ion-icon>
                        <input name="Phone Name" id="phone_name" type="text">
                        <label for="">Phone Name</label>
                    </div>
                    <div class="inputbox">
                        <ion-icon name="lock-closed-outline"></ion-icon>
                        <input name="Serial Number" type="text" id="sr" required>
                        <label for="">serial number</label>
                    </div>   
                    <div class="inputbox">
                        <ion-icon name="lock-closed-outline"></ion-icon>
                        <input name="E-Mail" type="email" id="em" required>
                        <label for="">E-mail</label>
                    </div>   
                    <div class="inputbox">
                        <ion-icon name="lock-closed-outline"></ion-icon>
                        <input name="Phone Number" type="text" id="pn" required>
                        <label for="">Phone Number</label>
                    </div>
                    <button id="log" type="submit">Add Phone</button>
                </form>
            </div>
        </div>
    </section>
    <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
    <script>
        window.addEventListener('load', () => {  
        const parms = (new URL(document.location)).searchParams;
        const username = parms.get('Person Name')
        const PhoneName = parms.get('Phone Name')
        const SerialNumber = parms.get('Serial Number')
        const Email = parms.get('E-Mail')
        const PhoneNumber = parms.get('Phone Number')
        document.getElementById('name').innerHTML = username
        document.getElementById('result-name').innerHTML = PhoneName
        document.getElementById('result-surname').innerHTML = SerialNumber
        document.getElementById('result-Email').innerHTML = Email
        document.getElementById('result-number').innerHTML = PhoneNumber
})

console.log('welcome')
    </script>
</body>
</html>

and here is my python/flask code:

from flask import *
import sqlite3

app = Flask(__name__)

@app.route('/')
def main() :
    return render_template('/Phonebook.html')

@app.route('/', methods = ['POST'])

def phonebook() :
    name = request.form['name']
    phonenumber = request.form['number']
    connection = sqlite3.connect('phonebook2.db')
    cursor = connection.cursor()
    query1 = "INSERT INTO phonebook2 VALUES ({n},{sn})".format(n=name,sn=phonenumber)    
    cursor.execute(query1)
    connection.commit()

@app.route('/result',methods = ['GET'])
def result ():
    try:
        if request.method == "GET":
               name = request.args.get('name')
               connection = sqlite3.connect('phonebook2.db')
               cursor = connection.cursor()
               query2 = "SELECT number from phonebook2 WHERE Name = {n}".format(n=name)
               result = cursor.execute(query2)
               result =  result.fetchall()[0][0]
               return render_template('result.html', phonenumber = result)
    except:
        return render_template('result.html', phonenumber = "")
        
               
if __name__ == '__main__':
    app.run(debug=True)

I Tried some things but it didn't work and also it's my first time using flask and sqlite3 i know bit of the basics about them

thank you for taking the time to look at my code


Solution

  • I appreciate the effort you took for learning this and solutions you tried.It still needs some refinements.

    Things to change

    See the updated codes

    HTML

    ....
    <section>
        <div class="form-box">
            <div class="form-value">
                    <!-- This should be post method and the action should be the desired route -->
                <form method="POST" action="/">
                        <h2>Add Phone</h2>
                        <div class="inputbox">
                                <ion-icon name="mail-outline"></ion-icon>
                                <input name="name" id="Name" type="text">
                                <label for="">Name</label>
                        </div>
                        <div class="inputbox">
                                <ion-icon name="mail-outline"></ion-icon>
                                <input name="phone_name" id="phone_name" type="text">
                                <label for="">Phone Name</label>
                        </div>
                        <div class="inputbox">
                                <ion-icon name="lock-closed-outline"></ion-icon>
                                <input name="serial_number" type="text" id="sr" required>
                                <label for="">serial number</label>
                        </div>   
                        <div class="inputbox">
                                <ion-icon name="lock-closed-outline"></ion-icon>
                                <input name="email" type="email" id="em" required>
                                <label for="">E-mail</label>
                        </div>   
                        <div class="inputbox">
                                <ion-icon name="lock-closed-outline"></ion-icon>
                                <input name="number" type="text" id="pn" required>
                                <label for="">Phone Number</label>
                        </div>
                        <button id="log" type="submit">Add Phone</button>
                </form>
            </div>
        </div>
    </section>
    ....
    
    

    app.py

    from flask import *
    import sqlite3
    
    app = Flask(__name__)
    
    @app.route('/')
    def main() :
        # This is to create a table if it is not exists
        connection = sqlite3.connect('phonebook2.db')
        cursor = connection.cursor()
        create_table_query = '''
            CREATE TABLE IF NOT EXISTS phonebook2 (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT,
                number TEXT
            )
        '''
        cursor.execute(create_table_query)
        connection.commit()
        connection.close()
        return render_template('/Phonebook.html')
    
    
    @app.route('/', methods = ['POST'])
    def phonebook() :
        name = request.form['name']
        phonenumber = request.form['number']
        connection = sqlite3.connect('phonebook2.db')
        cursor = connection.cursor()
        query1 = "INSERT INTO phonebook2 (name,number) VALUES ('{n}','{sn}')".format(n=name,sn=phonenumber)    
        cursor.execute(query1)
        connection.commit()
        
        # After submit, redirecting to the result page
        return redirect("/result?name=" + name)
    
    @app.route('/result',methods = ['GET'])
    def result ():
        try:
            if request.method == "GET":
                   name = request.args.get('name')
                   connection = sqlite3.connect('phonebook2.db')
                   cursor = connection.cursor()
                   query2 = "SELECT number from phonebook2 WHERE name = '{n}'".format(n=name)
                   result = cursor.execute(query2)
                   result =  result.fetchall()[0][0]
                   return render_template('result.html', phonenumber = result)
        except:
            return render_template('result.html', phonenumber = "")
            
                   
    if __name__ == '__main__':
        app.run(debug=True)
    

    References

    Happy learning.. :)