Articles by "MYSQL"
Showing posts with label MYSQL. Show all posts
In today tutorial we are going to be looking at how to import an sql file into the database to create table in the database for storage of database of personal details.You can modify for your own taste,this tutorial is basically for learning.But before we proceed there are some basic things we need to set in place to run this code successfully.
how-to-import-mysql-using-php.jpg

Below are the content of this tutorials:

we need to create a style for the html using css.
we need to create a database and also connect to the database check here for how to create database.
We need our sql script that we need to import into the database.
We are require to write the php script that will help in the execution process.
We are going to be taking each of the content step by step,so follow the steps carefully and import your script to your database so cheaply within shortest period of time

1. Open your code editor copy and paste the below code and save as style.css
<style>

body {

width:600px;

text-align:center;

}

.import-message {

padding: 10px;

}

.success-message {

background-color: #a8ebc4;

   border-color: #1b7943;

   color: #1b7943;

}

.error-message {

border-color: #d96557;

    background: #f0c4bf;

    color: #d96557;

}

</style>

2. Next create a database and also connect to the database with the below code

<?php

$db['db_host'] = "localhost";

$db['db_user'] = "root";

$db['db_pass'] ="";

$db['db_name']  = "sqldatabase";



foreach($db as $key => $value){

   

    define(strtoupper($key),$value);

}

   

   

$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);

?>


Save the above code with db.php

3. Now the sample SQL we are going to be import are given below and it save with mydatabase.sql

CREATE TABLE IF NOT EXISTS `contact_table` (

  `id` int(11) NOT NULL,

  `first_name` varchar(255) NOT NULL,

  `last_name` varchar(255) NOT NULL,

  `address` varchar(255) NOT NULL,

  `email` varchar(255) NOT NULL,

  `phone` varchar(20) NOT NULL,

  `date_of_birth` date NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;


4. Creating the php code with the code given below and save as index.php to end with the tutorial

<html>

<head>

<link rel="stylesheet" type="text/css" href="style.css">

</head>

<body>

<?php

<?php include "db.php";?>

$query = ' ';

$myScript = file('mydatabase.sql');

foreach ($myScript as $line) {



$startWith = substr(trim($line), 0 ,2);

$endWith = substr(trim($line), -1 ,1);



if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {

continue;

}



$query = $query . $line;

if ($endWith == ';') {

mysqli_query($connection,$query) or die('<div class="error-message import-message">There SQL Query cannot be executed due to some problems <b>' . $query. '</b></div>');

$query= ' ';

}

}

echo '<div class="success-message import-message">importation of the SQL file was  successfully</div>';

?>

</body>

</html>


Following the steps successfully you have known how to import sql to the database using php.





Let take a tour on how to create a simple user login session timeout logout in php,this functionality is to set the time in which user login session will expire and the user will be logged out automatically from the website.At times the essence of this , is mainly for security purpose to avoid other from getting access into your account.
We will take it in more simplified way for your better understanding,just follow the steps in a known time the functionality will be created.

how-to-import-mysql-using-php.jpg
Steps To Create User Login Session Timeout Logout In PHP


1. Create a script with php and name it as functions.php with the below code
<?php

function isLoginSessionExpired() {

$login_session_duration = 10;

$current_time = time();

if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){

if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){

return true;

}

}

return false;

}

?>

This help in setting the session during,once the duration is exceeded the user will be logged out automatically from the website.
2. Create style to give our page more beautiful look with the below code and name it styles.css
body{width:610px;}

.tableheader {

background-color: #95BEE6;

color:white;

font-weight:bold;

}

.tablerow {

background-color: #A7D6F1;

color:white;

}

.message {

color: #333;

border: #FF0000 1px solid;

background: #FFE7E7;

padding: 5px 20px;

}



.tblLogin{

margin-top : 2px;

}

3. Create user logging session and name it user_login_session.php with the given code below
<?php

session_start();

$message="";

if(count($_POST)>0) {

if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin") {

$_SESSION["user_id"] = $row[user_id];

$_SESSION["user_name"] = $row[user_name];

$_SESSION['loggedin_time'] = time();

} else {

$message = "Invalid Username or Password!";

}

}

if(isset($_SESSION["user_id"])) {

header("Location:user_dashboard.php");

}

?>

<html>

<head>

<title>User Login</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<form name="frmUser" method="post" action="">

<div class="message"><?php if($message!="") { echo $message; } ?></div>

<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">

<tr class="tableheader">

<td align="center" colspan="2">Enter Login Details</td>

</tr>

<tr class="tablerow">

<td align="right">Username</td>

<td><input type="text" name="user_name"></td>

</tr>

<tr class="tablerow">

<td align="right">Password</td>

<td><input type="password" name="password"></td>

</tr>

<tr class="tableheader">

<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

</body>

</html>

4. Also create user logout session with the code below and name it logout.php
<?php

session_start();

unset($_SESSION["user_id"]);

unset($_SESSION["user_name"]);

$url = "index.php";

if(isset($_GET["session_expired"])) {

$url .= "?session_expired=" . $_GET["session_expired"];

}

header("Location:$url");

?>

This script help us to destroy the session when it has expired and pull out the user from being logged into the website.
5. Next follow by creating the user dashboard and name it user_dashboard.php with the below code
<?php

session_start();

include("functions.php");

if(isset($_SESSION["user_id"])) {

if(isLoginSessionExpired()) {

header("Location:logout.php?session_expired=1");

}

}

?>

<html>

<head>

<title>User Login</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<table border="0" cellpadding="10" cellspacing="1" width="100%">

<tr class="tableheader">

<td align="center">User Dashboard</td>

</tr>

<tr class="tablerow">

<td>

<?php

if(isset($_SESSION["user_name"])) {

?>

Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.

<?php

}

?>

</td>

</tr>

</body>

</html>


6. Finally create an index.php code with the given code below
<?php

session_start();

include("functions.php");

$message="";

if(count($_POST)>0) {

if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin") {

$_SESSION["user_id"] = 1001;

$_SESSION["user_name"] = $_POST["user_name"];

$_SESSION['loggedin_time'] = time();

} else {

$message = "Invalid Username or Password!";

}

}



if(isset($_SESSION["user_id"])) {

if(!isLoginSessionExpired()) {

header("Location:user_dashboard.php");

} else {

header("Location:logout.php?session_expired=1");

}

}



if(isset($_GET["session_expired"])) {

$message = "Login Session is Expired. Please Login Again";

}

?>

<html>

<head>

<title>User Login Session Timeout Logout in PHP</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<form name="frmUser" method="post" action="">

<?php if($message!="") { ?>

<div class="message"><?php echo $message; ?></div>

<?php } ?>

<table border="0" cellpadding="10" cellspacing="1" width="100%" class="tblLogin">

<tr class="tableheader">

<td align="center" colspan="2">Enter Login Details</td>

</tr>

<tr class="tablerow">

<td align="right">Username</td>

<td><input type="text" name="user_name"></td>

</tr>

<tr class="tablerow">

<td align="right">Password</td>

<td><input type="password" name="password"></td>

</tr>

<tr class="tableheader">

<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>

</tr>

</table>

</form>

</body>

</html>


Having follow the steps accordingly,then you have built a simple user login session timeout in PHP

Contact form as the name implies is a medium of interaction between a website owner and the viewer. The contact us form allow visitors to communicate with the site owner from the website. Using the contact us form, visitors can easily submit their query, views, opinions and suggestions to the site administrator about the website, service or product that is been provided by the site.



Contact us form is very crucial in website for easy communication between the viewer and the site owner.Through this medium the viewer send the administration email base on the services been offered and this medium also help the administrator to have quick response to this client.

In this tutorial we are taking a tour on how to create a basic contact us form using PHP,CSS and HTML in building this system. Contact us notify the admin via email whenever there is a request from client or suggestion.

This tutorial is divided into three parts the PHP part which serve as the engine per say,HTML which is just like the body and also the CSS which gives the HTML a beautiful layout.We are going to take it one step at a time,so relax as we move on.

Steps Involves in Creating A Simple Contact Us Form

Below are some of the steps which we are going to be undertaking.

1.    Create a Database if you have not done that and if you do not know how to create a database follow our tutorials on how to create a database here.

2.    Create the HTML page.In this section we are going to create a HTML page that will collect our values from our client and submit it to our website database and admin email account by adding the given below code to our HTML page of our website.

<h2>Basic PHP Contact Form</h2>
<div class="contactFrm">
    <?php if(!empty($statusMsg)){ ?>
        <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
    <?php } ?>
    <form action="" method="post">
        <h4>Name</h4>
        <input type="text" name="name" placeholder="Your Name" required="">
        <h4>Email </h4>
        <input type="email" name="email" placeholder="email@example.com" required="">
        <h4>Subject</h4>
        <input type="text" name="subject" placeholder="Write subject" required="">
        <h4>Message</h4>
        <textarea name="message" placeholder="Write your message here" required=""> </textarea>
        <input type="submit" name="submit" value="Submit">
        <div class="clear"> </div>
    </form>
</div>


3.The Next step,is to create our PHP page that will help in posting this values to our database and and to admin email account by verifying the email, checking for blank input etc,escaping some variables before posting it to our database.Copy and Paste the below code to PHP page and save with .php extension.

<?php
$statusMsg = '';
$msgClass = '';
if(isset($_POST['submit'])){
    // Get the submitted form data
    $email = $_POST['email'];
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
   
    // Check whether submitted data is not empty
    if(!empty($email) && !empty($name) && !empty($subject) && !empty($message)){
       
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
            $statusMsg = 'Please enter your valid email.';
            $msgClass = 'errordiv';
        }else{
            // Recipient email
            $toEmail = 'your_email@gmail.com';
            $emailSubject = 'Contact Request Submitted by '.$name;
            $htmlContent = '<h2>Contact Request Submitted</h2>
                <h4>Name</h4><p>'.$name.'</p>
                <h4>Email</h4><p>'.$email.'</p>
                <h4>Subject</h4><p>'.$subject.'</p>
                <h4>Message</h4><p>'.$message.'</p>';
           
            // Set content-type header for sending HTML email
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
           
            // Additional headers
            $headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";
           
            // Send email
            if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
                $statusMsg = 'Your contact request has been submitted successfully !';
                $msgClass = 'succdiv';
            }else{
                $statusMsg = 'Your contact request submission failed, please try again.';
                $msgClass = 'errordiv';
            }
        }
    }else{
        $statusMsg = 'Please fill all the fields.';
        $msgClass = 'errordiv';
    }
}
?>


4.Next the step is to beautify our HTML page with some CSS code.To do this copy and paste the below code in your stylesheet page and save as .css extension.

.contactFrm h4 {
    font-size: 1em;
    color: #252525;
    margin-bottom: 0.5em;
    font-weight: 300;
    letter-spacing: 5px;
}
.contactFrm input[type="text"], .contactFrm input[type="email"] {
    width: 92%;
    color: #9370DB;
    background: #fff;
    outline: none;
    font-size: 0.9em;
    padding: .7em 1em;
    border: 1px solid #9370DB;
    -webkit-appearance: none;
    display: block;
    margin-bottom: 1.2em;
}
.contactFrm textarea {
    resize: none;
    width: 93.5%;
    background: #fff;
    color: #9370DB;
    font-size: 0.9em;
    outline: none;
    padding: .6em 1em;
    border: 1px solid #9370DB;
    min-height: 10em;
    -webkit-appearance: none;
}
.contactFrm input[type="submit"] {
    outline: none;
    color: #FFFFFF;
    padding: 0.5em 0;
    font-size: 1em;
    margin: 1em 0 0 0;
    -webkit-appearance: none;
    background: #9370DB;
    transition: 0.5s all;
    border: 2px solid #795CB4;
    -webkit-transition: 0.5s all;
    transition: 0.5s all;
    -moz-transition: 0.5s all;
    width: 47%;
    cursor: pointer;
}
.contactFrm input[type="submit"]:hover {
    background: none;
    color: #9370DB;
}
p.statusMsg{font-size:18px;}
p.succdiv{color: #008000;}
p.errordiv{color:#E80000;}



I believe this tutorial has help you a lot in carrying out this simple project on your website,do not forget to share with a friend by clicking on the share button below and you can also subscribe to get the latest update delivered to your inbox by clicking here

For most programmers who like writing articles on different type of programs related tutorials,In one way or the other will want their code to highlighter just like the one written on a well known code editor like sublime text, brackets etc. Today we are going to be looking at how to highlight your code on blogger with just a simple code highlighter known as PrismJs.
Are still wondering what's PrismJs ? Check it's official page(website) for more information http://prismjs.com/, it's the second generation of syntax highlighting, it is more lightweight and that doesn't affect your page load time at all.


The overall adding procedure is the same as mentioned on the PrismJS official page but there are yet some modifications need to be made if you want it to work properly on Blogger blogs. In this tutorial i will provide the links to minified version of the codes, once you get the idea about adding it, you can use whatever version you want.

How To Add PrismJs on Your Blogger

•    Firstly login into your blogger site.
•    After you have logged in go to your Dashboard and click on theme
•    Proceed by clicking Edit HTML
•    After the Edit HTML has loaded press CTRL + F  and search for </head>
•    Copy and paste the code given below just before </head>


<link rel="stylesheet" href="http://prismjs.com/themes/prism.css"/>
 

<script type="text/javascript" src="http://prismjs.com/prism.js">

•    Finally Click on save
Tips:Make sure you backup your template before you carry out the procedure given above.

Tips : The links in the script and link tag is only for demo of the code, if you want to use different theme on your hosted website then you can download the version of your choice on PrismJS Download page, upload it to your hosting service and replace the links (prismjs.com/theme/prism.css and prismjs.com/prism.js) with your hosted file's links .

How To Display Code on Your Blogger Using PrismJs

The following example is for displaying HTML codes in your pages, to define any languages you have to edit language-xxx

<pre class='language-markup'>

<code>

// Your HTML Code here

</code>

</pre>

Tip: You can add the class for a language to any parent element and the children elements will inherit the defined language. It is very useful when you just want to display codes of the same language in a page also xxx refer to the language you are writing on eg php.

How To Implement Different Languages

To define languages you just have to change the language-xxxx in the class you can find in <pre> and <code> tags.

    For HTML we will use this tags to wrap the display codes
       
   
<pre class='language-markup'>

    <code>

    // Your HTML Code here

    </code>

    </pre>


    language-markup is used for HTML markups. You may use this for XML codes too.
    CSS will be wrapped into this tags
       

 <pre class='language-css'>

    <code>

    // Your CSS Code here

    </code>

    </pre>

    JavaScript can be wrapped into this

       
   
<pre class='language-javascript'>

    <code>

    // Your JS Code here

    </pre>

    </code>

    JQuery can also be displayed with this.
    Want to learn more than check out the PrismJS homepage

Read also: How to Use Google Prettify Syntax Highlighter With Blogger


How To Implement  Different Themes

The great thing about PrismJS syntax highlighter is that you can make the code blend with your site's overall theme by using different themes provided by PrismJS. There are the following themes available by default for it : default, dark, funky, okaidia, twilight, coy and solarized light

With a single addition of a CSS file you can change the theme for all PrismJS syntax highlighter instances on your blog.
In the first step we added the default theme,
  
<link rel="stylesheet" href="http://prismjs.com/themes/prism.css"/>

<script type='text/javascript' src="http://prismjs.com/prism.js"></script>

   

The http://prismjs.com/themes/prism.css in the first line of code sets the theme to default, while the following sets it to its corresponding theme.

Dark
 
 <link rel="stylesheet" href="http://prismjs.com/themes/prism-dark.css"/>

Funky

<link rel="stylesheet" href="http://prismjs.com/themes/prism-funky.css"/>

Okaidia

<link rel="stylesheet" href="http://prismjs.com/themes/prism-okaidia.css"/>
 

Twilight

<link rel="stylesheet" href="http://prismjs.com/themes/prism-twilight.css"/>

Coy

<link rel="stylesheet" href="http://prismjs.com/themes/prism-coy.css"/>

Solarized Light
  
<link rel="stylesheet" href="http://prismjs.com/themes/prism-solarizedlight.css"/>

   
     
The post is meanly for those who are new to PHP coding or other PHP coders who are interested to learn for further project in the future. If you are new to PHP web development approach and you are finding it some how difficult, just relax your mind and take a deep breath as we are about to proceed to connecting to a database using PHP and MySQL.
But before we start there are some certain materials required to run PHP, since we are all know that PHP is a server-side scripting language. We need a server to run PHP.In this tutorial we are working offline, so there are some basic requirements

Requirements

These are some of the list of required item to follow along we the tutorials, If you do not have any of the listed materials you can search the web to get them as roll on. Here are the required items as listed below:

  •  PHP Apache Server
  • MySQL Server
  •  Code Editor eg Sublime Text,Notepad++,Brackets etc


NOTE: For the PHP Apache and MySQL server you can download already compiled software that comprises of the two Server eg Xampp Server,Wampp Server etc.

STEPS
1.Install the coder that you have downloaded and also the Server(Xampp,Wampp etc).With these installed then you are ready to go.

2.We are going to be using Xampp server in these tutorials,before you start you will run Xampp server and also a browser

3.After installation run the Xampp server,take glance at how it look like while running.






4.Open your browser and type localhost/phpmyadmin to create a database.Phpmyadmin looks like the below image.






5.Click on new to create database.For this tutorial,we will be creating a database name Basis.After clicking the new button a page will pop-up enter your database name and click Create and the database will be created as shown below.We need to create tables after creating database but for the case of this tutor,we are stoping at database creation.



6.After carrying out step 5 correctly,open your coder and create a page db.php and type the following codes as shown below.
<?php
 $db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] ="";
$db['db_name'] = "basic";
foreach($db as $key => $value){
define(strtoupper($key),$value);
}
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if($connection){
echo "We are connected";
}
?>
Note:With the code typed above,you are now connected to the Database called basic