DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Kalatravas has posted 29 posts at DZone. View Full User Profile

PHP Script That Updates Mysql Database , With Variables Received Through POST

  • submit to reddit



// This script just defines the MySQL constants.

DEFINE ('DB_USER', 'root');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'kostas_123');

// No closing PHP tag to avoid 'headers already sent' errors.

//Here follows the php script for database update with variables received through POST

// addEmployee.php
// This script receives six pieces of information in $_POST.
// The script performs minimal validation, then inserts the data into the database.

// Minimal validation:
if (isset($_POST['departmentId'], $_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['phoneExt'], $_POST['hireDate']) && ( ((int)$_POST['departmentId']) > 0 )  && ( ((int)$_POST['phoneExt']) > 0 ) ) {

	// Include the database information script:

	// Connect to the database:
	$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	// If a connection was established, run the query:
	if ($dbc) {
		// Sanctify the provided information:
		$firstName = mysqli_real_escape_string($dbc, trim($_POST['firstName']));
		$lastName = mysqli_real_escape_string($dbc, trim($_POST['lastName']));
		$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
		$hireDate = mysqli_real_escape_string($dbc, trim($_POST['hireDate']));
		$departmentId = (int) $_POST['departmentId'];
		$phoneExt = (int) $_POST['phoneExt'];

		// Run the query:
		$q = "INSERT INTO employees (departmentId, firstName, lastName, email, phoneExt, hireDate) VALUES ($departmentId, '$firstName', '$lastName', '$email', $phoneExt, '$hireDate')";
		$r = mysqli_query($dbc, $q);

		// Report upon the results:
		if (mysqli_affected_rows($dbc) == 1) {
			echo 'The employee has been added.';
		} else {
			echo 'The employee could not be added due to a system error.';

	} else {
		echo 'A server error occurred.';

} else {
	echo 'This page has been accessed in error.';