Is this code correct? Data insert into MySql using PHP and Jquery Ajax


#1

Hi, This very simple code is working. Plz ignore the form validation and other extra stuff like duplicate data entry for now.

Is the code 100% correct? I mean do you notice any bad practice? Youtube PHP tuts are full of outdated and bad practice videos.

index.html

<body>

<script>
	$(document).ready(function() {
		$('.submit').click(function(e) {			
			e.preventDefault();
			var name = $('#name').val();
			var age = $('#age').val();



			console.log(name);
			console.log(age);

			$.ajax({
				type: 'POST',
				data: {name: name, age: age},
				url: 'insert.php',
				success: function() {
					$(".result").html("Added");
				}				
			});
		});
	});
</script>

<p class="result"></p>
<form id="myform" method="post">
Name: <input id="name" type="text" name="name">
Age: <input id="age" type="text" name="age">
<input class="submit" type="button" value="Submit">
</form>

</body>

insert.php

<?php
require("connect.php");

    $name = $_POST['name'];
    $age = $_POST['age'];

    $sql = "INSERT INTO tb1p1 (name, age) VALUES ('$name', '$age')";
    $result = mysqli_query($connect, $sql) or die ('Error querying database.');
    mysqli_close($connect);
    echo "Customer Added";

#2

Your PHP should be using prepared statements instead of putting variables in the string directly to prevent SQL Injection.

$statement = mysqli_prepare($connect, 'INSERT INTO tb1p1 (name, age) VALUES (?, ?)');
mysqli_stmt_bind_param($statement, 'ss', $name, $age);
mysqli_stmt_execute($statement);

This sends the query to the database separately from the data that is to be inserted, so the database won’t mix them up.

Also, I don’t like the practice of include-ing a file, and then all of a sudden a global $connect exists. If you want it do it like this then at least return the connection from connect.php:

return mysqli_connect(...);

and then in your insert.php:

$connect = require('connect.php');

Better yet would be to abstract the notion of a database behind a custom class, but that might be taking things too far for now :slight_smile:

EDIT: Also the table name tb1p1 is quite poor, it doesn’t convey any information as to what I might find in there.