Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,754,016 members, 6,541,792 topics. Date: Sunday, 17 October 2021 at 01:20 AM

Simple CRUD Application In PHP And Mysql – Part 3 - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Simple CRUD Application In PHP And Mysql – Part 3 (1062 Views)

. / Simple CRUD Application In PHP And Mysql – Part 2 / Simple CRUD Application In PHP And Mysql (2) (3) (4)

(1) (Reply)

Simple CRUD Application In PHP And Mysql – Part 3 by maekhel(m): 11:13am On Mar 11, 2015
Welcome guys to the third part of the Simple CRUD application In PHP and MySQL. In the previous part, we looked at setting up our working environment and directory structure. We have also created a database and table our application will be using. If your just joining, please refer to the previous parts so as to catch up.
In this part, we will get to the meat of the application and start coding. We will be creating our database connection file (connect.php) and also create staff file (create.php).
Since this tutorial is about database interactions, we must first establish our database connection with which we will use subsequently to connection our database and perform database operations. Open conncet.php file create from previous part, remember this file is in the db folder inside our main CRUD folder. This file should be empty when opened. Now copy and paste the code below into it.
<?php

//collect to our database

$db_server = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "crud";

$db = new mysqli($db_server, $db_user, $db_pass, $db_name);

//check if database connection was successful

if($db->connect_errno){
echo "Could not connect to database";
}
What this code does is to connect to our database. As you can see, am using the mysqli extension which support both procedural and OOP concept. But we will be using the OOP part of it. First I created some variables to hold my database details (these are just mine, remember to change them to your own details). Then a $db variable to hold the database connection which we can always refer to. The mysqli accepts 3 arguments (database server, database user and databse password) and an optional 4th argument (database name). I then went further to check if our database connection was successful using $db->connect_errno. What this does is return an error number if the database connection was not successful hence we echo an appropriate error message.
Having our database connection ready, we can now start performing database operations on that database.
Now open the create.php file, this should also be empty. First thing to do is include our database connection file in the file so as to be able to make use of the database connection created earlier. I used the require() to include the file. You can read more about PHP file inclusion.
<?php
require 'db/connect.php';

?>
Its time to create the HTML form that will accept inputs that will be stored in our database. Copy and paste the code snippets below just after the closing PHP tag (?>wink.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Creating A Simple CRUD Application | TutorialsLodge</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<h1>Create New Staff</h1>
<span class="error"></span>
<span class="success"></span>
<form action="" method="post">
<table class="table">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td><label for="position">Position:</label></td>
<td><input type="text" id="position" name="position"></td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio"></textarea></td>
</tr>
<tr>
<td></td>
<td><button type="submit" class="create" name="create">CREATE</button>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn" href="index.php">BACK</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
This markup is quite straightforward, so I won’t be explaining each of since this is not an HTML tutorial. But there some few things to point out. If you noticed, there are two <span> tags with class error and success respectively. The <span> will display our error and success message respectively. We will update it later. Now to the fun part, the PHP mechanism that will process the form data and insert them into the database. From our form markup, we are using the POST method and the form is submitting to itself since the action attribute is empty. Copy and paste the code below in between the PHP tags (<?php and ?>wink but after the file inclusion.
$error = ""; //variable to hold our form error message
$success = ""; //variable to hold our success message

if(isset($_POST['create'])){
$name = trim($_POST['name']);
$position = trim($_POST['position']);
$bio = trim($_POST['bio']);

if(empty($name) && empty($position) && empty($bio)){
$error = "You must fill all fields.";
}else{
$insert = $db->prepare("INSERT INTO staff (name, position, bio, joined) VALUES (?, ?, ?, NOW())"wink;
$insert->bind_param('sss', $name, $position, $bio);
if($insert->execute()){
header("location:index.php"wink;
}

}

}
First I declared some empty variable which will hold our error or success message. I then check to make sure the create button of the form is clicked. If the button has been clicked, I then collect the form data through the global PHP array ($_POST) and assign these values variables. I also used the trim() to remove white/blank spaces from both the left and right side of the form data. Then I further check to make sure all the form fields are filled else an error message. If the forms fields are fill, we can move to insert the details into the database. As you can see, am using prepared statement. Prepared Statements make our query more secured compared to just doing normal query. Maybe I will do a tutorial on prepared Statements later. Using the $db->prepare(), which accept normal SQL query but in a different way. I used placeholders instead of actual values for the name, position and bio respectively. For the joined field, I used the MySQL NOW() which will return the current date and time when the query is performed. Now that will have prepared the query, it time to bind params which will replace the placeholders. I assigned this prepare to a variable called $insert which we can later use as reference. We do that using the bind_param(). This method accepts 2 arguments, the first is the data type of the placeholder (in our case which are all string values), so that why I have ‘sss’. Each s stands for each string value. The second argument is a list of the actual values that will replace the placeholders. Since we have already assigned these values to variables, we just pass the variables as the list of value of the second argument. After the binding is to now execute the whole query using execute(). Now if the query was executed successfully we redirect to the index.php page (which we will create later) using the header().
Update your markup the reflect the error or success message as below:
<span class="error"><?php if(isset($error)) echo $error;?></span>
<span class="success"><?php if(isset($success)) echo $success;?></span>
The complete code for the create.php file is shown below:
<?php
require 'db/connect.php';

$error = ""; //variable to hold our form error message
$success = ""; //variable to hold our success message

if(isset($_POST['create'])){
$name = trim($_POST['name']);
$position = trim($_POST['position']);
$bio = trim($_POST['bio']);

if(empty($name) && empty($position) && empty($bio)){
$error = "You must fill all fields.";
}else{
$insert = $db->prepare("INSERT INTO staff (name, position, bio, joined) VALUES (?, ?, ?, NOW())"wink;
$insert->bind_param('sss', $name, $position, $bio);
if($insert->execute()){
header("location:index.php"wink;
}

}

}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Creating A Simple CRUD Application | TutorialsLodge</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<h1>Create New Staff</h1>
<span class="error"><?php if(isset($error)) echo $error;?></span>
<span class="success"><?php if(isset($success)) echo $success;?></span>
<form action="" method="post">
<table class="table">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td><label for="position">Position:</label></td>
<td><input type="text" id="position" name="position"></td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio"></textarea></td>
</tr>
<tr>
<td></td>
<td><button type="submit" class="create" name="create">CREATE</button>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn" href="index.php">BACK</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
That’s the end of this part, see you in the next part. Don’t wanna miss the next tutorial, subscribe to our newsletter. If you have any questions or suggestions as regards this tutorial, kindly leave them in the comment form below. I will like to hear from you.

Subscribe to our newsletter and join subscribers who are already receiving blog updates directly in their mail box.

Source: http://tutorialslodge.com/simple-crud-application-in-php-and-mysql-part-3/

(1) (Reply)

Pls Teach Me How To Hack Gmail Account Easily With Phone / Anyone Know Where I Can Download HOT TOPIX Wordpress Template For Free?? / Payoneer Users, How Do I Request For Gbp Card

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2021 Oluwaseun Osewa. All rights reserved. See How To Advertise. 127
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.