I have a problem with Phpmyadmin, i just transfered my files to ubuntu because of a coursework
whenever i add a new field to phpmyadmin
it stops adding data
basically, its accepting only one field
and when you check the table data , it gives zero result
below are my codes
<!--This form links the fields to the database as well as allows inseting values to the database-->
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "password", "Pamplemousses_db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$Name = mysqli_real_escape_string($link, $_POST['Name']);
$Surname = mysqli_real_escape_string($link, $_POST['Surname']);
// Attempt insert query execution
$sql = "INSERT INTO Transport (Name,Surname) VALUES ('$Name','$Surname')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($db_connect);
header("location:Transportbooking.php?note=success");
?>
This is my html file
<!DOCTYPE html>
<html>
<head>
<title> Transport Booking | Pamplemousses </title>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<?php include("navigation_bar.html");?>
<?
error_reporting(0);
$note=$_REQUEST['note'];
?>
</head>
<title></title>
<link rel="stylesheet" type="text/css" href="hotels.css" />
</head>
<body>
<div id="page-wrap">
<?PHP if($note=='success')
{
echo "<div class=\"success\">Form successfully submitted!</div>";
}
?>
</div>
<br/>
<form action="transport_process.php" method="post" name="Transport">
<div id="contact-area">
<div class="form-all">
<ul class="form-section page-section">
<li id="cid_1" class="form-input-wide" data-type="control_head">
<div class="form-header-group">
<div class="header-text httal htvam">
<br/>
<h2 id="header_1" class="form-header">
Book Your Transport Here
</h2>
<br/>
</div>
</div>
</li>
<li class="form-line" data-type="control_fullname" id="id_3">
<div id="cid_3" class="form-input jf-required">
<span class="form-sub-label-container" style="vertical-align: top;">
<label class="form-sub-label" for="first_3" id="sublabel_first" style="min-height: 13px;"> Name </label><br/>
<input class="form-textbox" type="text" size="10" name="Name" id="Name" aria-describedby="name-format" required/><br/>
</span>
<span class="form-sub-label-container" style="vertical-align: top;">
<label class="form-sub-label" for="last_3" id="sublabel_last" style="min-height: 13px;"> Lastname </label><br/>
<input class="form-textbox" type="text" size="15" name="Surname" id="Surname" aria-describedby="name-format" required/>
</span>
<input type="submit" value="submit">
</ul>
</div>
</form>
</body>
</html>
Three Fields But only accepting ID and Name:
When i remove everything and include only name, the database store the Name
but the moment i add surname
it stops adding data
Please help
Related
I am trying to create a simple form that will insert the given data received by my HTML form, into my SQL table named 'Vendors', however I am struggling to work with its functionality.
There are 7 text fields that I am wanting to add to my Vendors table, and these are so named:
vendorName
addressL1 (Line 1)
addressL2
postcode
email
telephone
description
The HTML for this form can be found below:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form action="" method="post">
<ul class="form-style-1">
<li>
<label style="color:#4D4D4D;" >Vendor Name <span class="required">*
</span></label>
<center> <input type="text" name="vendorName" class="field-long"
required="required" placeholder="Vendor Name" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Address <span class="required">*
</span></label>
<center> <input type="text" name="addressL1" required="required"
class="field-long" placeholder="Address Line 1" /> </center>
</br>
<center> <input type="text" name="addressL2" required="required"
class="field-long" placeholder="Address Line 2" /> </center>
</br>
<center> <input type="text" name="postcode" required="required"
class="field-short" placeholder="Postcode" /> </center>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Contact Details <span
class="required">*</span></label>
<center> <input type="text" name="email" required="required"
class="field-long" placeholder="Email Address" /> </center>
</br>
<center> <input type="text" name="telephone" required="required"
class="field-long" placeholder="Phone Number" /> </center>
</select>
</li>
<li>
<label style="color:#4D4D4D;">Vendor Description </label>
<center> <textarea name="description" id="field5" class="field-long
field-textarea" placeholder="Description"></textarea> </center>
</li>
<li>
<center> <input type="submit" class="AddButton" value="POST"></input>
</center>
</li>
</ul>
</form>
</body>
</html>
And the PHP I have used is:
<?php
date_default_timezone_set('Europe/London');
$server = "";
$connectionInfo = array( "Database"=>"");
$conn = sqlsrv_connect($server,$connectionInfo);
if (!$conn)
{
die("Connection failed");
}
$_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$VendorName = $_POST['vendorName'];
$AddressLine1 = $_POST['addressL1'];
$AddressLine2 = $_POST['addressL2'];
$Postcode = $_POST['postcode'];
$VendorEmail = $_POST['email'];
$VendorNumber = $_POST['telephone'];
$VendorDes = $_POST['description'];
$time = time();
$timestamp = date("Y-m-d H:i:s", $time);
$describeQuery = ("INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ('".$VendorName."', '".$AddressLine1."',
'".$AddressLine2."', '".$Postcode."',
'".$VendorEmail."', '".$VendorNumber."',
'".$VendorDes."', '".$timestamp."')");
$results = sqlsrv_query($conn, $describeQuery);
if(sqlsrv_query($conn, $describeQuery))
{
$alert = "Vendor Successfully Added";
echo "<script type='text/javascript'>alert('$alert');
</script>";
}
else
{
echo 'Information not inserted';
}
}
sqlsrv_close($conn);
?>
Each time I submit the form, it goes straight to the 'Information not inserted' ELSE statement and doesn't import the data into my database.
I have removed my server name and database name for precautionary reasons, however I can assure you they are correct as I have worked on a previous project and used the same method of connecting.
Any help on this would be greatly appreciated, and if there are any formatting mistakes, apologies in advance, I am not an avid user of stack overflow.
Use Mysqli Please, I have updated the script.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Vendors (VendorName, VendorAL1,
VendorAL2, VendorPost, VendorEmail, VendorNumber, VendorDes,
Added)
VALUES ($VendorName, $AddressLine1, $AddressLine2,$Postcode,$VendorEmail,$VendorNumber,$VendorDes,$timestamp)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Hi I'm having some problems when I'm trying to submit a form of mine, everything seems to look fine on my end but im not quite sure why it's still not working any help would be appreciated.
config.php
<?php
$servername = "localhost";
$username = "release";
$password = "";
$dbname = "release";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
submit.php
<?php
include('config.php');
$producers = $_POST['producers'];
$company = $_POST['company'];
$title = $_POST['title'];
if(!$producers or !$company or !$title) {
echo 'Please make sure to fill out all required feilds.';
} else {
// Insert into DB
$sql = "INSERT INTO release (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
}
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}$con->close();
?>
index.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style>
input[type="text"] {
height: 30px;
}
</style>
<title>RRP ยป Welcome!</title>
</head>
<body>
<div style="width: 1080px; margin-top: 50px;">
<h3>Welcome!</h3>
<h4>You can edit the basic release form info below. <br /> Once done hit the "Submit" button to carry on to the new form!</h4>
<div class="container">
<form class="contact-us form-horizontal" action="submit.php" method="post">
<div class="control-group">
<label class="control-label">Producers</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" name="producers" placeholder="Producers(seperate by commas)">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Production Company</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-globe"></i></span>
<input type="text" class="input-xlarge" name="company" placeholder="Rolling Ridges Productions">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Title</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-pencil"></i></span>
<input type="text" class="input-xlarge" name="title" placeholder="Desperate Measures">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
</body>
</html>
error
Error: INSERT INTO release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')' at line 1
Resolved: was as simple as adding ticks to release
release is a MySQL keyword, and should be enclosed in backticks: `release`
try to use backticks in table name if it is keyword release
$sql = "INSERT INTO `release` (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
Also it is better to write your database in the following format
database name -> db_name eg db_release, and
table name -> tb_name eg tb_release
so as to avoid keywords errors
It seems to me that id should not be assigned the string value 'null'. Typically id columns are auto increment, in which case you should simply omit the column:
$sql = "INSERT INTO `release` (producers, company, title)
VALUES ('".addslashes($producers)."', '".addslashes($company)."', '".addslashes($title)."'";
The addslashes is to protect again SQL injection. You should also sanitize your inputs:
$producers = strval($_POST['producers']);
$company = strval($_POST['company']);
$title = strval($_POST['title']);
I am trying to create a registration and login page by using PHP to connect to MYSQL database and insert the information into the tables. Unfortunately I am able to connect to the database with no problems, and it connects to the table. When I process the information by submitting it via the HTML form, it says that an entry has been added but the MYSQL database has a blank entry. I will post the HTML and PHP below. Thank you for all your help.
<HTML>
<HEAD>
<TITLE> Programming </TITLE>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<LINK REL="stylesheet" TYPE="text/css" href="homework2.css">
</HEAD>
<BODY>
<!-- CSS for http://the7.dream-demo.com/ -->
<div id="container">
<div id="header">
<div class="menuitem"> Home </div>
<div class="menuitem">Products</div>
<div class="menuitem">Case Studies</div>
<div class="menuitem">Pricing</div>
<div class="menuitem">About Us</div>
</div>
<div id="bodycontent">
<div id="banner">
<div id="bannerleft"> <h1> We make you better athletes. Find out how! </h1> </div>
<div id="signin">
<form class="well form-inline" action="login.php" method="post">
<input type="text" class="input-small" placeholder="Email" name="email" >
<input type="password" class="input-small" placeholder="Password" name="password">
<br><br>
<!--
If you do not want to use twitter bootstrap css then you should uncomment next 6 lines and uncomment the
above 2 lines that provide input boxes
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<br>
-->
<input type="submit" name="submit" id="logmein" value="Log In">
</form>
</div>
</div>
<div id="featurestrip">
<div id="signup">
<form action="signup.php" method="post">
<label for="user_name">Firstname:</label>
<input type="text" name="signup-FirstName" id="signup-FirstName">
<br>
<label for="user_pass">Password:</label>
<input type="password" name="signup-Password" id="signup-Password">
<br><br>
<label for="user_email">Email: </label>
<input type="text" name="signup-email" id="signup-email">
<br>
<input type="submit" name="signmeup" id="signmeup" value="Sign Me Up!">
</form>
</div>
<div id="featureright"> <p>Sign up and find out more on how we can help. Pricing starts at $19.95 a month. </p>
<p><h3>Premium service starts at $49.95.</h3></p>
</div>
</div>
<div id="corefeatures">
<img height="200px" src="http://www.hockeymanitoba.ca/wp-content/uploads/2013/02/ltad-model.jpg">
</div>
<div id="testimonials"> Testimonial
<img height="200px" src="http://www.neuroexplosion.com/storage/development%20model%20jpeg.jpg?__SQUARESPACE_CACHEVERSION=1305662626397">
<img height="200px" src="http://www.phecanada.ca/sites/default/files/physical_literacy/LTAD_FMS.jpg">
</div>
<!--
<div id="portfolio"> Portfolio</div>
<div id="skills"> Skills</div>
-->
</div>
<div id="footer">Copyright Notice. All Rights Reserved. 2014</div>
</div>
</BODY>
</HTML>
PHP
PHP CODE BELOW
<?php
echo "<TR>";
echo "<TD>";
$dyn_user_name = $_POST['user_name'];
echo $dyn_user_name;
echo "</TD>";
echo "<TD>";
$dyn_user_pass = $_POST['user_pass'];
echo $dyn_user_pass;
echo "</TD>";
echo "<TD>";
$dyn_user_email= $_POST['user_email'];
echo $dyn_user_email;
echo "</TD>";
echo "</TR>";
///This is for connecting to the database
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'users_db2015';
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die ("Couldn't connect");
echo "Connection Successful";
//to put data into database
//select database
$db_selected = mysql_select_db($mysql_database, $connect)
or die ("Couldn't connect to the database");
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
echo "<BR>Selected the database " . $mysql_database;
//create sql query for data insertion
$insert_sql = "INSERT INTO users1 (user_name, user_pass, user_email)
values ('$dyn_user_name', '$dyn_user_pass', '$dyn_user_email')";
$insert_result = mysql_query($insert_sql);
//if successful, add another row, if not, then don't
if ($insert_result){
echo "<BR> 1 record added";
}
else{
echo "<BR> Couldn't add the information";
}
//Display data in the database (run a query in mysql to retrieve data)
//prepare query
$get_data_sql = "SELECT * FROM users1";
//run query
$result= mysql_query($get_data_sql);
//get numbner of rows in the result
$num_rows = mysql_num_rows($result);
//loop through result
$q=0;
while ($q < $num_rows){
//takes results and gives you the first row, which is
//stored as a hashtable
//takes row and represents as key value pair, keep on using the value pair
//as the keys
$new_row= mysql_fetch_array($result);
//look into firstname and retrieve what's in that row, so it will return a name
//do this same this for the score
echo $row_user_name = $new_row['user_name'];
echo $row_user_pass = $new_row['user_pass'];
echo $row_user_email = $new_row['user_email'];
echo "<TR>";
echo "<TD>";
echo $row_user_name;
echo "</TD>";
echo "<TD>";
echo $row_user_pass;
echo "</TD>";
echo "<TD>";
echo $row_user_email;
echo "</TD>";
echo "</TR>";
$q=$q+1;
}
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm only just beginning to learn how to program, and most of this code isn't original they are from tutorials and stuff. I am using it to learn how it all goes together.
I've been having trouble with implementing the php and mysql scripts into the main HTML page.
** Ive been using WAMP
This is the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and
media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.box{
background-color: #d3d3d3;
border: 1px solid grey;
}
</style>
</head>
<body>
<div class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
Insanity and Calamity
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Andrew</li>
<li>Tommy</li>
<li>Jayme</li>
</ul>
<ul class="nav pull-right">
<li>Sign Up</li>
<li class="divider-vertical"></li>
<li class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
<form action="login.php" method="post" accept-charset="UTF-8">
<input id="user_username" style="margin-bottom: 15px;" type="text" name="user[username]" size="30" />
<input id="user_password" style="margin-bottom: 15px;" type="password" name="user[password]" size="30" />
<input id="user_remember_me" style="float: left; margin-right: 10px;" type="checkbox" name="user[remember_me]" value="1" />
<label class="string optional" for="user_remember_me"> Remember me</label>
<input class="btn btn-primary" style="clear: left; width: 100%; height: 32px; font-size: 13px;" type="submit" name="commit" value="Sign In" />
</form>
</div>
</li>
</ul>
</div>
</div>
</div>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6 box">Holy cow</div>
<div class="col-md-6 box">Holy cow</div>
</div>
<div class="row">
<div class="col-md-4 box">Holy cow is super cool</div>
<div class="col-md-4 box">Holy cow is super cool</div>
<div class="col-md-4 box">Holy cow is super cool</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
the login.php
<html>
<head>
<title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
</body>
</html>
Register.php
<html>
<head>
<title>User registration form- PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User registration form- PHP MySQL Ligin System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="first_name" /><br />
Last name: <input type="text" name="last_name" /><br />
Email: <input type="type" name="email" /><br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
#prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`)
VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>
</body>
</html>
DB_const.php
<?php
# mysql db constants
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'php_mysql_login_system';
?>
Taking your code, and focusing on the SESSION, hashed passwords, db. And not the few lines of getting mysqli bindings with parameters for now, or css, etc, I leave you with the following:
index.php
<?php
session_start(); // Start or resume the session
if ($_POST['logout_yeehaw'])
{ // form has been submitted to self from Logout button
$_SESSION['proceed']=0; // bye bye, pseudo logout (true, you could kill all at once, please forgive)
$_SESSION['userId']=-1;
$_SESSION['fn']="";
else
{
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-2.1.4.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
.box{
background-color: #d3d3d3;
border: 1px solid grey;
}
</style>
</head>
<body>
<?php
include "showLoginStatus.php";
?>
<div class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
Insanity and Calamity
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Andrew</li>
<li>Tommy</li>
<li>Jayme</li>
</ul>
<ul class="nav pull-right">
<li>Register</li>
<li class="divider-vertical"></li>
<li>Login</li>
</ul>
</div>
</div>
</div>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6 box">Holy cow cool</div>
<div class="col-md-6 box">Holy cow cool</div>
</div>
<div class="row">
<div class="col-md-4 box">Holy super cool</div>
<div class="col-md-4 box">Holy super cool</div>
</div>
</div>
</body>
</html>
login.php
<?php
session_start(); // Start or resume the session
$bailOutGoHome = '<script type="text/javascript">';
$bailOutGoHome .= 'window.location = "'. "index.php".'"';
$bailOutGoHome .= '</script>';
$_SESSION['proceed']=0; // bye bye, pseudo logout (true, you could kill all at once, please forgive)
$_SESSION['userId']=-1;
$_SESSION['fn']="";
?>
<html>
<head>
<title>User Login Form - PHP MySQL Login System | W3Epic.com</title>
</head>
<body>
<a href="index.php" >Home</a>
<h1>User Login Form - PHP MySQL Login System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<div style="background-color: #EDB495">You have just been logged out if you were logged in.</div>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
// no way man, we don't LIKE the next line at all !
//$sql = "SELECT userId,email from appusers WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$sql = "SELECT userId,email,password as dbhashxxx,first_name,last_name from appusers WHERE username ='{$username}' LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows == 1) {
echo "1";
$row = $result->fetch_array();
$dbHash=$row['dbhashxxx'];
if (password_verify($password, $dbHash)) {
// password is valid, set some session stuff and leave to index.php
$_SESSION['proceed']=1;
$_SESSION['userId']=$row['userId'];
$_SESSION['fn']=$row['first_name'] ." ". $row['last_name'];
echo $bailOutGoHome; // go home (index.php) avoids "headers already sent error"
}
}
// leave them stranded here, to slow down their robot
echo "<p>Invalid username/password combination. You are evil, now go away.</p>";
}
?>
</body>
</html>
register.php
<html>
<head>
<title>User registration form- PHP MySQL Login System | W3Epic.com</title>
</head>
<body>
<a href="index.php" >Home</a>
<h1>User registration form- PHP MySQL Login System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="first_name" /><br />
Last name: <input type="text" name="last_name" /><br />
Email: <input type="type" name="email" /><br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
#prepare data for insertion
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from appusers WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT email from appusers WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT email from appusers WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
// see http://php.net/manual/en/function.password-hash.php
$options = [
'cost' => 12, // let's splurge
];
$hash = password_hash($password, PASSWORD_BCRYPT, $options); // change to suit your concerns
# insert data into mysql database
# let the DB do the autoincrement of userId, don't pass NULL as 1st parameter
$sql = "INSERT INTO `appusers` (`username`, `password`, `first_name`, `last_name`, `email`)
VALUES ('{$username}', '{$hash}', '{$first_name}', '{$last_name}', '{$email}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registered successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>
</body>
</html>
showLoginStatus.php
<?php
if ($_SESSION['proceed']==1) {
echo "<div style=\"background-color: #A2ED95\">";
echo "You are logged in. Welcome ".$_SESSION['fn'].", userId=".$_SESSION['userId'];
echo "<form method=post action=\"". $_SERVER['PHP_SELF'] ."\">";
echo "<input type=hidden name=logout_yeehaw value=1>";
echo "<input type='submit' name='logout' value='Logout' />";
echo "</form></div>";
}
else
echo "<div style=\"background-color: #EDB495\">You are not logged in.</div>";
db_const.php
<?php
# mysql db constants
const DB_HOST = 'localhost';
const DB_USER = 'dbuser1';
const DB_PASS = 'newpassword';
const DB_NAME = 'login_system';
?>
random db stuff:
create database login_system;
use login_system;
-- drop table appusers;
create table appusers
( -- does not care about saving user SALT
-- remember that the cleartext password, the cost, and SALT are ALL baked into hash
-- so as far as I am concerned, the SALT is a throw-away, after user one-time gen of it
userId int auto_increment primary key,
username varchar(20) not null,
password varchar(255) not null, -- the hash, maybe blowfish, maybe not, look at code
first_name varchar(50) not null,
last_name varchar(50) not null,
email varchar(100) not null
);
-- truncate table appusers;
-- note : despite the below, cleartext passwords will not be used
insert appusers(username,password,first_name,last_name,email) values ('andrew','cleartext','andrew','smith','andrew#gmail.com');
select * from appusers;
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+
| userId | username | password | first_name | last_name | email |
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+
| 1 | user1 | $2y$11$mp34MpHbhAcbN5YVlUBh4eTv0HMxuJJbvWhFKdtfkMDyhJpwnBCpG | Fred | Gibbons | f#g.com |
| 2 | user2 | $2y$11$8dkjzLghFqU4nXSPPFdsa.nLvlw.EvdgxvYe5FbGsB7mx4BBRAqwy | Kelly | Hartshorne | kelly#gmail.com |
| 3 | user3 | $2y$12$rk66cxOSRLUjIDKVU2EFq.Zz8T06qdEuzC4i3lKAi84IpGSKcGV8. | joe | schmoe | j |
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+
create user 'dbuser1'#'localhost' identified by 'newpassword';
select user,host,password from mysql.user where user='dbuser1';
+---------+-----------+-------------------------------------------+
| user | host | password |
+---------+-----------+-------------------------------------------+
| dbuser1 | localhost | *Fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
+---------+-----------+-------------------------------------------+
grant all on login_system.* to 'dbuser1'#'localhost';
I am going crazy trying to learn how to use sessions to store values of custom fields in my registration_form.php so I can call the data on other pages. I have read all sorts of websites but nobody seems to explain where exactly I am supposed to put the code to capture the data. I have two custom registration fields I added to a script (bio and displayname). I tried inserting this code on the registration form at the top and bottom and also on a register.php (both scripts below).
Where does the code go to store these fields to a session? I know it is wrong below because at this point I have tried placing it everywhere in everyway I can....
//registration_form.php
<?php session_start();
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
$author = $_SESSION['displayname'];
$bio = $_SESSION['bio'];
?>
<HTML>
<head>
<title>Practice</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/style.css" rel="stylesheet" media="screen">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<div class="logo">
<h2><?php include('db.php'); echo $logotxt; ?></h2>
</div>
<form class="form-horizontal" id="register_form" method="post">
<h2>Register</h2>
<div class="line"></div>
<div class="control-group">
<input type="text" id="inputEmail" name="email" placeholder="Email">
</div>
<div class="control-group">
<input type="text" id="inputuserid" name="username" placeholder="Username">
</div>
<div class="control-group">
<input type="text" id="displayname" name="displayname" placeholder="Display name">
</div>
<div class="control-group">
<textarea name="bio" class="textfield" id="bio" cols="25" rows="7" placeholder="Bio
(optional). Tell us about yourself."></textarea>
</div>
<button type="submit" class="btn btn-large btn-primary btn-sign-in" data-loading-
text="Loading...">Register</button>
Sign in
<div class="messagebox">
<div id="alert-message"></div>
</div>
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
}
?>
//register.php
<?php
include("db.php");
$con=mysql_connect($server, $db_user, $db_pwd) //connect to the database server
or die ("Could not connect to mysql because ".mysql_error());
mysql_select_db($db_name) //select the database
or die ("Could not select to mysql because ".mysql_error());
//prevent sql injection
$username=mysql_real_escape_string($_POST["username"]);
$displayname=mysql_real_escape_string($_POST["displayname"]);
$password=mysql_real_escape_string($_POST["password"]);
$email=mysql_real_escape_string($_POST["email"]);
$bio=mysql_real_escape_string($_POST["bio"]);
//check if user exist already
$query="select * from ".$table_name." where username='$username'";
$result=mysql_query($query,$con) or die('error');
if (mysql_num_rows($result))
{
die($msg_reg_user);
}
//check if user exist already
$query="select * from ".$table_name." where email='$email'";
$result=mysql_query($query,$con) or die('error');
if (mysql_num_rows($result))
{
die($msg_reg_email);
}
session_start();
$_SESSION['displayname'] = $displayname;
$_SESSION['bio'] = $bio;
$activ_key = sha1(mt_rand(10000,2222).time().$email);
$hashed_password = crypt($password);
$query="insert into ".$table_name."(username,displayname,password,email,activ_key,bio)
values ('$username','$displayname','$hashed_password','$email','$activ_key','$bio')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error());
}
I am not sure what you are trying to here but should not your form action in regisration_form.php be set to register.php?
<form class="form-horizontal" id="register_form" method="post" action="register.php">
Then you form will be submitted to register.php. The way you have set up Session in register.php is basically correct. To access the session value in other pages do:
$displayname= $_SESSION['displayname'];
$bio=$_SESSION['bio'];