$_POST is not getting any values and i have tried a lot of procedure already mentioned on stack overflow but they are not working for me. I have tried printing the $_POST it is empty. i need some suggestions on it..please help
It was previously working when it was in mysql database but i tried to change the database to sqlserver and now its not working but i am not understanding i have not made any changes to this particular code and i have seen this also that it is not being affected by some other file.
there is no mistake in empty condition i wrote it myself to check whether it was empty or not and it was always showing empty whether i submit data or not
i am attaching some codes which are related to this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<?php
ob_start();
session_start();
require_once 'config.php';
?>
<?php
if(empty($_POST)){
echo "hello";
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data){
$_SESSION['success'] = USER_REGISTRATION_SUCCESS;
header('Location: index.php');exit;
}
} catch (Exception $e) {
$_SESSION['error'] = $e->getMessage();
}
}
?>
<!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">
<meta name="description" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<meta name="keywords" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<title>PHP Quiz Script</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.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/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.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">PHP Quiz Application</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit" name="submit">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
<?php unset($_SESSION['success'] ); unset($_SESSION['error']); ?>
<?php
$server="NIKUNJ";
$ci = array("Database" => "My database","UID"=>"sa", "PWD"=>"sql#123","Characterset"=>"UTF-8") or die( "check db connect1" );
$conn = sqlsrv_connect($server,$ci) or die ( "check db connect2" ) ;
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
function mssql_insert_id() {
$id = 0;
$res = sqlsrv_query("SELECT ##identity AS id");
if ($row = sqlsrv_fetch_array($res, MSSQL_ASSOC)) {
$id = $row["id"];
}
return $id;
}
class Cl_User
{
/**
* #var will going contain database connection
*/
protected $_con;
/**
* it will initalize DBclass
*/
public function __construct()
{
$db = new Cl_DBclass();
$this->_con = $db->con;
}
/**
* this will handles user registration process
* #param array $data
* #return boolean true or false based success
*/
public function registration( array $data )
{
echo "hello";
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$name = mssql_escape( $trimmed_data['name'] );
$password = mssql_escape( $trimmed_data['password'] );
$cpassword = mssql_escape( $trimmed_data['confirm_password'] );
// Check for an email address:
if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
$email = mssql_escape( $trimmed_data['email']);
} else {
throw new Exception( "Please enter a valid email address!" );
}
if((!$name) || (!$email) || (!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "INSERT INTO users (id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
};
} else{
throw new Exception( USER_REGISTRATION_FAIL );
}
}
/**
* This method will handle user login process
* #param array $data
* #return boolean true or false based on success or failure
*/
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mssql_escape( $this->_con, $trimmed_data['email'] );
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT id, name, email, created FROM users where email = '$email' and password = '$password' ";
$result = sqlsrv_query($this->_con, $query);
$data = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
$count = SQLSRV_num_rows($result);
echo $count;
sqlsrv_close($this->_con);
if( $count == 1){
$_SESSION = $data;
$_SESSION['logged_in'] = true;
return true;
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
/**
* This will shows account information and handles password change
* #param array $data
* #throws Exception
* #return boolean
*/
public function account( array $data )
{
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
$cpassword = $trimmed_data['confirm_password'];
$user_id = $_SESSION['id'];
if((!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "UPDATE users SET password = '$password' WHERE id = '$user_id'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This handle sign out process
*/
public function logout()
{
session_unset();
session_destroy();
session_start();
$_SESSION['success'] = LOGOUT_SUCCESS;
header('Location: index.php');
}
/**
* This reset the current password and send new password to mail
* #param array $data
* #throws Exception
* #return boolean
*/
public function forgetPassword( array $data )
{
if( !empty( $data ) ){
// escape variables for security
$email = mssql_escape( $this->_con, trim( $data['email'] ) );
if((!$email) ) {
throw new Exception( FIELDS_MISSING );
}
$password = $this->randomPassword();
$password1 = md5( $password );
$query = "UPDATE users SET password = '$password1' WHERE email = '$email'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
$to = $email;
$subject = "New Password Request";
$txt = "Your New Password ".$password;
$headers = "From: rahul.ranjan72#hotmail.com" . "\r\n" .
"CC:rahul.ranjan72#hotmail.com";
mail($to,$subject,$txt,$headers);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This will generate random password
* #return string
*/
private function randomPassword()
{
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
public function pr($data = '' )
{
echo "<pre>"; print_r($data); echo "</pre>";
}
public function getCategory()
{
$query = "SELECT * FROM categories";
$results = sqlsrv_query($conn, $query) or die(SQLSRV_errors());
$categories = array();
while ( $result = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC) ) {
echo $result['id'];
$categories[$result['id']] = $result['category_name'];
}
return $categories;
}
public function getQuestions(array $data)
{
if( !empty( $data ) ){
// escape variables for security
$category_id = mssql_escape( $this->_con, trim( $data['category'] ) );
if((!$category_id) ) {
throw new Exception( FIELDS_MISSING );
}
$user_id = $_SESSION['id'];
$query = "INSERT INTO scores ( user_id,right_answer,category_id)VALUES ( '$user_id',0,'$category_id')";
sqlsrv_query( $this->_con, $query);
$_SESSION['score_id'] = mssql_insert_id();
$results = array();
$number_question = $_POST['num_questions'];
$total_question = $_POST['total_num_questions'];
$row = sqlsrv_query( $this->_con, "select * from questions where category_id=$category_id ORDER BY RAND()");
$check=SQLSRV_num_rows($row);
if($check<$total_question)
$rowcount=$check;
else
$rowcount = $total_question;
$remainder = $rowcount/$number_question;
$results['number_question'] = $number_question;
$results['remainder'] = $remainder;
$results['rowcount'] = $rowcount;
while ( $result = SQLSRV_FETCH_ASSOC($row) ) {
$results['questions'][] = $result;
}
sqlsrv_close($this->_con);
return $results;
} else{
throw new Exception( FIELDS_MISSING );
}
}
public function getAnswers(array $data)
{
if( !empty( $data ) ){
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
$total_question = $_POST['total_num_questions'];
$keys=array_keys($data);
$order=join(",",$keys);
$query = "select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)";
$response=sqlsrv_query( $this->_con, $query) or die(SQLSRV_errors());
$user_id = $_SESSION['id'];
$score_id = $_SESSION['score_id'];
while($result=sqlsrv_fetch_array($response)){
if($result['answer']==$_POST[$result['id']]){
$right_answer++;
}else if($data[$result['id']]=='smart_quiz'){
$unanswered++;
}
else{
$wrong_answer++;
}
}
$results = array();
$results['right_answer'] = $right_answer;
$results['wrong_answer'] = $wrong_answer;
$results['unanswered'] = $unanswered;
$update_query = "update scores set right_answer='$right_answer', wrong_answer = '$wrong_answer', unanswered = '$unanswered' where user_id='$user_id' and id ='$score_id' ";
sqlsrv_query( $this->_con, $update_query) or die(SQLSRV_errors());
sqlsrv_close($this->_con);
return $results;
}
}
}
<?php
/**
#author vetripandi
#copyright http:www.vetbossel.in
*/
require_once 'messages.php';
//site specific configuration declartion
define( 'DB_HOST', 'NIKUNJ' );
define( 'DB_USERNAME', 'sa');
define( 'DB_PASSWORD', 'sql#123');
define( 'DB_NAME', 'user_login');
function __autoload($class)
{
$parts = explode('_', $class);
$path = implode(DIRECTORY_SEPARATOR,$parts);
require_once $path . '.php';
}
its the image of the data i am sending but $_POST is not getting any values and nothing happens after signup button is pressed
Your code is only running if the $_POST array is empty.
Change your code to the following.
if(!empty($_POST))
Other than that, I see no problems.
It's better practice to take the submit button as a centre of attention for the execution of the server side coding executing.
Therefore check if the $_POST data has been sent using isset:
if (isset($_POST['submit']))
{
// the data has successfully been sent
}
are you sure is's ok ?
if(empty($_POST))
you always execute code in if if $_POST is empty
if(!empty($_POST))
execute when $_POST NOT empty
This may not be your problem, but generally the submit button is
<input type="submit" value="submit">
rather than
<button type="submit">Submit</button>
From: W3schools.com
I got my mistake. I dont know how but the value of the forms were not only transferred to this php file but also in another php file names check-email.php which was part of my project which was not mentioned anywhere in register.php.
I got to know the problem by seeing some post related to this kind of problem on stack overflow where he said to check you PHP_error_log and Apache error log. The error was clearly stated there. By doing some changes to check-email.php it is working fine now. Thank you everybody for your help anyway
Related
I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:
/index.php - Uncaught Error: Call to a member function prepare() on
null in
/Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56
Stack trace:
0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)
1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')
2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')
3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line
56
Here is my code for index.php:
<?php
include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;
// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {
// TODO: filter input for the "box_file" and "description" parameters.
// Hint: filtering input for files means checking if the upload was successful
$upload_info=$_FILES["box_file"];
$upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
if ($upload_info['error']==UPLOAD_ERR_OK){
$upload_name=basename($upload_info["name"]);
$upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );
$sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
$params=array(
':user_id' => $current_user['id'],
':file_name'=> $upload_name,
':file_ext'=>$upload_ext,
':description'=>$upload_desc,
);
$result=exec_sql_query($db, $sql, $params);
if ($result){
$file_id=$db->lastInsertId("id");
$new_path="uploads/documents/$file_id.$upload_ext";
move_uploaded_file($upload_info["tmp_name"],$new_path);
}
}
// TODO: If the upload was successful, record the upload in the database
// and permanently store the uploaded file in the uploads directory.
// $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
// $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>
<body>
<h1>Fine Art Photography</h1>
<div id="content-wrap">
<?php
// If the user is logged in, let them upload files and view their uploaded files.
if ( is_user_logged_in() ) {
foreach ($messages as $message) {
echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>\n";
}
?>
<h2>Upload a File</h2>
<!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
<form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
<ul>
<li>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<label for="box_file">Upload File:</label>
<input id="box_file" type="file" name="box_file">
</li>
<li>
<label for="box_desc">Description:</label>
<textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
</li>
<li>
<button name="submit_upload" type="submit">Upload File</button>
</li>
</ul>
</form>
<?php
} else {
?>
<p><strong>You need to sign in before you can upload image.</strong></p>
<?php
include("includes/login.php");
}
?>
<!-- <h2>Saved Files</h2> -->
<h2>Categories</h2>
<h2>Photos</h2>
<div class="img">
<?php
$records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
if (count($records) > 0) {
foreach($records as $record) {
echo "<div class=\"content\">";
echo "<div class=\"block\">";
echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
"\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</body>
</html>
And here is my code for init.php:
<?php
// vvv DO NOT MODIFY/REMOVE vvv
// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
if (version_compare(phpversion(), '7.0', '<')) {
define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
echo VERSION_MESSAGE;
throw VERSION_MESSAGE;
}
}
check_php_version();
function config_php_errors()
{
ini_set('display_startup_errors', 1);
ini_set('display_errors', 0);
error_reporting(E_ALL);
}
config_php_errors();
// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
if (!file_exists($db_filename)) {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (file_exists($init_sql_filename)) {
$db_init_sql = file_get_contents($init_sql_filename);
try {
$result = $db->exec($db_init_sql);
if ($result) {
return $db;
}
} catch (PDOException $exception) {
// If we had an error, then the DB did not initialize properly,
// so let's delete it!
unlink($db_filename);
throw $exception;
}
} else {
unlink($db_filename);
}
} else {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
return null;
}
function exec_sql_query($db, $sql, $params = array())
{
$query = $db->prepare($sql);
if ($query and $query->execute($params)) {
return $query;
}
return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^
// You may place any of your code here.
// $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');
define('SESSION_COOKIE_DURATION', 60*60*1);
$session_messages = array();
function log_in($username, $password) {
global $db;
global $current_user;
global $session_messages;
if ( isset($username) && isset($password) ) {
// check if username exists in the database
$sql = "SELECT * FROM users WHERE username = :username;";
$params = array(
':username' => $username
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// There shouldn't be repetitive username.
$account = $records[0];
// Check if password is correct
if ( password_verify($password, $account['password']) ) {
// Create session
$session = session_create_id();
// Store session ID in database
$sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
$params = array(
':user_id' => $account['id'],
':session' => $session
);
$result = exec_sql_query($db, $sql, $params);
if ($result) {
// If result exists, session stored in DB
// Send this back to the user.
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
$current_user = $account;
return $current_user;
} else {
array_push($session_messages, "Log in failed. Something went wrong");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "No username or password given.");
}
$current_user = NULL;
return NULL;
}
function find_user($user_id) {
global $db;
$sql = "SELECT * FROM users WHERE id = :user_id;";
$params = array(
':user_id' => $user_id
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// users are unique, there should only be 1 record
return $records[0];
}
return NULL;
}
function find_session($session) {
global $db;
if (isset($session)) {
$sql = "SELECT * FROM sessions WHERE session = :session;";
$params = array(
':session' => $session
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// No repetitive sessions
return $records[0];
}
}
return NULL;
}
function session_login() {
global $db;
global $current_user;
if (isset($_COOKIE["session"])) {
$session = $_COOKIE["session"];
$session_record = find_session($session);
if ( isset($session_record) ) {
$current_user = find_user($session_record['user_id']);
// The session will last for 1 more hour
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
return $current_user;
}
}
$current_user = NULL;
return NULL;
}
function is_user_logged_in() {
global $current_user;
// if $current_user is not NULL, then a user is logged in.
return ($current_user != NULL);
}
function log_out() {
global $current_user;
// Remove the session from the cookie and fgo back in time to expire the session.
setcookie('session', '', time() - SESSION_COOKIE_DURATION);
$current_user = NULL;
}
// ---- Check for login, logout requests. Or check to keep the user logged in. ----
// Check if we should login the user
if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
log_in($username, $password);
} else {
// check if the user already logged in
session_login();
}
// Check if we should logout the user
if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
log_out();
}
?>
When I submit my data from the form, it won't insert the form data in to the database. The connection to the databse is set and when I check the connection it always responds that it is connected. The database is correctly setup with all values: id, name, date, emailadress and text. The username, password and database name are correct.
The syntax should be correct. I work with mysql workbench.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title></title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="input.css">
<header>
<h1></h1>
</header>
<nav>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</nav>
<main>
<form method="post" action="input.php">
<label>Name</label>
<input placeholder="Name" name="name" type="text"><br>
<label>Mailadress</label>
<input placeholder="Emailadress" name="eMail" type="email"><br>
<label>Your comment</label>
<textarea name="comment" placeholder="Text" name="comment"cols="60" rows="15"></textarea>
<input value="Send" type="submit">
</form>
</main>
</body>
</html>
PHP code:
<?php
if($con->connect_error)
{
die("No connection" .$con-> connect_error);
}
echo "Connected";
$guestbook = new GuestbookAccess();
if (isset($_POST['submit'])){
$name = $_POST['name']; $eMail = $_POST['eMail']; $comment = $_POST['comment'];
}
class GuestbookAccess
{
private $db;
/**
* Opens the database.
*/
public function __construct()
{
$username = "tipuser";
$password = "TIP2018_WebEngineering";
$database = "tip";
// Open the database
$this->db = mysqli_connect("localhost", $username, $password);
if ($this->db == false) {
die("Unable to connect to database");
}
// Select database
mysqli_select_db($this->db, $database);
}
/**
* Evaluates current time and adds a new guestbook entry with given name,
* e-Mail and comment.
* #param String $name User name
* #param String $eMail User e-mail address
* #param String $comment The entry text
* #return On success: Integer Index generated by the database for the entry
* On failure: Boolean false
*/
public function addEntry($name, $eMail, $comment)
{
// For security: suppress SQL injection
$name = mysqli_real_escape_string($this->db, $name);
$eMail = mysqli_real_escape_string($this->db, $eMail);
$comment = mysqli_real_escape_string($this->db, $comment);
// Add entry to the database
$result = mysqli_query($this->db, "INSERT INTO guestbook (name, email, comment) VALUES ('$name', '$eMail', '$comment')");
if ($result)
{
$result = mysqli_insert_id($this->db);
}
return $result;
}
/**
* Return in an table (two-dimensional array) all entries of the guest book.
* Each row of the table represents one entry in the guest book.
* #return table[...]["Index"] --> Integer: Index of the entry (for deleting)
* table[...]["Name"] --> String: name of the user
* table[...]["eMail"] --> String: e-Mail of the user
* table[...]["Comment"] --> String: The guest book entry (as text)
* table[...]["Date"] --> String: Date and time of the entry
*/
public function getEntries()
{
// Create query
$result = mysqli_query($this->db, "SELECT * FROM guestbook");
$table = false;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$table[$i]["Index"] = $row["indes"];
$table[$i]["Date"] = $row["date"];
$table[$i]["Name"] = $row["name"];
$table[$i]["eMail"] = $row["email"];
$table[$i]["Comment"] = $row["comment"];
$i++;
}
mysqli_free_result($result);
return $table;
// Get all entries in the guestbook
$table = $guestbook->getEntries();
if ($table) { // Check if there are enrtries
echo "\nThe guestbook contains:\n";
foreach ($table as $row) {
// Output each element
$index = $row["Index"];
$name = $row["Name"];
$date = $row["Date"];
$email = $row["eMail"];
$comment = $row["Comment"];
echo "Index: $index, ";
echo "Name: $name, ";
echo "Date: $date, ";
echo "eMail: $email, ";
echo "Comment: $comment\n";
}
}
else {
echo "\nGuest book is empty\n";
}
/**
* Closes the database.
*/
function __destruct()
{
mysqli_close($this->db);
}
}
}
?>
You should add name as submit for submit type in your input tage so to make the isset($_POST['submit']) work in php
<input value="Send" type="submit" name="submit">
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using PHP mysqli to access and insert record to database and also prepared statements but somewhere there is an error i couldn't figure out.. pointing out the mistake will be very much helpful
mailer.php
<?php
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($record) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $record->name , $record->message);
if ($stmt->execute()) {
$status = ($stmt->affected_rows == 1) ? true : false;
$stmt->fetch_object();
$stmt->close();
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
if (isset($_POST['submit']) ) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$result = $submit->addRecord($name,$message);
if ($result) {
echo "Message Saved";
}
}
Also i am using ajax call from an external file containing a form and scripts within that
index.php
<!DOCTYPE html>
<html>
<head>
<title>Contact Form | PHP, AJAX and MySQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form id="submit_form">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
<br />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
<span id="error_message" class="text-danger"></span>
<span id="success_message" class="text-success"></span>
</form>
</div>
</body>
</html>
<script>
jQuery(function($){
$('form#submit_form').submit(function(e){
e.preventDefault();
var name = $(this).find('#name').val(),
message = $(this).find('#message').val();
if(name == '' || message == '') {
$('#error_message').html("All Fields are required");
}
else {
$('#error_message').html('');
$.ajax({
url:"mailer.php",
method:"POST",
data:{
name: name,
message: message
},
success:function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html(data).fadeOut(3000);
}
});
}
});
});
</script>
You are giving 2 parameters to your addRecord() method, but it expects only 1. But, it seems it expects an object which you are not initializing so I adjusted it, so it takes the two parameters you are giving it.
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
Also I removed some unnecessary steps in the method:
$status = ($stmt->affected_rows == 1) ? true : false;
$status = $stmt->affected_rows === 1;
The comparison itself will return a boolean, so no need to use an explicit structure.
$stmt->fetch_object();
$stmt->close();
Fetching the object without ever using it is a waste.
When leaving the scope of the method, the garbage collector will unset the stmt.
Code to test the function:
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
$name = "dsfdsf";
$message = "message";
$result = $submit->addRecord($name,$message);
var_dump($result); // bool(true)
How do I make the following database only submit the entries if the password matches '1996' - I have tried looking into this and can't find out anything. The following could also have a display.php file that has the database details on and they also have the correct pin coding. I just don't know how to make this part of the coding make sure the pin is correct before submitting the details and if the pin is incorrect then an error message apears.
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $db;
var $pin;
public function display_public() {
$q = "SELECT * FROM sianDB4 ORDER BY created DESC LIMIT 4";
$r = mysql_query($q);
$entry_display = '';
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$title = ($a['title']);
$bodytext = ($a['bodytext']);
$author = ($a['author']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$title
</h2>
<h3>
$bodytext
</h3>
<p>
$author
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="title">Title:</label><br />
<input name="title" id="title" type="text" maxlength="150" />
<div class="clear"></div>
<label for="bodytext">Body Text:</label><br />
<textarea name="bodytext" id="bodytext"></textarea>
<div class="clear"></div>
<label for="author">Author:</label><br />
<textarea name="author" id="author"></textarea>
<div class="clear"></div>
<label for="pin">Pin:</label><br />
<input name="pin" id="pin" type="Password" maxlength="4" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['title'] )
$title = mysql_real_escape_string($_POST['title']);
if ( $_POST['bodytext'])
$bodytext = mysql_real_escape_string($_POST['bodytext']);
if ( $_POST['author'])
$author = mysql_real_escape_string($_POST['author']);
if ( $title && $bodytext && $author ) {
$created = time();
$sql = "INSERT INTO sianDB4
VALUES( '$title','$bodytext','$author','$created')";
return mysql_query($sql);
}else{
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password,$this->pin) or die("Could not connect. " . mysql_error());
mysql_select_db($this->db) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS sianDB4 (
title VARCHAR(150),
bodytext TEXT,
author TEXT,
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
As noted by #Jay, the use of the mysql_* suite of functions is not to be recommended anymore so hopefully you can make use of the code below which uses mysqli instead.
I'm not sure how you were using or presenting the class to the user but you'll no doubt be able to make the necessary changes.
<?php
class simplecms{
/*
Pass in the dbconn as a parameter to this class's constructor
*/
private $db;
private $pin;
public function __construct( dbconn $db=null, $pin=false ){
$this->db=$db;
$this->pin=intval( $pin );
}
public function display_public() {
$sql='select * from `siandb4` order by `created` desc limit 4';
$res=$this->db->query( $sql );
/* use an array rather than concatenating a string for output */
$html=array();
if( $res ){
while( $rs = $res->fetch_object() ){
$html[]="
<div class='post'>
<h2>{$rs->title}</h2>
<h3>{$rs->bodytext}</h3>
<p>{$rs->author}</p>
</div>";
}
} else {
$html[]="
<h2>This Page Is Under Construction</h2>
<p>No entries have been made on this page. Please check back soon, or click the link below to add an entry!</p>";
}
/* hide this from ordinary users somehow */
$html[]="
<p class='admin_link'>
<a href='{$_SERVER['SCRIPT_NAME']}?admin=1'>Add a New Entry</a>
</p>";
/* Add the admin form */
$html[]=$this->display_admin();
/* display stuff */
echo implode( PHP_EOL, $html );
}
public function display_admin() {
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){/* Add record to the db if the pin matches */
$message=$this->write() ? 'Database has been updated' : 'Sorry, unable to add that record - check your PIN is correct';
}
$admin = isset( $_GET['admin'] ) ? intval( filter_input( INPUT_GET, 'admin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
return $admin ? "
<style>
form#admin, form#admin *{display:block;box-sizing:content-box!important;}
form#admin{ width:50%;display:block;clear:both;float:none;margin:0 auto;}
form#admin label{width:100%;clear:both;float:none;margin:0.5rem auto 3rem auto;padding:0.25rem;}
form#admin label input, form#admin textarea{float:right;width:60%;padding:1rem;}
form#span{color:red;}
</style>
<form id='admin' method='post'>
<label for='title'>Title:<input name='title' id='title' type='text' maxlength='150' /></label>
<label for='bodytext'>Body Text:<textarea name='bodytext' id='bodytext'></textarea></label>
<label for='author'>Author:<textarea name='author' id='author'></textarea></label>
<label for='pin'>Pin:<input name='pin' id='pin' type='Password' maxlength='4' /></label>
<input type='submit' value='Create This Entry!' />
<span>{$message}</span>
</form>" : "";
}
public function write(){
$pin = isset( $_POST['pin'] ) ? intval( filter_input( INPUT_POST, 'pin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
$title = isset( $_POST['title'] ) ? filter_input( INPUT_POST, 'title', FILTER_SANITIZE_STRING ) : false;
$bodytext = isset( $_POST['bodytext'] ) ? filter_input( INPUT_POST, 'bodytext', FILTER_SANITIZE_STRING ) : false;
$author = isset( $_POST['author'] ) ? filter_input( INPUT_POST, 'author', FILTER_SANITIZE_STRING ) : false;
if ( $title && $bodytext && $author && $pin===$this->pin ) {
/* ? not sure you really want to run this each and every time but... */
$this->buildtbl();
/* Prepare the sql and execute - return status */
$sql='insert into `sianDB4` set `title`=?, `bodytext`=?, `author`=?;';
$stmt=$this->db->prepare( $sql );
$stmt->bind_param( 'sss', $title, $bodytext, $author );
return $stmt->execute();
}
return false;
}
private function buildtbl(){/* build the table - slightly modified */
$sql='create table if not exists `siandb4` (
`id` int(10) unsigned not null auto_increment,
`title` varchar(150) null default null,
`bodytext` text null,
`author` text null,
`created` timestamp null default current_timestamp,
primary key (`id`)
)engine=innodb;';
$this->db->query( $sql );
}
}//end class
class dbconn{
/* Simple mysqli db connection */
private $conn;
public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
$this->conn=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
}
public function query( $sql ){
return $this->conn->query( $sql );
}
public function prepare( $sql ){
return $this->conn->prepare( $sql );
}
}//end class
?>
<html>
<head>
<title>Simple CMS - Hello Kitty Example!</title>
<style>
h2,h3{font-size:1rem;}
div.post{font-size:0.85rem;border-bottom:1px dotted gray;margin:0 auto 3rem auto;}
</style>
</head>
<body>
<h1>Simple CMS - Hello Kitty Example!</h1>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxxxxx';
$dbname = 'xxxxxx';
$db=new dbconn( $dbhost, $dbuser, $dbpwd, $dbname );
$cms=new simplecms( $db, 1996 );
$cms->display_public();
$db=$cms=null;
?>
</body>
</html>
I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code:
<?php
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user, $pass, $email)
{
// Used for display only
$this->unclean_username = $user;
// Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if (usernameExists($this->clean_username)) {
$this->username_taken = true;
}
else if (emailExists($this->clean_email)) {
$this->email_taken = true;
}
else {
// No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db, $emailActivation, $websiteUrl, $db_table_prefix;
// Prevent this function being called if there were construction errors
if ($this->status) {
// Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
// Construct a unique activation token
$this->activation_token = generateactivationtoken();
// Do we need to send out an activation email?
if ($emailActivation) {
// User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
// Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE", array(
"{$websiteUrl}/",
$this->activation_token
));
// Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array(
"#ACTIVATION-MESSAGE",
"#ACTIVATION-KEY",
"#USERNAME#"
) ,
"subjectStrs" => array(
$activation_message,
$this->activation_token,
$this->unclean_username
)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if (!$mail->newTemplateMsg("new-registration.txt", $hooks)) {
$this->mail_failure = true;
}
else {
// Send the mail. Specify users email here and subject.
// SendMail can have a third parementer for message if you do not wish to build a template.
if (!$mail->sendMail($this->clean_email, "New User")) {
$this->mail_failure = true;
}
}
}
else {
// Instant account activation
$this->user_active = 1;
}
if (!$this->mail_failure) {
// Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `" . $db_table_prefix . "users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'" . $db->sql_escape($this->unclean_username) . "',
'" . $db->sql_escape($this->clean_username) . "',
'" . $secure_pass . "',
'" . $db->sql_escape($this->clean_email) . "',
'" . $this->activation_token . "',
'" . time() . "',
'0',
'" . $this->user_active . "',
'1',
'" . time() . "',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
Config.php file for Register Processing
<?php
if (is_dir("install/")) {
header("Location: install/");
die();
}
require_once ("settings.php");
// Dbal Support - Thanks phpBB ; )
require_once ("db/" . $dbtype . ".php");
// Construct a db instance
$db = new $sql_db();
if (is_array($db->sql_connect($db_host, $db_user, $db_pass, $db_name, $db_port, false, false))) {
die("Unable to connect to the database");
}
if (!isset($language)) $langauge = "en";
require_once ("lang/" . $langauge . ".php");
require_once ("class.user.php");
require_once ("class.mail.php");
require_once ("funcs.user.php");
require_once ("funcs.general.php");
require_once ("class.newuser.php");
session_start();
// Global User Object Var
// loggedInUser can be used globally if constructed
if (isset($_SESSION["userPieUser"]) && is_object($_SESSION["userPieUser"])) $loggedInUser = $_SESSION["userPieUser"];
else if (isset($_COOKIE["userPieUser"])) {
$db->sql_query("SELECT session_data FROM " . $db_table_prefix . "sessions WHERE session_id = '" . $_COOKIE['userPieUser'] . "'");
$dbRes = $db->sql_fetchrowset();
if (empty($dbRes)) {
$loggedInUser = NULL;
setcookie("userPieUser", "", -parseLength($remember_me_length));
}
else {
$obj = $dbRes[0];
$loggedInUser = unserialize($obj["session_data"]);
}
}
else {
$db->sql_query("DELETE FROM " . $db_table_prefix . "sessions WHERE " . time() . " >= (session_start+" . parseLength($remember_me_length) . ")");
$loggedInUser = NULL;
}
?>
Register Page PHP Code
<?php
require_once ("models/config.php");
// Prevent the user visiting the logged in page if he/she is already logged in
if (isUserLoggedIn()) {
header("Location: index.php");
die();
}
/*
Below is a very simple example of how to process a new user.
Some simple validation (ideally more is needed).
The first goal is to check for empty / null data, to reduce workload here we let the user class perform it's own internal checks, just in case they are missed.
*/
// Forms posted
if (!empty($_POST)) {
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
// Perform some validation
// Feel free to edit / change as required
if (minMaxRange(5, 25, $username)) {
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT", array(
5,
25
));
}
if (minMaxRange(8, 50, $password) && minMaxRange(8, 50, $confirm_pass)) {
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT", array(
8,
50
));
}
else if ($password != $confirm_pass) {
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if (!isValidemail($email)) {
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
// End data validation
if (count($errors) == 0) {
// Construct a user object
$user = new User($username, $password, $email);
// Checking this flag tells us whether there were any errors such as possible data duplication occured
if (!$user->status) {
if ($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE", array(
$username
));
if ($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE", array(
$email
));
}
else {
// Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if (!$user->userPieAddUser()) {
if ($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if ($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if (count($errors) == 0) {
if ($emailActivation) {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
}
else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
HTML Register Form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Registration |
<?php echo $websiteName; ?>
</title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>
Sign Up
</h2>
</div>
<div class="modal-body">
<div id="success">
<p>
<?php echo $message ?>
</p>
</div>
<div id="regbox">
<form name="newUser" action="
<?php echo $_SERVER['PHP_SELF'] ?>
" method="post">
<p>
<label>
Username:
</label>
<input type="text" name="username" />
</p>
<p>
<label>
Password:
</label>
<input type="password" name="password" />
</p>
<p>
<label>
Re-type Password:
</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>
Email:
</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear">
</div>
<p style="margin-top:30px; text-align:center;">
<a href="login.php">
Login
</a>
/
<a href="forgot-password.php">
Forgot Password?
</a>
/
<a href="
<?php echo $websiteUrl; ?>
">
Home Page
</a>
</p>
</body>
</html>
In your html file remove the action attribute of tag form or use action = "". Donot use $_SERVER[PHP_SELF] as it is prone to extra scripts being run from your page.
Other than that, will check the code. Try using echo or print_r wherever possible to check what part is causing problem. Use try-catch for checking if the db returns errors in SQL.