OnClick Insert Radio Button value into Database using PDO in jQuery Ajax PHP

Hi, Friends in this tutorial I show you how to insert data into MySQL database table using PHP PDO (PHP Data Object). Using Radio button I am going to insert values in the database. PDO helps named parameters, which makes the instant statements easier to read and understand for maintenance. MySQL only helps interrogation point as placeholders in prepared statements. You can handle all errors with one simple try/catch statement, which is way more easy to read than the procedural MySQL way.
If you like to update the data using Popup then here you have an article.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>OnClick Insert Radio Button value into Database using PDO in Jquery Ajax PHP | SoftAOX Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> </head> <body> <h1> On Click Insert Radio Button Value into Database</h1> <input type="radio" name="gender" value="Male">Male <br/> <br/> <input type="radio" name="gender" value="Female">Female <br/> <br/> <input type="radio" name="gender" value="Others">Others <br/> <h3 id="result"></h3> <br/> <script> $(document).ready(function() { $('input[type="radio"]').click(function() { var gender = $(this).val(); $.ajax({ url: "insert.php", method: "POST", data: { gender: gender }, success: function(data) { $('#result').html(data); } }); }); }); </script> </body> </html> |
insert.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php //Insert Data $hostname = "localhost"; $username = "root"; $password = ""; $databasename = "tut"; try { $conn = new PDO("mysql:host=$hostname;dbname=$databasename",$username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); if(isset($_POST["gender"])) { $query = "INSERT INTO gender(gender) VALUES (:gender)"; $statement = $conn->prepare($query); $statement->execute( array( 'gender' => $_POST["gender"] ) ); $count = $statement->rowCount(); if($count > 0) { echo "Data Inserted Successfully..!"; } else { echo "Data Insertion Failed"; } } } catch(PDOException $error) { echo $error->getMessage(); } ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]