Msaada: Kutengeneza mahusiano kati ya PHP na Database server (MySQL) kwa kutumia XAMMP kwenye windows OS

Sep 12, 2017
5
45
Habari!

Niko na project ya kutengeneza system ambayo itawasaidia vijana kujisajili na kuinga kwenye system(server).

·Naomba msaada wakutengeneza mahusiano kati ya PHP na Database server (MySQL) kwa kutumia XAMMP kwenye window Machine?

Kwa niaba.

Sent using Jamii Forums mobile app
 

Graph

JF-Expert Member
Jul 20, 2016
2,745
2,000
Maswali ya muhimu
1. Unajua PHP?
2. Kama jibu 1 ni ndiyo, kwa kiwango kipi? Kama ni hapana ishia hapa, nenda kwanza kasome php
3. Unajua basics za MySQL? Naongelea kutengeneza table, kuweka data, query na relationships zake?
4. Kama jibu 3 ni ndiyo, ushawahi kutengeneza database rahisi tu yenye table user na colums kama name, email, pass e.t.c? Kama ni hapana, ishia hapa nenda kasome kwanza MySQL basics.
5. Kama majibu yote hapo juu ni ndiyo, umeshindwa vipi kutengeneza login system rahisi? Ingia google andika "php mysql" utaona results fungua ya kwanza itakuonyesha jinsi ya kuconnect php na mysql, na sample kabisa jinsi ya kuinteract na db. Tengeneza table yako then project imeisha.

Kwa kifupi inaenda hivi
- install xamp, washa server ni kuclick tu
- fungua php, andika driver ya mysql unayotumia.
- tengeneza variables zako uanze query

Mfano
Code:
$servername = "localhost";
$username = "username";
$password = "password";

// Unganisha na mysql server
$conn = mysqli_connect($servername, $username, $password);

// Imefanikiwa kuconnect?
if (!$conn) {
    //Imefail ua app na display error message
}

//Kama code imefika hapa then connection imefanikiwa. Tumia connection kufanya queries unazotaka

Sasa hizo ni basics, inakutosha kwa sasa, baadaye ujifunze different app architectures ujue kupangilia app yako vizuri.
 

mwitamarwa

Senior Member
Oct 16, 2016
130
225
Maswali ya muhimu
1. Unajua PHP?
2. Kama jibu 1 ni ndiyo, kwa kiwango kipi? Kama ni hapana ishia hapa, nenda kwanza kasome php
3. Unajua basics za MySQL? Naongelea kutengeneza table, kuweka data, query na relationships zake?
4. Kama jibu 3 ni ndiyo, ushawahi kutengeneza database rahisi tu yenye table user na colums kama name, email, pass e.t.c? Kama ni hapana, ishia hapa nenda kasome kwanza MySQL basics.
5. Kama majibu yote hapo juu ni ndiyo, umeshindwa vipi kutengeneza login system rahisi? Ingia google andika "php mysql" utaona results fungua ya kwanza itakuonyesha jinsi ya kuconnect php na mysql, na sample kabisa jinsi ya kuinteract na db. Tengeneza table yako then project imeisha.

Kwa kifupi inaenda hivi
- install xamp, washa server ni kuclick tu
- fungua php, andika driver ya mysql unayotumia.
- tengeneza variables zako uanze query

Mfano
Code:
$servername = "localhost";
$username = "username";
$password = "password";

// Unganisha na mysql server
$conn = mysqli_connect($servername, $username, $password);

// Imefanikiwa kuconnect?
if (!$conn) {
    //Imefail ua app na display error message
}

//Kama code imefika hapa then connection imefanikiwa. Tumia connection kufanya queries unazotaka

Sasa hizo ni basics, inakutosha kwa sasa, baadaye ujifunze different app architectures ujue kupangilia app yako vizuri.
Hili li jamaa linajua iseee, ma MTU kama haya ndio yanatakiwa kuwa kwenye KUNDI la watu wasiojulikana ili kuipeleka tz kwenye level ya Edward snowdern ( jasus wa kimarekani )

Sent using Jamii Forums mobile app
 

Black Coffee

JF-Expert Member
Aug 26, 2016
1,787
2,000
Maswali ya muhimu
1. Unajua PHP?
2. Kama jibu 1 ni ndiyo, kwa kiwango kipi? Kama ni hapana ishia hapa, nenda kwanza kasome php
3. Unajua basics za MySQL? Naongelea kutengeneza table, kuweka data, query na relationships zake?
4. Kama jibu 3 ni ndiyo, ushawahi kutengeneza database rahisi tu yenye table user na colums kama name, email, pass e.t.c? Kama ni hapana, ishia hapa nenda kasome kwanza MySQL basics.
5. Kama majibu yote hapo juu ni ndiyo, umeshindwa vipi kutengeneza login system rahisi? Ingia google andika "php mysql" utaona results fungua ya kwanza itakuonyesha jinsi ya kuconnect php na mysql, na sample kabisa jinsi ya kuinteract na db. Tengeneza table yako then project imeisha.

Kwa kifupi inaenda hivi
- install xamp, washa server ni kuclick tu
- fungua php, andika driver ya mysql unayotumia.
- tengeneza variables zako uanze query

Mfano
Code:
$servername = "localhost";
$username = "username";
$password = "password";

// Unganisha na mysql server
$conn = mysqli_connect($servername, $username, $password);

// Imefanikiwa kuconnect?
if (!$conn) {
    //Imefail ua app na display error message
}

//Kama code imefika hapa then connection imefanikiwa. Tumia connection kufanya queries unazotaka

Sasa hizo ni basics, inakutosha kwa sasa, baadaye ujifunze different app architectures ujue kupangilia app yako vizuri.
mkuu umetisha uko viwango vingine asee
 
Sep 12, 2017
5
45
Maswali ya muhimu
1. Unajua PHP?
2. Kama jibu 1 ni ndiyo, kwa kiwango kipi? Kama ni hapana ishia hapa, nenda kwanza kasome php
3. Unajua basics za MySQL? Naongelea kutengeneza table, kuweka data, query na relationships zake?
4. Kama jibu 3 ni ndiyo, ushawahi kutengeneza database rahisi tu yenye table user na colums kama name, email, pass e.t.c? Kama ni hapana, ishia hapa nenda kasome kwanza MySQL basics.
5. Kama majibu yote hapo juu ni ndiyo, umeshindwa vipi kutengeneza login system rahisi? Ingia google andika "php mysql" utaona results fungua ya kwanza itakuonyesha jinsi ya kuconnect php na mysql, na sample kabisa jinsi ya kuinteract na db. Tengeneza table yako then project imeisha.

Kwa kifupi inaenda hivi
- install xamp, washa server ni kuclick tu
- fungua php, andika driver ya mysql unayotumia.
- tengeneza variables zako uanze query

Mfano
Code:
$servername = "localhost";
$username = "username";
$password = "password";

// Unganisha na mysql server
$conn = mysqli_connect($servername, $username, $password);

// Imefanikiwa kuconnect?
if (!$conn) {
    //Imefail ua app na display error message
}

//Kama code imefika hapa then connection imefanikiwa. Tumia connection kufanya queries unazotaka

Sasa hizo ni basics, inakutosha kwa sasa, baadaye ujifunze different app architectures ujue kupangilia app yako vizuri.
Nitajuaje MySQL driver's gani ipo installed?

Sent using Jamii Forums mobile app
 

Graph

JF-Expert Member
Jul 20, 2016
2,745
2,000
Nitajuaje MySQL driver's gani ipo installed?

Sent using Jamii Forums mobile app

Mkuu mtumie google akusaidie, kama developer google ni kitu cha muhimu sana. Au ujaribu pia kutafuta solution kwanza kabla ya kuuliza. Hiyo simple code nimekuandikia hapo, ungekua umejisumbua hata kidogo kuiandika ungekua ushatambua kua kuna native mysql driver kwenye php, usingerudi kuuliza hili swali.
 

Lukas4

JF-Expert Member
Aug 24, 2013
980
1,000
Maswali ya muhimu
1. Unajua PHP?
2. Kama jibu 1 ni ndiyo, kwa kiwango kipi? Kama ni hapana ishia hapa, nenda kwanza kasome php
3. Unajua basics za MySQL? Naongelea kutengeneza table, kuweka data, query na relationships zake?
4. Kama jibu 3 ni ndiyo, ushawahi kutengeneza database rahisi tu yenye table user na colums kama name, email, pass e.t.c? Kama ni hapana, ishia hapa nenda kasome kwanza MySQL basics.
5. Kama majibu yote hapo juu ni ndiyo, umeshindwa vipi kutengeneza login system rahisi? Ingia google andika "php mysql" utaona results fungua ya kwanza itakuonyesha jinsi ya kuconnect php na mysql, na sample kabisa jinsi ya kuinteract na db. Tengeneza table yako then project imeisha.

Kwa kifupi inaenda hivi
- install xamp, washa server ni kuclick tu
- fungua php, andika driver ya mysql unayotumia.
- tengeneza variables zako uanze query

Mfano
Code:
$servername = "localhost";
$username = "username";
$password = "password";

// Unganisha na mysql server
$conn = mysqli_connect($servername, $username, $password);

// Imefanikiwa kuconnect?
if (!$conn) {
    //Imefail ua app na display error message
}

//Kama code imefika hapa then connection imefanikiwa. Tumia connection kufanya queries unazotaka

Sasa hizo ni basics, inakutosha kwa sasa, baadaye ujifunze different app architectures ujue kupangilia app yako vizuri.
We jamaa inabidi nikutafute kuna liishu fulani hivi naliandaa, ili nikupe mchongo
 

Black Coffee

JF-Expert Member
Aug 26, 2016
1,787
2,000
Ahsante kwa compliment, ila hili ni jambo la kawaida sana, hata halihitaji expert kulijua. Mtu aliyesoma programming hata kwa wiki mbili tu anaweza kulifanya.
me ndo kama naanza kutambaa kwenye programming lakini i know ntafika soon
 

proxy

JF-Expert Member
Jul 3, 2016
1,190
2,000
Ingia mysql then run hii command
CREATE TABLE IF NOT EXISTS `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(30) NOT NULL, `userEmail` varchar(60) NOT NULL, `userPass` varchar(255) NOT NULL, PRIMARY KEY (`userId`), UNIQUE KEY `userEmail` (`userEmail`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Ukishamaliza nenda kwenye php tengeneza page zifuatazo
–dbconnect.php
–register.php
-index.php
-home.php
-logout.php

Codes for dbconnect.php
<?php // this will avoid mysql_connect() deprecation error. error_reporting( ~E_DEPRECATED & ~E_NOTICE ); // but I strongly suggest you to use PDO or MySQLi. define('DBHOST', 'localhost'); define('DBUSER', 'root'); define('DBPASS', ''); define('DBNAME', 'dbtest'); $conn = mysql_connect(DBHOST,DBUSER,DBPASS); $dbcon = mysql_select_db(DBNAME); if ( !$conn ) { die("Connection failed : " . mysql_error()); } if ( !$dbcon ) { die("Database Connection failed : " . mysql_error()); }

Codes for register.php


User Registration and Login Script with PHP and MySQL

On 1/27/2015 By Pradeep Khodke

In this tutorial we will discuss how to create user registration and login management system with PHP andMySQL in simple procedural way. user registration and login system is most important thing for any kind of web applications and it is common thing too, and session plays important role in this type of system, for that we have to use session, In this tutorial, we are going to use PHP sessions to keep user login status, see the live demo of php mysql login signup script or you can also download this script, and i have updated this script with php server side validations, so how to do login php let’s start.

[https://lh3]



Live Demo

Download Script


read also : Login and Registration with PDO and OOP
read also : Login Script with Email Verification & Forgot Password using PHP
read also : Login and Registration with PHP MySQLi

First of all create a database and table as below.
you can create it by importing following sql command in to your phpmyadmin.
database : dbtest
table : users-- -- Database: `dbtest` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(30) NOT NULL, `userEmail` varchar(60) NOT NULL, `userPass` varchar(255) NOT NULL, PRIMARY KEY (`userId`), UNIQUE KEY `userEmail` (`userEmail`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;copy-paste the above sql code into phpmyqdmin to create database and table.

Now we have to create following files..
–dbconnect.php
–register.php
–index.php
–home.php
–logout.php





Dbconnect.Php

contains code for localhost connection and database selection.
<?php // this will avoid mysql_connect() deprecation error. error_reporting( ~E_DEPRECATED & ~E_NOTICE ); // but I strongly suggest you to use PDO or MySQLi. define('DBHOST', 'localhost'); define('DBUSER', 'root'); define('DBPASS', ''); define('DBNAME', 'dbtest'); $conn = mysql_connect(DBHOST,DBUSER,DBPASS); $dbcon = mysql_select_db(DBNAME); if ( !$conn ) { die("Connection failed : " . mysql_error()); } if ( !$dbcon ) { die("Database Connection failed : " . mysql_error()); }

Register.Php

contains simple html form and few lines of php code.
save this file as ‘register.php‘, this file contains simple html form with all the required registration fields except user id because it’s auto incremented and some php code for registering a new user. all the user registration process can be done in this single php file.
<?php ob_start(); session_start(); if( isset($_SESSION['user'])!="" ){ header("Location: home.php"); } include_once 'dbconnect.php'; $error = false; if ( isset($_POST['btn-signup']) ) { // clean user inputs to prevent sql injections $name = trim($_POST['name']); $name = strip_tags($name); $name = htmlspecialchars($name); $email = trim($_POST['email']); $email = strip_tags($email); $email = htmlspecialchars($email); $pass = trim($_POST['pass']); $pass = strip_tags($pass); $pass = htmlspecialchars($pass); // basic name validation if (empty($name)) { $error = true; $nameError = "Please enter your full name."; } else if (strlen($name) < 3) { $error = true; $nameError = "Name must have atleat 3 characters."; } else if (!preg_match("/^[a-zA-Z ]+$/",$name)) { $error = true; $nameError = "Name must contain alphabets and space."; } //basic email validation if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $error = true; $emailError = "Please enter valid email address."; } else { // check email exist or not $query = "SELECT userEmail FROM users WHERE userEmail='$email'"; $result = mysql_query($query); $count = mysql_num_rows($result); if($count!=0){ $error = true; $emailError = "Provided Email is already in use."; } } // password validation if (empty($pass)){ $error = true; $passError = "Please enter password."; } else if(strlen($pass) < 6) { $error = true; $passError = "Password must have atleast 6 characters."; } // password encrypt using SHA256(); $password = hash('sha256', $pass); // if there's no error, continue to signup if( !$error ) { $query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')"; $res = mysql_query($query); if ($res) { $errTyp = "success"; $errMSG = "Successfully registered, you may login now"; unset($name); unset($email); unset($pass); } else { $errTyp = "danger"; $errMSG = "Something went wrong, try again later..."; } } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Coding Cage - Login & Registration System</title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="container"> <div id="login-form"> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off"> <div class="col-md-12"> <div class="form-group"> <h2 class="">Sign Up.</h2> </div> <div class="form-group"> <hr /> </div> <?php if ( isset($errMSG) ) { ?> <div class="form-group"> <div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>"> <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?> </div> </div> <?php } ?> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span> <input type="text" name="name" class="form-control" placeholder="Enter Name" maxlength="50" value="<?php echo $name ?>" /> </div> <span class="text-danger"><?php echo $nameError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span> <input type="email" name="email" class="form-control" placeholder="Enter Your Email" maxlength="40" value="<?php echo $email ?>" /> </div> <span class="text-danger"><?php echo $emailError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span> <input type="password" name="pass" class="form-control" placeholder="Enter Password" maxlength="15" /> </div> <span class="text-danger"><?php echo $passError; ?></span> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <a href="index.php">Sign in Here...</a> </div> </div> </form> </div> </div> </body> </html> <?php ob_end_flush(); ?>

Baada ya kutengeneza register page sasa inatakiwa utengeneze login/index.php
<?php ob_start(); session_start(); require_once 'dbconnect.php'; // it will never let you open index(login) page if session is set if ( isset($_SESSION['user'])!="" ) { header("Location: home.php"); exit; } $error = false; if( isset($_POST['btn-login']) ) { // prevent sql injections/ clear user invalid inputs $email = trim($_POST['email']); $email = strip_tags($email); $email = htmlspecialchars($email); $pass = trim($_POST['pass']); $pass = strip_tags($pass); $pass = htmlspecialchars($pass); // prevent sql injections / clear user invalid inputs if(empty($email)){ $error = true; $emailError = "Please enter your email address."; } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $error = true; $emailError = "Please enter valid email address."; } if(empty($pass)){ $error = true; $passError = "Please enter your password."; } // if there's no error, continue to login if (!$error) { $password = hash('sha256', $pass); // password hashing using SHA256 $res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'"); $row=mysql_fetch_array($res); $count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row if( $count == 1 && $row['userPass']==$password ) { $_SESSION['user'] = $row['userId']; header("Location: home.php"); } else { $errMSG = "Incorrect Credentials, Try again..."; } } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Coding Cage - Login & Registration System</title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="container"> <div id="login-form"> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off"> <div class="col-md-12"> <div class="form-group"> <h2 class="">Sign In.</h2> </div> <div class="form-group"> <hr /> </div> <?php if ( isset($errMSG) ) { ?> <div class="form-group"> <div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?> </div> </div> <?php } ?> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span> <input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" /> </div> <span class="text-danger"><?php echo $emailError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span> <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" /> </div> <span class="text-danger"><?php echo $passError; ?></span> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <a href="register.php">Sign Up Here...</a> </div> </div> </form> </div> </div> </body> </html> <?php ob_end_flush(); ?>

Home.Php
<?php ob_start(); session_start(); require_once 'dbconnect.php'; // if session is not set this will redirect to login page if( !isset($_SESSION['user']) ) { header("Location: index.php"); exit; } // select loggedin users detail $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']); $userRow=mysql_fetch_array($res); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Welcome - <?php echo $userRow['userEmail']; ?></title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="[HASHTAG]#navbar[/HASHTAG]" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="Coding ">Coding</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="[URL="http://www.pawahost.co.tz[/URL]">Back to Article</a></li> <li><a href="[URL="http://www.pawahost.co.tz[/URL]">jQuery</a></li> <li><a href="[URL="http://www.pawahost.co.tz[/URL]">PHP</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div id="wrapper"> <div class="container"> <div class="page-header"> <h3>Coding Cage - Programming Blog</h3> </div> <div class="row"> <div class="col-lg-12"> <h1>Focuses on PHP, MySQL, Ajax, jQuery, Web Design and more...</h1> </div> </div> </div> </div> <script src="assets/jquery-1.11.3-jquery.min.js"></script> <script src="assets/js/bootstrap.min.js"></script> </body> </html> <?php ob_end_flush(); ?>

Logout.php codes

this page contains only few lines of php code to unset and destroy the current logged in users session, and after destroying the session the page automatically redirect to the ‘index/login’ page.
<?php session_start(); if (!isset($_SESSION['user'])) { header("Location: index.php"); } else if(isset($_SESSION['user'])!="") { header("Location: home.php"); } if (isset($_GET['logout'])) { unset($_SESSION['user']); session_unset(); session_destroy(); header("Location: index.php"); exit; }

Naamini hii itakusaidia vya kutosha ukikwama nicheki kwa namba 0687535650
 

Masiya

JF-Expert Member
Apr 2, 2012
6,953
2,000
Humu nimeingia thieta au chumba cha Marobots?

Sent from Calculator Phone vesion007

mkuu umetisha uko viwango vingine asee

Mkuu mtumie google akusaidie, kama developer google ni kitu cha muhimu sana. Au ujaribu pia kutafuta solution kwanza kabla ya kuuliza. Hiyo simple code nimekuandikia hapo, ungekua umejisumbua hata kidogo kuiandika ungekua ushatambua kua kuna native mysql driver kwenye php, usingerudi kuuliza hili swali.
 

desiigner

JF-Expert Member
Jul 30, 2014
522
250
Ingia mysql then run hii command
CREATE TABLE IF NOT EXISTS `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(30) NOT NULL, `userEmail` varchar(60) NOT NULL, `userPass` varchar(255) NOT NULL, PRIMARY KEY (`userId`), UNIQUE KEY `userEmail` (`userEmail`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Ukishamaliza nenda kwenye php tengeneza page zifuatazo
–dbconnect.php
–register.php
-index.php
-home.php
-logout.php

Codes for dbconnect.php
<?php // this will avoid mysql_connect() deprecation error. error_reporting( ~E_DEPRECATED & ~E_NOTICE ); // but I strongly suggest you to use PDO or MySQLi. define('DBHOST', 'localhost'); define('DBUSER', 'root'); define('DBPASS', ''); define('DBNAME', 'dbtest'); $conn = mysql_connect(DBHOST,DBUSER,DBPASS); $dbcon = mysql_select_db(DBNAME); if ( !$conn ) { die("Connection failed : " . mysql_error()); } if ( !$dbcon ) { die("Database Connection failed : " . mysql_error()); }

Codes for register.php


User Registration and Login Script with PHP and MySQL

On 1/27/2015 By Pradeep Khodke

In this tutorial we will discuss how to create user registration and login management system with PHP andMySQL in simple procedural way. user registration and login system is most important thing for any kind of web applications and it is common thing too, and session plays important role in this type of system, for that we have to use session, In this tutorial, we are going to use PHP sessions to keep user login status, see the live demo of php mysql login signup script or you can also download this script, and i have updated this script with php server side validations, so how to do login php let’s start.

[https://lh3]



Live Demo

Download Script


read also : Login and Registration with PDO and OOP
read also : Login Script with Email Verification & Forgot Password using PHP
read also : Login and Registration with PHP MySQLi

First of all create a database and table as below.
you can create it by importing following sql command in to your phpmyadmin.
database : dbtest
table : users-- -- Database: `dbtest` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(30) NOT NULL, `userEmail` varchar(60) NOT NULL, `userPass` varchar(255) NOT NULL, PRIMARY KEY (`userId`), UNIQUE KEY `userEmail` (`userEmail`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;copy-paste the above sql code into phpmyqdmin to create database and table.

Now we have to create following files..
–dbconnect.php
–register.php
–index.php
–home.php
–logout.php





Dbconnect.Php

contains code for localhost connection and database selection.
<?php // this will avoid mysql_connect() deprecation error. error_reporting( ~E_DEPRECATED & ~E_NOTICE ); // but I strongly suggest you to use PDO or MySQLi. define('DBHOST', 'localhost'); define('DBUSER', 'root'); define('DBPASS', ''); define('DBNAME', 'dbtest'); $conn = mysql_connect(DBHOST,DBUSER,DBPASS); $dbcon = mysql_select_db(DBNAME); if ( !$conn ) { die("Connection failed : " . mysql_error()); } if ( !$dbcon ) { die("Database Connection failed : " . mysql_error()); }

Register.Php

contains simple html form and few lines of php code.
save this file as ‘register.php‘, this file contains simple html form with all the required registration fields except user id because it’s auto incremented and some php code for registering a new user. all the user registration process can be done in this single php file.
<?php ob_start(); session_start(); if( isset($_SESSION['user'])!="" ){ header("Location: home.php"); } include_once 'dbconnect.php'; $error = false; if ( isset($_POST['btn-signup']) ) { // clean user inputs to prevent sql injections $name = trim($_POST['name']); $name = strip_tags($name); $name = htmlspecialchars($name); $email = trim($_POST['email']); $email = strip_tags($email); $email = htmlspecialchars($email); $pass = trim($_POST['pass']); $pass = strip_tags($pass); $pass = htmlspecialchars($pass); // basic name validation if (empty($name)) { $error = true; $nameError = "Please enter your full name."; } else if (strlen($name) < 3) { $error = true; $nameError = "Name must have atleat 3 characters."; } else if (!preg_match("/^[a-zA-Z ]+$/",$name)) { $error = true; $nameError = "Name must contain alphabets and space."; } //basic email validation if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $error = true; $emailError = "Please enter valid email address."; } else { // check email exist or not $query = "SELECT userEmail FROM users WHERE userEmail='$email'"; $result = mysql_query($query); $count = mysql_num_rows($result); if($count!=0){ $error = true; $emailError = "Provided Email is already in use."; } } // password validation if (empty($pass)){ $error = true; $passError = "Please enter password."; } else if(strlen($pass) < 6) { $error = true; $passError = "Password must have atleast 6 characters."; } // password encrypt using SHA256(); $password = hash('sha256', $pass); // if there's no error, continue to signup if( !$error ) { $query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')"; $res = mysql_query($query); if ($res) { $errTyp = "success"; $errMSG = "Successfully registered, you may login now"; unset($name); unset($email); unset($pass); } else { $errTyp = "danger"; $errMSG = "Something went wrong, try again later..."; } } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Coding Cage - Login & Registration System</title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="container"> <div id="login-form"> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off"> <div class="col-md-12"> <div class="form-group"> <h2 class="">Sign Up.</h2> </div> <div class="form-group"> <hr /> </div> <?php if ( isset($errMSG) ) { ?> <div class="form-group"> <div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>"> <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?> </div> </div> <?php } ?> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span> <input type="text" name="name" class="form-control" placeholder="Enter Name" maxlength="50" value="<?php echo $name ?>" /> </div> <span class="text-danger"><?php echo $nameError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span> <input type="email" name="email" class="form-control" placeholder="Enter Your Email" maxlength="40" value="<?php echo $email ?>" /> </div> <span class="text-danger"><?php echo $emailError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span> <input type="password" name="pass" class="form-control" placeholder="Enter Password" maxlength="15" /> </div> <span class="text-danger"><?php echo $passError; ?></span> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <a href="index.php">Sign in Here...</a> </div> </div> </form> </div> </div> </body> </html> <?php ob_end_flush(); ?>

Baada ya kutengeneza register page sasa inatakiwa utengeneze login/index.php
<?php ob_start(); session_start(); require_once 'dbconnect.php'; // it will never let you open index(login) page if session is set if ( isset($_SESSION['user'])!="" ) { header("Location: home.php"); exit; } $error = false; if( isset($_POST['btn-login']) ) { // prevent sql injections/ clear user invalid inputs $email = trim($_POST['email']); $email = strip_tags($email); $email = htmlspecialchars($email); $pass = trim($_POST['pass']); $pass = strip_tags($pass); $pass = htmlspecialchars($pass); // prevent sql injections / clear user invalid inputs if(empty($email)){ $error = true; $emailError = "Please enter your email address."; } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) { $error = true; $emailError = "Please enter valid email address."; } if(empty($pass)){ $error = true; $passError = "Please enter your password."; } // if there's no error, continue to login if (!$error) { $password = hash('sha256', $pass); // password hashing using SHA256 $res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'"); $row=mysql_fetch_array($res); $count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row if( $count == 1 && $row['userPass']==$password ) { $_SESSION['user'] = $row['userId']; header("Location: home.php"); } else { $errMSG = "Incorrect Credentials, Try again..."; } } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Coding Cage - Login & Registration System</title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="container"> <div id="login-form"> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off"> <div class="col-md-12"> <div class="form-group"> <h2 class="">Sign In.</h2> </div> <div class="form-group"> <hr /> </div> <?php if ( isset($errMSG) ) { ?> <div class="form-group"> <div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?> </div> </div> <?php } ?> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span> <input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" /> </div> <span class="text-danger"><?php echo $emailError; ?></span> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span> <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" /> </div> <span class="text-danger"><?php echo $passError; ?></span> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button> </div> <div class="form-group"> <hr /> </div> <div class="form-group"> <a href="register.php">Sign Up Here...</a> </div> </div> </form> </div> </div> </body> </html> <?php ob_end_flush(); ?>

Home.Php
<?php ob_start(); session_start(); require_once 'dbconnect.php'; // if session is not set this will redirect to login page if( !isset($_SESSION['user']) ) { header("Location: index.php"); exit; } // select loggedin users detail $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']); $userRow=mysql_fetch_array($res); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Welcome - <?php echo $userRow['userEmail']; ?></title> <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="[HASHTAG]#navbar[/HASHTAG]" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="Coding ">Coding</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="PAWAHOST – My WordPress Blog[/URL]">Back to Article</a></li> <li><a href="PAWAHOST – My WordPress Blog[/URL]">jQuery</a></li> <li><a href="PAWAHOST – My WordPress Blog[/URL]">PHP</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div id="wrapper"> <div class="container"> <div class="page-header"> <h3>Coding Cage - Programming Blog</h3> </div> <div class="row"> <div class="col-lg-12"> <h1>Focuses on PHP, MySQL, Ajax, jQuery, Web Design and more...</h1> </div> </div> </div> </div> <script src="assets/jquery-1.11.3-jquery.min.js"></script> <script src="assets/js/bootstrap.min.js"></script> </body> </html> <?php ob_end_flush(); ?>

Logout.php codes

this page contains only few lines of php code to unset and destroy the current logged in users session, and after destroying the session the page automatically redirect to the ‘index/login’ page.
<?php session_start(); if (!isset($_SESSION['user'])) { header("Location: index.php"); } else if(isset($_SESSION['user'])!="") { header("Location: home.php"); } if (isset($_GET['logout'])) { unset($_SESSION['user']); session_unset(); session_destroy(); header("Location: index.php"); exit; }

Naamini hii itakusaidia vya kutosha ukikwama nicheki kwa namba 0687535650


mkuu, Ungetumia mysqli badala ya msql. PHP version 7.* haisupport tena mysql, so km jamaa aneomba msaada anatumia latest version ya xampp code hizi hazitosoma kabisa.
 

proxy

JF-Expert Member
Jul 3, 2016
1,190
2,000
mkuu, Ungetumia mysqli badala ya msql. PHP version 7.* haisupport tena mysql, so km jamaa aneomba msaada anatumia latest version ya xampp code hizi hazitosoma kabisa.
Kwenye Linux unaweza kudowngrade php ,anyway akikwama atanijuza.
 

Toa taarifa ya maudhui yasiyofaa!

Kuna taarifa umeiona humu JamiiForums na haifai kubaki mtandaoni?
Fanya hivi...

Umesahau Password au akaunti yako?

Unapata ugumu kuikumbuka akaunti yako? Unakwama kuanzisha akaunti?
Contact us

Similar Discussions

Top Bottom