article

Sunday, February 16, 2020

Python Flask File Generate Excel Report from MySQL


Python Flask File Generate Excel Report from MySQL

from flask import Flask, Response, render_template
from flaskext.mysql import MySQL
import io
import xlwt
import pymysql

app = Flask(__name__)


mysql = MySQL()
 
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route('/')
def upload_form():
 return render_template('download.html')


@app.route('/download/report/excel')
def download_report():
  conn = mysql.connect()
  cursor = conn.cursor(pymysql.cursors.DictCursor)
  
  cursor.execute("SELECT emp_id, emp_first_name, emp_last_name, emp_designation FROM employees")
  result = cursor.fetchall()
  
  #output in bytes
  output = io.BytesIO()
  #create WorkBook object
  workbook = xlwt.Workbook()
  #add a sheet
  sh = workbook.add_sheet('Employee Report')
  
  #add headers
  sh.write(0, 0, 'Emp Id')
  sh.write(0, 1, 'Emp First Name')
  sh.write(0, 2, 'Emp Last Name')
  sh.write(0, 3, 'Designation')
  
  idx = 0
  for row in result:
   sh.write(idx+1, 0, str(row['emp_id']))
   sh.write(idx+1, 1, row['emp_first_name'])
   sh.write(idx+1, 2, row['emp_last_name'])
   sh.write(idx+1, 3, row['emp_designation'])
   idx += 1
  
  workbook.save(output)
  output.seek(0)
  
  return Response(output, mimetype="application/ms-excel", headers={"Content-Disposition":"attachment;filename=employee_report.xls"})

 
if __name__ == '__main__':
    app.run(debug=True)
<html>
<head>
    <title>Python Flask File Generate Excel Report from MySQL</title>
</head>
<body>
<h2>Generate Excel Report from MySQL</h2>
<p>
 <a href="{{ url_for('.download_report') }}">Generate Excel Report</a>
</p>
</body>
</html>

Friday, February 14, 2020

Flash-Admin intro using sqlite SQLAlchemy


Flash-Admin into using sqlite SQLAlchemy

install flask admin from pip


pip install flask-admin


 
#app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///admin.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

db = SQLAlchemy(app)

# set optional bootswatch theme
app.config['FLASK_ADMIN_SWATCH'] = 'darkly'

admin = Admin(app, name='microblog', template_mode='bootstrap3')
# Add administrative views here

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))

admin.add_view(ModelView(Person, db.session))

if __name__ == '__main__':
    app.run(debug=True)
 

Wednesday, February 12, 2020

Python Flask Datatable using SQLalchemy With Mysql


Python Flask Datatable using SQLalchemy With Mysql

First you need to install flask, and after that you need to install flask-sqlalchemy.

pip install Flask

pip install Flask-SQLAlchemy


#app.py
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
 
app = Flask(__name__)
app.secret_key = "cairocoders-ednalan-06300131"
 
#SqlAlchemy Database Configuration With Mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@localhost/testingdb'
                                        #mysql+pymysql://username:passwd@host/databasename 
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
 
db = SQLAlchemy(app)
 
#Creating model table for our CRUD database
class Employee(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(100))
    email = db.Column(db.String(100))
    phone = db.Column(db.String(100))
 
    def __init__(self, name, email, phone):
        self.name = name
        self.email = email
        self.phone = phone
 
#query on all our employee data
@app.route('/')
def Index():
    all_data = Employee.query.all()
    return render_template("index.html", employees = all_data)
 
#insert data to mysql database via html forms
@app.route('/insert', methods = ['POST'])
def insert():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
 
        my_data = Employee(name, email, phone)
        db.session.add(my_data)
        db.session.commit()
 
        flash("Employee Inserted Successfully")
        return redirect(url_for('Index'))
 
#update employee
@app.route('/update', methods = ['GET', 'POST'])
def update():
    if request.method == 'POST':
        my_data = Employee.query.get(request.form.get('id'))
 
        my_data.name = request.form['name']
        my_data.email = request.form['email']
        my_data.phone = request.form['phone']
 
        db.session.commit()
        flash("Employee Updated Successfully")
        return redirect(url_for('Index'))
 
#delete employee
@app.route('/delete//', methods = ['GET', 'POST'])
def delete(id):
    my_data = Employee.query.get(id)
    db.session.delete(my_data)
    db.session.commit()
    flash("Employee Deleted Successfully")
    return redirect(url_for('Index'))
 
if __name__ == "__main__":
    app.run(debug=True)
//index.html
{% extends 'base.html' %}
{% include 'header.html' %}

{% block title %} Home {% endblock %}
 
{% block body %}
<div class="container">
    <div class="row">
        <div class="col md-12">
            <div class="jumbotron p-3">
                <h2>Manage <b>Employees </b>  <button type="button"  class="btn btn-success float-right"
                data-toggle="modal" data-target="#mymodal">Add New Employees</button> </h2>
                {% with messages = get_flashed_messages() %}
                {% if messages %}
                
    {% for message in messages %}
                <div class="alert alert-success alert-dismissable" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="close">
                        <span aria-hidden="true">x</span>
                    </button>
                {{message}}
                </div>
                {% endfor %}
    
                {% endif %}
                {% endwith %}
 
                <table class="table table-hover table-striped">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Action</th>
                    </tr>
                   {% for row in employees %}
                    <tr>
                        <td>{{row.id}}</td>
                        <td>{{row.name}}</td>
                        <td>{{row.email}}</td>
                        <td>{{row.phone}}</td>
                        <td>
                            <a href="/update/{{row.id}}" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#modaledit{{row.id}}">Edit</a>
                            <a href="/delete/{{row.id}}" class="btn btn-danger btn-xs" onclick="return confirm('Are You Sure To Delete ?')">Delete</a>
                        </td>
                    </tr>
     <!-- Modal Edit Employee-->
     <div id="modaledit{{row.id}}" class="modal fade" role="dialog">
        <div class="modal-dialog">
        <div class="modal-content">
       <div class="modal-header"><h4 class="modal-title">Update Information</h4></div>
        <div class="modal-body">
        <form action="{{url_for('update')}}" method="POST">
         <div class="form-group">
          <label>Name:</label>
          <input type="hidden"  name="id" value="{{row.id}}">
          <input type="text" class="form-control" name="name" value="{{row.name}}">
         </div>
         <div class="form-group">
          <label>Email:</label>
          <input type="text" class="form-control" name="email" value="{{row.email}}">
         </div>
         <div class="form-group">
          <label>Phone:</label>
          <input type="text" class="form-control" name="phone" value="{{row.phone}}">
         </div>
         <div class="form-group">
          <button class="btn btn-primary" type="submit">Update</button>
         </div>
        </form>
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </div>
      </div>
     </div> 
     {% endfor %}
    </table>
   </div>
 
  <!-- Modal Add Employee-->
  <div id="mymodal" class="modal fade" role="dialog">
      <div class="modal-dialog">
     <div class="modal-content">
    <div class="modal-header"><h4 class="modal-title">Add Employee</h4></div>
    <div class="modal-body">
     <form action="{{url_for('insert')}}" method="POST">
      <div class="form-group">
       <label>Name:</label>
       <input type="text" class="form-control" name="name" required="1">
      </div>
      <div class="form-group">
       <label>Email:</label>
       <input type="email" class="form-control" name="email" required="1">
      </div>
      <div class="form-group">
       <label>Phone:</label>
       <input type="number" class="form-control" name="phone" required="1">
      </div>
      <div class="form-group">
      <button class="btn btn-primary" type="submit">Add Employee</button>
      </div>
     </form>
    </div>
    <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
   </div>
   </div>
  </div>
  
 </div>
 </div>
</div>
{% endblock %}
//base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %} </title>
</head>
<body>
{% block body %} {% endblock %}
 
 
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
 
</body>
</html>
//header.html
{% extends 'base.html' %}

{% block title %} Python Flask Datatable {% endblock %}

{% block body %}
<div class="jumbotron p-3">
    <div class="well text-center">
        <h1>Python Flask Datatable using SQLalchemy With Mysql</h1>
    </div>
</div>
{% endblock %}

Monday, February 10, 2020

Uploading Files with Python Flask-Uploads


Uploading Files with Python Flask-Uploads

pip install flask-uploads


from flask_uploads import UploadSet, configure_uploads
#app.py
from flask import Flask, request, render_template, url_for
from flask_uploads import UploadSet, configure_uploads, IMAGES

app = Flask(__name__)

photos = UploadSet('photos', IMAGES)

app.config['UPLOADED_PHOTOS_DEST'] = 'static/img'
configure_uploads(app, photos)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        return filename
    return render_template('upload.html')
	
if __name__ == '__main__':
	app.run(debug=True)
//upload.html
<html>
<head>
	<title>Upload</title>
</head>
<body>
<h1>Uploading Files with Python Flask-Uploads</h1>
<form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}">
    <input type=file name=photo>
    <input type="submit">
</form>
</body>
</html>

jQuery AJAX Forms Submit with Python Flask


jQuery AJAX Forms Submit with Python Flask

Submitting forms without refreshing is a common feature of many websites.


from flask import Flask, render_template, url_for, request, jsonify

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('form.html')

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

	email = request.form['email']
	name = request.form['name']
	
	if name and email:
		newName = name

		return jsonify({'name' : newName})

	return jsonify({'error' : 'Missing data!'})
	
	
if __name__ == '__main__':
	app.run(debug=True)
//templates\form.html
<!DOCTYPE html>
<html>
<head>
	<title>AJAX Example</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
	<script src="{{ url_for('static', filename='js/form.js') }}"></script>
</head>
<body>
<div class="container">
	<br><br><br><br>
	<form class="form-inline">
	  <div class="form-group">
	    <label class="sr-only" for="emailInput">Email address</label>
	    <input type="email" class="form-control" id="emailInput" placeholder="Email">
	  </div>
	  <div class="form-group">
	    <label class="sr-only" for="nameInput">Name</label>
	    <input type="text" class="form-control" id="nameInput" placeholder="First Name">
	  </div>
	  <button type="submit" class="btn btn-default">Submit</button>
	</form>
	<br>
	<div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div>
	<div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div>
</div>
</body>
</html>

//static\js\form.js
$(document).ready(function() {
	$('form').on('submit', function(event) {
		$.ajax({
			data : {
				name : $('#nameInput').val(),
				email : $('#emailInput').val()
			},
			type : 'POST',
			url : '/process'
		})
		.done(function(data) {
			if (data.error) {
				$('#errorAlert').text(data.error).show();
				$('#successAlert').hide();
			}
			else {
				$('#successAlert').text(data.name).show();
				$('#errorAlert').hide();
			}
		});
		event.preventDefault();
	});
});

Login Page in Flask Using Sessions



Login Page in Flask Using Sessions
#app.py
from flask import Flask, request, session, redirect, url_for, render_template, g
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session.pop('user', None)

        if request.form['password'] == 'password':
            session['user'] = request.form['username']
            return redirect(url_for('protected'))

    return render_template('index.html')

@app.route('/protected')
def protected():
    if g.user:
        return render_template('protected.html')

    return redirect(url_for('index'))

@app.before_request
def before_request():
    g.user = None
    if 'user' in session:
        g.user = session['user']

@app.route('/getsession')
def getsession():
    if 'user' in session:
        return session['user']

    return 'Not logged in!'

@app.route('/dropsession')
def dropsession():
    session.pop('user', None)
    return 'Dropped!'
 
if __name__ == '__main__':
    app.run(debug=True)
//index.html
<html>
<head>
    <title>Login Page</title>
</head>
<body>
<h1>Login Page in Flask Using Sessions</h1>
<h1>Please login</h1>
<form method="POST">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>
//protected.html
<html>
<head>
    <title>Protected Page</title>
</head>
<body>
<h1>Welcome to the protected page!</h1>
</body>
</html>

Thursday, February 6, 2020

Build a Blog App With Flask and Flask-SQLAlchemy


Build a Blog App With Flask and Flask-SQLAlchemy

A blog simple app that demonstrates what you can do with Flask.

using Flask-SQLAlchemy to handle the database
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy 
from datetime import datetime

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 

db = SQLAlchemy(app)

class Blogpost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    subtitle = db.Column(db.String(50))
    author = db.Column(db.String(20))
    date_posted = db.Column(db.DateTime)
    content = db.Column(db.Text)

@app.route('/')
def index():
    posts = Blogpost.query.order_by(Blogpost.date_posted.desc()).all()

    return render_template('index.html', posts=posts)

@app.route('/post/')
def post(post_id):
    post = Blogpost.query.filter_by(id=post_id).one()

    return render_template('post.html', post=post)

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

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

@app.route('/addpost', methods=['POST'])
def addpost():
    title = request.form['title']
    subtitle = request.form['subtitle']
    author = request.form['author']
    content = request.form['content']

    post = Blogpost(title=title, subtitle=subtitle, author=author, content=content, date_posted=datetime.now())

    db.session.add(post)
    db.session.commit()

    return redirect(url_for('index'))
 
if __name__ == '__main__':
    app.run(debug=True)
//index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Clean Blog - Start Bootstrap Theme</title>
    <!-- Bootstrap core CSS -->
    <link href="{{ url_for('static', filename='bootstrap.min.css') }}" rel="stylesheet">
    <!-- Custom fonts for this template -->
    <link href="{{ url_for('static', filename='font-awesome.min.css') }}" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <!-- Custom styles for this template -->
    <link href="{{ url_for('static', filename='clean-blog.min.css') }}" rel="stylesheet">
  </head> 
  <body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
      <div class="container">
        <a class="navbar-brand" href="{{ url_for('index') }}">Start Bootstrap</a>
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu
          <i class="fa fa-bars"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
           <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="{{ url_for('index') }}">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{{ url_for('about') }}">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{{ url_for('add') }}">Add</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
 
     <!-- Page Header -->
    <header class="masthead" style="background-image: url('{{ url_for('static', filename='home-bg.jpg') }}')">
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            <div class="site-heading">
              <h1>Clean Blog</h1>
              <span class="subheading">A Blog Theme by Start Bootstrap</span>
            </div>
          </div>
        </div>
      </div>
    </header>
 
 
        <!-- Main Content -->
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
        {% for post in posts %}
          <div class="post-preview">
            <a href="{{ url_for('post', post_id=post.id) }}">
              <h2 class="post-title">
                {{ post.title }}
              </h2>
              <h3 class="post-subtitle">
                {{ post.subtitle }}
              </h3>
            </a>
            <p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
          </div>
          {% endfor %}
          <hr>
        </div>
      </div>
    </div>

    <hr>
 
    <!-- Footer -->
    <footer>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            <p class="copyright text-muted">Copyright © Your Website 2017</p>
          </div>
        </div>
      </div>
    </footer>

    <!-- Bootstrap core JavaScript -->
    <script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
    <script src="{{ url_for('static', filename='popper.min.js') }}"></script>
    <script src="{{ url_for('static', filename='bootstrap.min.js') }}"></script>

    <!-- Custom scripts for this template -->
    <script src="{{ url_for('static', filename='clean-blog.min.js') }}"></script>

  </body>

</html>

Download Source Code


Tuesday, February 4, 2020

Flask-WTF


Flask-WTF

WTF stands for WT Forms which is intended to provide the interactive user interface for the user. The WTF is a built-in module of the flask which provides an alternative way of designing forms in the flask web applications.

Why WTF Useful?
WTF is useful due to the following factors.

The form elements are sent along with the request object from the client side to the server side. Server-Side script needs to recreate the form elements since there is no direct mapping between the client side form elements and the variables to be used at the server side.
There is no way to render the HTML form data at real time.

The WT Forms is a flexible, form rendering, and validation library used to provide the user interface.
#app.py
from flask import Flask, render_template, request, flash  
from forms import ContactForm 

app = Flask(__name__)

app.secret_key = 'cairocoders-ednalan-456895'  

@app.route('/contact', methods = ['GET', 'POST'])  
def contact():  
   form = ContactForm()  
   if form.validate() == False:  
      flash('All fields are required.')  
   return render_template('contact.html', form = form) 

@app.route('/success',methods = ['GET','POST'])  
def success():  
   return render_template("success.html") 
   
if __name__ == '__main__':
    app.run(debug=True)
#forms.py
from flask_wtf import Form  
from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField  
from wtforms import validators, ValidationError  
  
class ContactForm(Form):  
   name = TextField("Candidate Name ",[validators.Required("Please enter your name.")])  
   Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])  
   Address = TextAreaField("Address")  
     
   email = TextField("Email",[validators.Required("Please enter your email address."),  
   validators.Email("Please enter your email address.")])  
     
   Age = IntegerField("Age")  
   language = SelectField('Programming Languages', choices = [('java', 'Java'),('py', 'Python')])  
  
   submit = SubmitField("Submit")  
<!doctype html>  
<html>  
   <body>  
      <h2 style = "text-align: center;">Registration Form</h2>  
          
      {% for message in form.name.errors %}  
         <div>{{ message }}</div>  
      {% endfor %}  
        
      {% for message in form.email.errors %}  
         <div>{{ message }}</div>  
      {% endfor %}  
        
      <form action = "http://127.0.0.1:5000/success" method = "POST">  
           
            {{ form.hidden_tag() }}  
              
            <div style = "font-size:18px;" font-weight:bold; margin-left:150px;>  
               {{ form.name.label }}<br>  
               {{ form.name }}  
               <br>  
               {{ form.Gender.label }} {{ form.Gender }}  
               {{ form.Address.label }}<br>  
               {{ form.Address }}  
               <br>  
               {{ form.email.label }}<br>  
               {{ form.email }}  
               <br>  
               {{ form.Age.label }}<br>  
               {{ form.Age }}  
               <br>  
               {{ form.language.label}}<br><br>  
               {{ form.language }}  
               <br><br>  
               {{ form.submit }}  
            </div>  
              
         </fieldset>  
      </form>  
   </body>  
</html>  

Monday, February 3, 2020

Tasks App - Flask SQLAlchemy sqlite3


Tasks App - Flask SQLAlchemy sqlite3

A simple tasks app using Flask sqlalchemy and sqlite3 and also sqlite studio


from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///task.sqlite3'

db = SQLAlchemy(app)

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(200))
    done = db.Column(db.Boolean)

@app.route('/')
def home():
    tasks = Task.query.all()
    return render_template('index.html', tasks = tasks)

@app.route('/create-task', methods=['POST'])
def create():
    new_task = Task(content=request.form['content'], done= False)
    db.session.add(new_task)
    db.session.commit()
    return redirect(url_for('home'))

@app.route('/done/')
def done(id):
    task = Task.query.filter_by(id=int(id)).first()
    task.done = not(task.done)
    db.session.commit()
    return redirect(url_for('home'))

@app.route('/delete/')
def delete(id):
    Task.query.filter_by(id=int(id)).delete()
    db.session.commit()
    return redirect(url_for('home'))
 
if __name__ == '__main__':
    app.run(debug=True)
//index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Tasks App</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
    <!-- FONTS -->
 <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">

    <!-- MAIN CSS -->
    <link rel="stylesheet" href="{{url_for('static', filename='main.css')}}">

</head>

<body>

    <main class="container p-4">
        <h1 class="display-4 text-center title mt-4">Tasks App - Flask SQLAlchemy</h1>
        <div class="row">

            <div class="col-md-4 offset-md-4 my-auto">

                <div class="card">
                    <div class="card-header">

                        <form action="/create-task" method="POST">
                            <div class="form-group">
                                <input type="text" name="content" placeholder="Task" class="form-control" autofocus>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">Save</button>
                        </form>
                    </div>
                    <div class="card-body">


                        <ul class="list-group">
                            {% for task in tasks %}
                            <li class="list-group-item">
                                <span class="{% if task.done %} done {% endif %}">{{task.content}}</span> <a
                                    href="/done/{{task.id}}" class="btn btn-success btn-sm">Done</a>
                                <a href="{{url_for('delete', id=task.id)}}" class="btn btn-danger btn-sm">Delete</a>
                            </li>
                            {% endfor %}
                        </ul>
                    </div>

                </div>
            </div>
        </div>
    </main>

</body>

</html>
//main.css
body {
    background: #C9D6FF;  /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #E2E2E2, #C9D6FF);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #E2E2E2, #C9D6FF); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
color: #000;
}

.title {
    font-family: 'Open+Sans', cursive;text-transform:normal;
}

.done {
    text-decoration: line-through;
    color: #cfcfcf;
}

Sunday, February 2, 2020

Flask SQLAlchemy


Flask SQLAlchemy

Flask SQLAlchemy is an ORM tool which establishes the relationship between the objects and the tables of the relational databases.

In this section of the tutorial, we will create a small web application using flask-sqlalchemy

Install flask-sqlalchemy:

pip install flask-sqlalchemy 

import flask_sqlalchemy 


Code small web application using flask-sqlalchemy

#app.py
from flask import Flask, render_template, url_for, request, flash, redirect
from flask_sqlalchemy import SQLAlchemy  

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///employees.sqlite3'  
app.config['SECRET_KEY'] = "cairocoders-ednalan23589"  

db = SQLAlchemy(app)  

class Employees(db.Model):  
   id = db.Column('employee_id', db.Integer, primary_key = True)  
   name = db.Column(db.String(100))  
   salary = db.Column(db.Float(50))  
   age = db.Column(db.String(200))   
   pin = db.Column(db.String(10))  
   
   def __init__(self, name, salary, age,pin):  
      self.name = name  
      self.salary = salary  
      self.age = age  
      self.pin = pin  

@app.route('/')  
def list_employees():  
   return render_template('list_employees.html', Employees = Employees.query.all() )  

@app.route('/add', methods = ['GET', 'POST'])  
def addEmployee(): 
   if request.method == 'POST':  
      if not request.form['name'] or not request.form['salary'] or not request.form['age']:  
         flash('Please enter all the fields', 'error')  
      else:  
         employee = Employees(request.form['name'], request.form['salary'],  
            request.form['age'], request.form['pin'])  
           
         db.session.add(employee)  
         db.session.commit()  
         flash('Record was successfully added')  
         return redirect(url_for('list_employees'))  
   return render_template('add.html') 
  
if __name__ == '__main__':  
   db.create_all()  
   app.run(debug = True) 
//list_employees
<!DOCTYPE html>  
<html lang = "en">  
   <head><title>Home - Cairocoders</title></head>  
   <body>  
      <h3>  
         <a href = "{{ url_for('list_employees') }}">Employee Management System</a>  
      </h3>  
      
 <h3>Employees List</h3>  
      <table border="2" padding = "5">  
         <thead>  
            <tr>  
               <th>Name</th>  
               <th>Salary</th>  
               <th>Age</th>  
               <th>Pin</th>  
            </tr>  
         </thead> 
         <tbody>  
            {% for employee in Employees %}  
               <tr>  
                  <td>{{ employee.name }}</td>  
                  <td>{{ employee.salary }}</td>  
                  <td>{{ employee.age }}</td>  
                  <td>{{ employee.pin }}</td>  
               </tr>  
            {% endfor %}  
         </tbody>   
  </table> 
  <br><br>  
      <a href="{{ url_for('addEmployee') }}">Add New Employee</a> 
   </body>  
</html>  
//add.html
<!DOCTYPE html>  
<html>  
   <body>  
      <h3>Add new Employee</h3>  
      <hr/>  
        
      {%- for category, message in get_flashed_messages(with_categories = true) %}  
         <div class = "alert alert-danger">  
            {{ message }}  
         </div>  
      {%- endfor %}  
        
      <form action = "{{ request.path }}" method = "post">  
         <label for = "name">Name</label><br>  
         <input type = "text" name = "name" placeholder = "Name" /><br>  
   
         <label for = "salary">Salary</label><br>  
         <input type = "text" name = "salary" placeholder = "salary" /><br>  
           
         <label for = "age">Age</label><br>  
         <textarea name = "age" placeholder = "age"></textarea><br>  
           
         <label for = "PIN">Pin</label><br>  
         <input type = "text" name = "pin" placeholder = "pin" /><br>  
           
         <input type = "submit" value = "Submit" />  
      </form>  
   </body>  
</html>  

Wednesday, January 29, 2020

Flask SQLite

Flask SQLite

Flask can make use of the SQLite3 module of the python to create the database web applications. In this section of the tutorial, we will create a CRUD (create - read - update - delete) application.
from flask import Flask, render_template, request
import sqlite3 
app = Flask(__name__)

#con = sqlite3.connect("employee.db")  
#print("Database opened successfully")  
#con.execute("create table Employees (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, address TEXT NOT NULL)")  
#print("Table created successfully")  

@app.route("/")  
def index():  
    return render_template("index.html"); 

@app.route("/add")  
def add():  
    return render_template("add.html")  
 
@app.route("/savedetails",methods = ["POST","GET"])  
def saveDetails():  
    msg = "msg"  
    if request.method == "POST":  
        try:  
            name = request.form["name"]  
            email = request.form["email"]  
            address = request.form["address"]  
            with sqlite3.connect("employee.db") as con:  
                cur = con.cursor()  
                cur.execute("INSERT into Employees (name, email, address) values (?,?,?)",(name,email,address))  
                con.commit()  
                msg = "Employee successfully Added"  
        except:  
            con.rollback()  
            msg = "We can not add the employee to the list"  
        finally:  
            return render_template("success.html",msg = msg)  
            con.close()   

@app.route("/view")  
def view():  
    con = sqlite3.connect("employee.db")  
    con.row_factory = sqlite3.Row  
    cur = con.cursor()  
    cur.execute("select * from Employees")  
    rows = cur.fetchall()  
    return render_template("view.html",rows = rows)   

@app.route("/delete")  
def delete():  
    return render_template("delete.html")  

@app.route("/deleterecord",methods = ["POST"])  
def deleterecord():  
    id = request.form["id"]  
    with sqlite3.connect("employee.db") as con:  
        try:  
            cur = con.cursor()  
            cur.execute("delete from Employees where id = ?",id)  
            msg = "record successfully deleted"  
        except:  
            msg = "can't be deleted"  
        finally:  
            return render_template("delete_record.html",msg = msg)
   
if __name__ == '__main__':
   app.run(debug = True)
//index.html
<html>  
<head>  
<title>Flask Home</title>  
</head>  
<body>  
    <h2>Hi, welcome to the website</h2>  
    <a href="/add">Add Employee</a><br><br>  
    <a href ="/view">List Records</a><br><br>  
    <a href="/delete">Delete Record</a><br><br>  
</body>  
</html>  
//add.html
<!DOCTYPE html>  
<html>  
<head>  
    <title>Add Employee</title>  
</head>  
<body>  
    <h2>Employee Information</h2>   
    <form action = "/savedetails" method="post">  
    <table>  
        <tr><td>Name</td><td><input type="text" name="name"></td></tr>  
        <tr><td>Email</td><td><input type="email" name="email"></td></tr>  
        <tr><td>Address</td><td><input type="text" name="address"></td></tr>  
        <tr><td><input type="submit" value="Submit"></td></tr>  
    </table>  
    </form>  
</body>  
</html> 
<!DOCTYPE html>  
<html>  
<head>  
    <title>save details</title>  
</head>  
<body>  
    <h3>Hi Admin, {{msg}}</h3>  
    <a href="/view">View Employees</a>  
</body>  
</html>  
//view.html
<!DOCTYPE html>  
<html>  
<head>  
    <title>List</title>  
</head>  
<body>  
  
<h3>Employee Information</h3>  
<table border=5>  
    <thead>  
        <td>ID</td>  
        <td>Name</td>  
        <td>Email</td>  
        <td>Address</td>  
    </thead>  
      
    {% for row in rows %}  
      
        <tr>  
            <td>{{row["id"]}}</td>  
            <td>{{row["name"]}}</td>  
            <td>{{row["email"]}}</td>  
            <td>{{row["address"]}}</td>  
        </tr>  
      
    {% endfor %}  
</table>  
<br><br>  
  
<a href="/">Go back to home page</a>  
  
</body>  
</html>  
//delete.html
<!DOCTYPE html>  
<html>  
<head>  
    <title>delete record</title>  
</head>  
<body>  
  
    <h3>Remove Employee from the list</h3>  
  
<form action="/deleterecord" method="post">  
Employee Id <input type="text" name="id">  
<input type="submit" value="Submit">  
</form>  
</body>  
</html>  
//delete_record.html
<!DOCTYPE html>  
<html>  
<head>  
    <title>delete record</title>  
</head>  
<body>  
<h3>{{msg}}</h3>  
<a href="/view">View List</a>  
</body>  
</html>

Friday, January 24, 2020

Flask Flashing

Flask Flashing

Flask provides the flash() method, in the same way, the client-side scripting language like JavaScript uses the alerts or the python GUI framework Tkinter uses the dialogue box or the message box.

The flash() method is used to generate informative messages in the flask. It creates a message in one view and renders it to a template view function called next.

syntax to use the flash() method is given below.

flash(message, category) 
 
#app.py
from flask import Flask, render_template, request, flash, redirect, url_for
# Initialize the Flask application
app = Flask(__name__)

app.secret_key = "cairocoders-ednalan23"

@app.route('/')  
def home():  
    return render_template("index.html") 
  
@app.route('/login',methods = ["GET","POST"])  
def login():  
    error = None;  
    if request.method == "POST":  
        if request.form['pass'] != 'ednalan':  
            error = "invalid password"  
        else:  
            flash("you are successfuly logged in")  
            return redirect(url_for('home'))  
    return render_template('login.html',error=error) 
 
if __name__ == '__main__':
   app.run(debug = True)
//index.html
<html>  
<head>  
<title>Flask Home</title>  
</head>  
<body>  
    {% with messages = get_flashed_messages() %}  
         {% if messages %}  
               {% for message in messages %}  
                    <p>{{ message }}</p>  
               {% endfor %}  
         {% endif %}  
      {% endwith %}  
<h3>Welcome to the website</h3>  
<a href = "{{ url_for('login') }}">login</a>  
</body>  
</html>  
//login.html
<html>  
<head>  
    <title>login</title>  
</head>  
<body>  
    {% if error %}  
        <p><strong>Error</strong>: {{error}}</p>  
    {% endif %}  
  
    <form method = "post" action = "/login">  
        <table>  
            <tr><td>Email</td><td><input type = 'email' name = 'email' autocomplete="off"></td></tr>  
            <tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>  
            <tr><td><input type = "submit" value = "Submit"></td></tr>  
        </table>  
    </form>  
</body>  
</html>  

Wednesday, January 22, 2020

Flask Redirect and Errors

Flask Redirect and Errors

Flask class provides the redirect() function which redirects the user to some specified URL with the specified status code.

An HTTP status code is a response from the server to the request of the browser. When we visit a website, a request is sent to the server, and the server then responds to the browser's request with a three-digit code: the HTTP status code. This status code also represents the error.


The syntax to use the redirect() function is given below.

app.py
from flask import Flask, render_template, request, redirect, url_for
# Initialize the Flask application
app = Flask(__name__)


@app.route('/')
def index():
   return render_template('log_in.html')
   
@app.route('/login',methods = ['POST', 'GET']) 
def login(): 
   if request.method == 'POST' and request.form['txtemail'] == 'tutorial101@blogspot.com' and request.form['txtpass'] == 'ednalan' :
      return redirect(url_for('success'))
   else:
      return redirect(url_for('errorlogin'))

@app.route('/success')
def success():
   return '<h1>logged in successfully</h1>'
 
@app.route('/errorlogin')
def errorlogin():
   return '<h1>Bad Credentials. Please login again <a href = "/">login</a></h1>'
   
if __name__ == '__main__':
   app.run(debug = True)
//log_in.html
<html>
   <body>
 <form method = "post" action = "/login">  
  <p><h3>Login Account</h3></p>
        <table>  
            <tr><td>Email</td><td><input type = 'email' name = 'txtemail'></td></tr>  
            <tr><td>Password</td><td><input type = 'password' name = 'txtpass'></td></tr>  
            <tr><td><input type = "submit" value = "Submit"></td></tr>  
        </table>  
    </form> 
   </body>
</html>

Errors

Standard HTTP Codes
The following HTTP codes are standardized.

HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT
The default status code is HTTP_302_FOUND.

The abort() function
The abort() function is used to handle the cases where the errors are involved in the requests from the client side, such as bad requests, unauthorized access and many more. However, the error code is to be mentioned due to which the error occurred.

The syntax to use the abort() function is given below.

Flask.abort(code) 

The Following error codes depending upon the specified errors.

400: for bad requests
401: for unauthorized access
403: for forbidden
404: for not found
406: for not acceptable
415: for unsupported media types
429: for too many requests
from flask import Flask, render_template, request, redirect, url_for, abort
# Initialize the Flask application
app = Flask(__name__)


@app.route('/')
def index():
   return render_template('log_in.html')
   
@app.route('/login',methods = ['POST', 'GET']) 
def login(): 
   if request.method == 'POST' and request.form['txtemail'] == 'tutorial101@blogspot.com' and request.form['txtpass'] == 'ednalan' :
      return redirect(url_for('success'))
   else:
      abort(401)

@app.route('/success')
def success():
   return '

logged in successfully

' if __name__ == '__main__': app.run(debug = True)

Sunday, January 19, 2020

Flask – Sessions

Flask – Sessions

A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY.


The following code is a simple demonstration of session works in Flask.


from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)

app.secret_key = 'cairocoders-ednalan0711'

@app.route('/')
def index():
    if 'username' in session:
        username = session['username']
  
        return 'Logged in as ' + username + '<br>' + \
         "<b><a href = '/logout'>click here to log out</a></b>"
    return "You are not logged in <br><a href = '/login'></b>" + \
      "click here to log in</b></a>"
   
@app.route('/login', methods = ['GET', 'POST'])
def login():
   if request.method == 'POST':
      session['username'] = request.form['username']
      return redirect(url_for('index'))
   
   return "<form action = '' method = 'post'> " + \
      "<p><input type = text name = username></p> " + \
      "<p><input type = submit value = Login></p> " + \
   "</form>"
   
@app.route('/logout')
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('index'))
   
if __name__ == '__main__':
   app.run(debug = True)

Tuesday, January 14, 2020

Hello World - How to Make an Alexa Skill with Python part 2

Hello World - How to Make an Alexa Skill with Python part 2
 
#lambda_function.py
from __future__ import print_function
import json
 
# We'll start with a couple of globals...
CardTitlePrefix = "Greeting"

# --------------- entry point -----------------
 
def lambda_handler(event, context):
    # TODO implement
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])
          
    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},
                           event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])
    #return response("", response_plain_text("Hello from Lambda!", True))
 

# --------------- Events ------------------
def on_session_started(session_started_request, session):
    """ Called when the session starts """

    print("on_session_started requestId=" + session_started_request['requestId']
          + ", sessionId=" + session['sessionId'])

def on_launch(launch_request, session):
    """ Called when the user launches the skill without specifying what they want """

    print("on_launch requestId=" + launch_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # Dispatch to your skill's launch
    return get_welcome_response()
   
def on_intent(intent_request, session):
    """ Called when the user specifies an intent for this skill """

    print("on_intent requestId=" + intent_request['requestId'] +
          ", sessionId=" + session['sessionId'])
          
    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']   
    
    # Dispatch to your skill's intent handlers
    if intent_name == "greeting":
        return say_hello()
    elif intent_name == "AMAZON.HelpIntent":
        return get_welcome_response()
    elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
        return handle_session_end_request()
    else:
        raise ValueError("Invalid intent") 
          
# --------------- Functions that control the skill's behavior ------------------

def get_welcome_response():
    session_attributes = {}
    card_title = "Hello"
    speech_output = "Welcome to the Hello World demonstration... Ask me to say hello."
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = "I'm sorry - I didn't understand. You should ask me to say hello..."
    should_end_session = False
    return response(session_attributes, response_plain_text(card_title, speech_output, reprompt_text, should_end_session))
 
def say_hello():
    """
    Return a suitable greeting...
    """
    card_title = "Greeting Message"
    greeting_string = "Hello! this is a demonstration of alexa hello word using python"
    return response({}, response_plain_text(card_title, greeting_string, "Ask me to say hello...", True))

def handle_session_end_request():
    card_title = "Session Ended"
    speech_output = "Have a nice day! "
    # Setting this to true ends the session and exits the skill.
    should_end_session = True
    return response({}, response_plain_text(
        card_title, speech_output, None, should_end_session))
        
# --------------- speech response handlers -----------------
# build the json responses
 
def response_plain_text(title, output, reprompt_text, endsession):
    """ create a simple json plain text response  """
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': CardTitlePrefix + " - " + title,
            'content': output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': endsession
    }
 
def response(session_attributes, speech_response):
    """ create a simple json response """
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speech_response
    }
//skill.json
{
    "interactionModel": {
        "languageModel": {
            "invocationName": "demo quiz",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "greeting",
                    "slots": [],
                    "samples": [
                        "hello word",
                        "hello"
                    ]
                },
                {
                    "name": "AMAZON.RepeatIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StartOverIntent",
                    "samples": [
                        "start new game"
                    ]
                }
            ],
            "types": []
        }
    }
}

Monday, January 13, 2020

Hello World - How to Make an Alexa Skill with Python part 1

Hello World - How to Make an Alexa Skill with Python part 1
import json

# --------------- entry point -----------------

def lambda_handler(event, context):
    """ App entry point  """
    return response("", response_plain_text("hello word", True))


# --------------- speech response handlers -----------------
# build the json responses

def response_plain_text(output, endsession):
    """ create a simple json plain text response  """
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },     
        'shouldEndSession': endsession
    }

def response(attributes, speech_response):
    """ create a simple json response """
    return {
        'version': '1.0',
        'sessionAttributes': attributes,
        'response': speech_response
    }
//demoquiz.json
{
    "interactionModel": {
        "languageModel": {
            "invocationName": "demo quiz",
            "intents": [
                {
                    "name": "AMAZON.CancelIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.HelpIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StopIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.NavigateHomeIntent",
                    "samples": []
                },
                {
                    "name": "demo quiz",
                    "slots": [],
                    "samples": [
                        "start"
                    ]
                },
                {
                    "name": "AMAZON.RepeatIntent",
                    "samples": []
                },
                {
                    "name": "AMAZON.StartOverIntent",
                    "samples": [
                        "start new game"
                    ]
                }
            ],
            "types": []
        }
    }
}

Friday, January 10, 2020

Install Virtualenv on Windows 10 with PowerShell

Install Virtualenv on Windows 10 with PowerShell

Install Django Version 3.0.2 on windows 10 | Create Project and Setting Admin

Install Django Version 3.0.2 on windows 10 | Create Project and Setting Admin

Download and Install Git On Windows 10 | basic command | push the file to GitHub

Download and Install Git On Windows 10 | basic command | push the file to GitHub

Monday, January 6, 2020

Upload Multiple Images and Store in Database using PHP and MySQLi

Upload Multiple Images and Store in Database using PHP and MySQLi
CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `uploaded_on` datetime NOT NULL,
  `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `images`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `images`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Multiple Images and Store in Database using PHP and MySQL</title> 
</head>
<body>
<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName     = "testingdb";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

if(isset($_POST['submit'])){
    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');
    
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path
            $fileName = basename($_FILES['files']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;
            
            // Check whether file type is valid
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){
                // Upload file to server
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";
                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';
                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }
        
        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL,',');
            // Insert image file name into database
            $insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
            if($insert){
                $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
                $statusMsg = "Files are uploaded successfully.".$errorMsg;
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }
    }else{
        $statusMsg = 'Please select a file to upload.';
    }
    
    // Display status message
    echo $statusMsg;
}
?>
  <p><h2>Upload Multiple Images and Store in Database using PHP and MySQLi</h2></p>
            <form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple >
    <input type="submit" name="submit" value="UPLOAD">
   </form>

</body>
</html>

Related Post