I´m having trouble creating data onto a MySQL database via a php that I created in order to be able to create an account on a website I´m making I have the following php files that take care of the process (linked below), I have been looking to these lines of code for hours and I'm not able to figure out what is wrong with it ....
signup.php
<?php
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>AlojArt Reservas</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- styles -->
<link href="css/styles.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require 'login.php';
}
elseif (isset($_POST['register'])) { //user registering
require 'register.php';
}
}
?>
<body class="login-bg">
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-------------------- Logo -------------------->
<div class="logo">
<h1>AlojArt Reservas</h1>
</div>
</div>
</div>
</div>
</div>
<div class="page-content container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-wrapper">
<div id="register">
<div class="box">
<form action="signup.php" method="post" autocomplete="off">
<div class="content-wrap">
<h6>Criar conta</h6>
<input class="form-control" type="text" placeholder="Nome" name="nome_titular">
<input class="form-control" type="text" placeholder="Nome de utilizador " name="username">
<input class="form-control" type="password" placeholder="Palavra-passe" name="password">
<input class="form-control" type="email" placeholder="Endereço de e-mail" name="email">
<div class="action">
<button class="btn btn-primary btn-lg" name="register" />Criar conta</button>
</div>
</div>
</form>
</div>
</div>
<div class="already">
<div id="login">
<p>Já tem conta?</p>
Iniciar sessão
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>
register.php
<?php
require 'db.php';
session_start();
$_SESSION['nome_titular'] = $_POST['nome_titular'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['email'] = $_POST['email'];
// Escape all $_POST variables to protect against SQL injections
$nome_titular = $mysqli->escape_string($_POST['nome_titular']);
$username = $mysqli->escape_string($_POST['username']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM Utilizador WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'O utilizador jรก existe!';
header("location: error.php");
}
else { // User doesn't already exist in a database, proceed...
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. "VALUES ('$nome_titular','$username','$email','$password')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true;
header("location: dashboard.php");
}
else {
$_SESSION['message'] = "O registo falhou!";
header("location: error.php");
}
}
?>
EDIT: added db.php
db.php
<?php
/* Database connection settings */
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
I see there is no space ' ' before VALUES, this would cause failure of SQL.
Change your SQL to
$sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
. " VALUES ('$nome_titular','$username','$email','$password')";
If you still getting unexpected result, then please put following code to else get the error and comment out everything else.
printf("Error: %s\n", $mysqli->error);
==Update==
"Error: Duplicate entry '0' for key 'PRIMARY"
It refers to primary key constraint violation, in other word, you are trying to insert new value 0, which is already present in same column. Since, primary key doesn't allow duplicate. It is failing and falling to else block. To correct this issue, you need to make sure, you don't have duplicate entry for column which has primary key.
I see there is no connection for your page thats why it gets redirected to error.php change your db connection to this
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$con = mysqli_connect("$host,$user,$pass,$db") or die($mysqli->error);
mysqli_select_db($con,"your db name");
?>
in the form change button
<button type="submit" class="btn btn-primary btn-lg" name="register" />Criar conta
ALTER TABLE Your table name
ADD PRIMARY KEY (ID);
Related
Practising PHP by creating a very simple page that has a picture and the user can comment on it. I pretty much have everything down except adding the comment to the table within the database. I have it so I get an alert when the comment either gets added to the table or it does not go through. As far as I can tell, the code looks good but I could be wrong.
Here is the PHP file with the config info
<?php
$servername = "localhost";
$user = "user1";
$password = "";
$dbname = "comment_section";
//Create connection to database
$conn = mysqli_connect($servername, $user, $password, $dbname);
if(!conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE comment_list (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nid VARCHAR(128) NOT NULL,
comments TEXT NOT NULL,
date datetime NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table comment_list created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
And here is my index file
<?php
include 'comments.php';
error_reporting(0);
if (isset($_POST['submit'])) {
$name = $_POST['nid'];
$comment = $_POST['comments'];
$sql = "INSERT INTO comment_list (nid, comments)
VALUES ('$name', '$comment')";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "<script>alert('Comment added')</script>";
} else {
echo "<script>alert('Comment not added')</script>";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<!-- CSS, JS, and PHP files goes here -->
<link rel="stylesheet" href="style.css">
<!-- javascript code goes here -->
<!-- end of js code -->
</head>
<body>
<!-- Intro to what the site is about, possible pages to include comments -->
<header>
<h1></h1>
<nav>
<ul>
</ul>
</nav>
</header>
<!-- Image with comment section -->
<article>
<img src="images/IMG_1560.JPG" alt="" ">
<div class="wrapper">
<form action="" method="POST" class="form">
<div class="name">
<label for="name">Name</label>
<input type="text" name="nid" id="nid" placeholder="Name" required>
</div> <!-- End div class name -->
<div class="comment">
<label for="comment">Comment</label>
<textarea name="comments" id="comments" placeholder="Comment" required></textarea>
</div> <!-- End of div for textarea -->
<div class="but">
<button name="submit" class="btn">Post Comment</button>
</div>
</form>
<?php
$sql = "SELECT * FROM comment_list";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<?php echo $row['nid']; ?>
<p><?php echo $row['comments']; ?></p>
<?php
}
}
?>
</div>
</article>
<footer>
<p></p>
</footer>
</body>
</html>
Now every time I try to test and click on the submit button. I get an alert and the Comment Not Added pops up. Am I missing something? I also want it to show under the form whenever a user has left a comment. I know I can use Ajax without having to refresh the page, but I at least want to get the comment into the db/table and displayed under the form.
This question already has answers here:
PHP isset $_session equal to string
(1 answer)
How to use store and use session variables across pages?
(8 answers)
Closed 2 years ago.
I'm working on a login page using PHP with the intent of the page to take the user to landing page. There is a database set up with all the form fields populated and I set up test code to verify if the fields were being pulled properly and they were. But when the login website itself is being used, it redirects to itself no matter what the fields are filled with and wipes the fields clean. I've tried several different things with how the page was being called but still cannot get it to do anything other than wipe the fields clean and redirect to a clean version of itself. Here is the relevant code
<?php
session_start();
include 'config.php';
if(isset($_SESSION['user'])!="" && isset($_SESSION['store'])!=""){
header('Location: http://server-ip/landing.php');
exit();
}
$error = false;
if($_SERVER["REQUEST_METHOD"] == "POST" && ($_POST['btn-login'])){
$storeid = $_POST['Store'];//grabs store someone is logging in to
$userid = trim($_POST['userID']); //grabs user ID, sql injection cleaning
$userid = strip_tags($userid);
$userid = htmlspecialchars($userid);
$pass = trim($_POST['passhash']); //grabs the user password, sql injection cleaning
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
if(empty($storeid)){
$error = true;
$storeError = "Please select a store.";
}
if(empty($userid)){
$error = true;
$useridError = "Please enter your User ID.";
} else if (!filter_var($userid, FILTER_VALIDATE_INT)){
$error = true;
$useridError = "Please enter a valid User ID.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
//if no errors, continue
if(!$error){
$password = hash('sha256', $pass);
$res=mysqli_query($conn,"SELECT userID, passhash FROM User WHERE userID='$userid'");
$row = mysqli_fetch_array($res);
$count = mysqli_num_rows($res); //if userID and password are correct 1 row should be returned.
$sres=mysqli_query($conn,"SELECT storeID FROM Store WHERE storeID='$storeid'");
$srow = mysqli_fetch_array($sres);
if( $count == 1 && $row['password']==$password){
$_SESSION['user'] = $row['userID'];
$_SESSION['store'] = $srow['storeID'];
$_SESSION["loggedin"] = true;
header('Location: http://http://server-ip/landing.php');
exit();
} else{
$errMSG = "The userID or Password you entered was incorrect. Please try again.";
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<title>PIMSHOE Login</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid jumbotron text-center bg-primary text-white" style="margin-bottom:0">
<h1>PIMSHOE Admin</h1>
</div>
<?php if(isset($useridError) || isset($errMSG) ||isset($storeError) || isset($passError)) { ?>
<div role="alert" class="alert alert-danger text-center">
<?php
if(isset($useridError)) { echo $Error; }
if(isset($passError)) { echo $passError; }
if(isset($errMSG)) { echo $errMSG; }
if (isset($storeError)) { echo $storeError; }
?>
</div>
<?php } ?>
<div class="row mt-5">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<h2 class="text-center mb-4 mt-1">Sign in</h2>
<form id="loginform" class="form-horizontal" role="form" method="post" action="landing.php" accept-charset='UTF-8'>
<div class="form-group">
<label for="store"></label>
<?php
echo('<select class="form-control" id="store">
<option>Select Store</option>');
$sqli = "SELECT StoreID FROM Store";
$result = mysqli_query($conn, $sqli);
while($row = mysqli_fetch_array($result)){
echo('<option>'.$row['StoreID'].'</option>');
}
echo('</select>');
?>
</select>
</div>
<hr>
<div class="form-group">
<input type="text" name="user_name" class="form-control" maxlength="4" pattern="^[0-9]{4}" id="userID" placeholder="User ID">
</div>
<div class="form-group">
<input type="password" name="user_pass" class="form-control" id="password" placeholder="*********">
</div>
<div class="form-group">
<button id="btn-login" name="btn-login" type="submit" class="btn btn-primary btn-block bg-primary"> Login </button>
</div>
</form>
<!--Sign up Admins insert new users, maybe have it go to a form that sends a request email to an admin?-->
<p class="underlineHover">Forgot password?</p>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
I think the problem is with your first if statement.
The function isset returns a boolean (true or false) and you are comparing its return with "". You could write the statement in one of the two ways:
if(isset($_SESSION['user']) && isset($_SESSION['store'])){
or
if($_SESSION['user']!="" && $_SESSION['store']!=""){
I'm using PHP web service for my android development back end. The connection with php and MSSQL Server are successful but unfortunately I stuck at this part:
<?php
session_start();
include "connect.php";
$user_name = $_POST["username"];
$user_pass = strval($_POST["password"]);
//echo $user_name;
//echo $user_pass;
//$user_name = "admin";
//$user_pass = "admin";
$mysql_qry="SELECT ID, Password FROM user WHERE (ID = '" . $_POST["username"] . "' AND Password = '" . $_POST["password"] . "')";
$result= sqlsrv_query($conn ,$mysql_qry);
$row = sqlsrv_fetch_array($result);
if($row) {
$_SESSION["ID"] = $row['ID'];
header ('location:../createUser.php');
}else{
die( print_r( sqlsrv_errors(), true));
}
?>
It shows error: An invalid parameter was passed to sqlsrv_fetch_array.
This is my login form:
<!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, shrink-to-fit=no"
/>
<meta name="description" content="" />
<meta name="author" content="" />
<title>Login</title>
<!-- Custom fonts for this template-->
<link
href="vendor/fontawesome-free/css/all.min.css"
rel="stylesheet"
type="text/css"
/>
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet"
/>
<!-- Custom styles for this template-->
<link href="css/sb-admin-2.min.css" rel="stylesheet" />
</head>
<body class="bg-gradient-primary">
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<img class="col-lg-6 d-none d-lg-block " src="img/Login.png">
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">
Welcome To DEMO 1
</h1>
</div>
<form class="user" method="POST" action="php/login.php">
<div class="form-group">
<input
type="text"
name="username"
class="form-control form-control-user"
id="exampleInputEmail"
aria-describedby="emailHelp"
placeholder="Enter Username..."
/>
</div>
<div class="form-group">
<input
type="password"
name="password"
class="form-control form-control-user"
id="exampleInputPassword"
placeholder="Password"
/>
</div>
<button
class="btn btn-primary btn-user btn-block"
type="submit"
>
Login
</button>
</form>
<hr />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
</body>
</html>
I already check on the parameter and everything looks just fine. Why is the error keep occur?
I think you need one parameter in
$row = sqlsrv_fetch_array($result);
So , change to
$row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Or , edit your query
$mysql_qry="SELECT ID, Password FROM user WHERE ID = '$user_name' AND Password = '$user_pass' ";
Consdier the following:
One possible explanation for your error is that you are concatenating user input to build the SQL statement. In fact, you are injecting your code. Never do this, always use prepared statements and parameterized queries to prevent SQL injection. With PHP Driver for SQL Server, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
You need to hash the passowrd, because at the moment you are passing the password as plain text. When the password is hashed, you may safely pass it to the database.
Check the result from sqlsrv_query() execution.
As a note, you may use sqlsrv_has_rows() function to check if the result set has one or more rows.
The next example, based on your code, may help to get your expected results:
<?php
session_start();
include "connect.php";
$user_name = $_POST["username"];
$user_pass = strval($_POST["password"]);
$mysql_qry = "
SELECT ID, Password
FROM user
WHERE ID = ? AND Password = ?
";
$params = array($user_name, $user_pass);
$result = sqlsrv_query($conn, $mysql_qry, $params);
if ($result === false) (
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
)
if (sqlsrv_has_rows($result)) {
// You don't even need to fetch the record, just use:
// $_SESSION["ID"] = $user_name;
// header ('location:../createUser.php');
$row = sqlsrv_fetch_array($result);
if ($row === false) {
echo "Error (sqlsrv_fetch_array): ".print_r(sqlsrv_errors(), true);
exit;
}
$_SESSION["ID"] = $row['ID'];
header ('location:../createUser.php');
} else {
echo "User not found";
exit;
}
?>
My code below doesn't go to if ( $loginsuccess == 1 ). Everytime i try logging in it directs me to the else{ part of my code.
<?PHP
session_start();
$userid = $_POST['userid'];
$password = $_POST['password'];
$loginsuccess = 0;
$con = mysqli_connect('localhost', 'root');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con, 'btr');
$result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");
while($row = mysqli_fetch_array($result))
{
if ( $row['password'] == $password ){
$loginsuccess = 1;
}
}
mysqli_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
<script type="text/javascript">
<!--
function redirect_index(){
window.location = "menu.php"
}
function redirect_login(){
window.location = "login.php"
}
//-->
</script>
<title>Test</title>
</head>
<body>
<?PHP
if ( $loginsuccess == 1 ){
$_SESSION['userid'] = $userid;
?>
<div data-role="page" class="login">
<script type="text/javascript">
$('.login').live("pagecreate", function() {
setTimeout("redirect_index();", 3000);
});
</script>
<div data-role="header">
<h1>
Test
</h1>
</div>
<div data-role="content">
Login successful. You will be redirected to main page in 3 seconds...<br />
Back
</div>
<div data-role="footer">
Test
</div>
</div>
<?PHP
} else{
unset($_SESSION['userid']);
?>
<div data-role="page" class="login">
<script type="text/javascript">
$('.login').live("pagecreate", function() {
setTimeout("redirect_login();", 3000);
});
</script>
<div data-role="header">
<h1>
Test
</h1>
</div>
<div data-role="content">
Invalid id or password. You will be redirected to login page in 3 seconds...<br />
Login
</div>
<div data-role="footer">
Test
</div>
</div>
<?PHP
}
?>
</body>
</html>
could it be the data pass from the previous page ?
<?PHP
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
<!--
function redirect_index(){
window.location = "menu.php"
}
function redirect_login(){
window.location = "login.php"
}
//-->
</script>
<title>/title>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>
Login
</h1>
</div>
<div data-role="content">
<form method="post" action="login_script.php">
<div data-role="fieldcontain">
<label for="userid">
ID
</label>
<input type="text" name="userid" id="userid" value=""/>
</div>
<div data-role="fieldcontain">
<label for="password">
Password
</label>
<input type="password" name="password" id="password" value=""/>
</div>
<input type="submit" value="Login" data-role="button" data-inline="true"/>
</form>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
The method mysqli_query requires the following parameters:
The database connection resource, and
The query to run
As chris85 noted, you're missing the database resource parameter.
$result = mysqli_query($con, "SELECT * FROM user WHERE UserID='" . $userid . "'");
while ($row = mysqli_fetch_assoc($result)) {
To reiterate Jay Blanchard's comments regarding your application's security, it appears that you're both storing user passwords in your database in plain text and setting yourself up for SQL injection risks. The script below mitigates those risks by using prepared statements (prepare, bind_param and execute) and the password functions that have been included in PHP since 5.5.
Note that passwords must be inserted into the database after being run through password_hash; after that, you can use password_verify to validate the password.
$successful_login = false;
$query = 'SELECT password FROM user WHERE UserID = ?';
$stmt = mysqli_prepare($con, $query);
$stmt->bind_param('s', $userid);
$stmt->bind_result($row_passwd);
$stmt->execute();
if ($stmt->fetch()) {
$successful_login = password_verify($password, $row_passwd);
}
if ($successful_login) {
echo 'Account validated.';
}
Please check this line of your code:
$result = mysqli_query("SELECT * FROM user WHERE UserID='" . $userid . "'");
I think the SQL query doesn't need the single quote. (like this: SELECT * FROM user WHERE UserID='userid') If you use the single quotes the userid is interpreted as text and not as number. In this case it wouldn't find any entry for a user and in a row no password.
Try this line instead:
$result = mysqli_query("SELECT * FROM user WHERE UserID=" . $userid);
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'];