How to Store data on MySQL using PHP, BootstrapVue, and Axios?

How to Store data on MySQL using PHP, BootstrapVue, and Axios?

Hello everyone, in this tutorial we are going to use the BootstrapVue framework, PHP, and Axios to store client-side data on our MySQL database.

send and store data on MySQL using PHP, BootstrapVue, and AxiosLet’s start this tutorial by creating database table. To create a database table, just you have to paste and run the following code.

CREATE TABLE bootstrapvue (
  id bigint(20) NOT NULL,
  plainText varchar(50) NOT NULL,
  password varchar(50) NOT NULL,
  email varchar(50) NOT NULL,
  date date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

After that, you need to create 3 files; index.php,  app.js, and  api.php.

Then inside index.php write the following code.

<!DOCTYPE html>
<html>
<head>
  <title>Vue Bootstrap</title>
  <!-- Load required Bootstrap and BootstrapVue CSS -->
  <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
  <link type="text/css" rel="stylesheet" href="//unpkg.com/[email protected]/dist/bootstrap-vue.min.css" />

  <!-- Load polyfills to support older browsers -->
  <script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>

  <!-- Load Vue followed by BootstrapVue -->
  <script src="//unpkg.com/[email protected]/dist/vue.min.js"></script>
  <script src="//unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>	
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
</head>
<body>
  <div id="app">
    <b-container class='mt-5'>
      <b-form @submit='onSubmit'>
        <b-row class='my-1'>
          <b-col cols='2'>
            <label for='type-text'>Text: </label>
          </b-col>
          <b-col cols='8'>
            <b-form-input v-model='enteredData.plainText' id='type-text' type='text'></b-form-input>
          </b-col>
        </b-row>

        <b-row class='my-1'>
          <b-col cols='2'>
            <label for='type-password'>Password: </label>
          </b-col>
          <b-col cols='8'>
            <b-form-input v-model='enteredData.password' id='type-password' type='password'></b-form-input>
          </b-col>
        </b-row>

        <b-row class='my-1'>
          <b-col cols='2'>
            <label for='type-email'>Email: </label>
          </b-col>
          <b-col cols='8'>
            <b-form-input v-model='enteredData.email' id='type-email' type='email'></b-form-input>
          </b-col>
        </b-row>

        <b-row class='my-1'>
          <b-col cols='2'>
            <label for='type-date'>Date: </label>
          </b-col>
          <b-col cols='8'>
            <b-form-input v-model='enteredData.date' id='type-date' type='date'></b-form-input>
          </b-col>
        </b-row>

        <b-row class='pt-3'>
          <b-col cols='2'></b-col>
          <b-col cols='8' class='text-center'>
            <b-button type='submit' variant='primary'>Submit</b-button>
          </b-col>
        </b-row>

        <b-row>
          <b-col cols='10'>
            <b-card class='mt-3'
              header='Form Data Result'>
              <pre class="m-0">{{enteredData}}</pre>
            </b-card>
          </b-col>
        </b-row>
      </b-form>
    </b-container>
  </div>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>

20; There is @submit='onSubmit', which means whenever user click the submit button it will triger the function or method called onSubmit which you will find on app.js file.

26; There you find v-model='enteredData.plainText', v-model is use to synchronize the data. Then you find enteredData and then plainText because if you look inside app.js file there you can see plainText is inside enteredData.

Then open  app.js file and write the following code

var vue = new Vue({
  el: '#app',
  data: {
    enteredData: {
      plainText: '',
      password: '',
      email: '',
      date: ''
    }
  },

  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      var formData = vue.toFormData(vue.enteredData)
      axios.post('api.php', formData)
      .then( response=> {
        if (response.data.error) {
          vue.noteMsg('danger', response.data.message)
        } else {
          vue.noteMsg('info', response.data.message)
        }
      })
      .catch( error=> {
        vue.noteMsg('danger', error)
      });
    },
    noteMsg(color, msg) {
      this.$bvToast.toast(msg, {
        title: 'System message',
        variant: color,
        solid: true
      })
    },
    toFormData(obj) {
      var form_data = new FormData()
      for(var key in obj) {
        form_data.append(key, obj[key])
      }
      return form_data
    }
  }
})

2; Here we mention the element by its id, which we want to control. In our case we want to control the div with an id app. So I write # for id and the name app.

3; Then we create some variables to hold users data.

16; We are sending users data to api.php after that, we get response. If that response contain error message then we show red notification else the notification is blue in color.

24; If some reason, data is unable to send from client side then we catch that error here.

At last open api.php then write a following code

<?php 

$conn = new mysqli('localhost', 'root', '', 'yourDatabaseName');

if($conn->connect_error) {
  die('Could not connect to the database');
}

$response['error'] = false;

$plainText = $_POST['plainText'];
$password = $_POST['password'];
$email = $_POST['email'];
$date = $_POST['date'];

$insertQuery = $conn->query("INSERT INTO bootstrapvue (plainText, password, email, date) VALUES ('$plainText', '$password', '$email', '$date')");

if ($insertQuery) {
  $response['message'] = 'New record inserted sucessfully';
} else {
  $response['error'] = true;
  $response['message'] = $conn->error;
}

$conn->close();
header('content-type: application/json');
echo json_encode($response);
die();
?>

3; First we make a database connection.

5; If there is an error during a database connection then we display error message and exit from the program.

9; Then we set default value $response['error'] = false;

16; Then we execute insert query to store users data in the database

18; If this query execute sucessfully then we store success message on $response['message']

20; If not we store some error message

26; At last we return $response array.

And, this is how we send data from client side using BootstrapVue, and Axios and store that data in MySQL database using PHP

After this, you would also like to store image into server folder using PHP, and MySQL database

Also watch the video of this coding

Useful links BootstrapVue, Axios.

Share this post