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>
Related
I have been trying to get my session update, I have created a basic update with mysql as well, it updates in the sql database but it will not show the change within the page.
I'm not sure what else to check, because I checked within the chrome settings and it does show a php session id value but if I go into session storage it shows nothing.
transaction.php
<?php
$_title = 'Update profile';
require_once(__DIR__.'../../components/header.php');
session_start();
if(! isset($_SESSION['user_name'])){
header('Location: ../sign_in/sign_in.php');
die();
}
if (!isset($_SESSION["lang"])) { $_SESSION["lang"] = "en"; }
if (isset($_POST["lang"])) { $_SESSION["lang"] = $_POST["lang"]; }
require_once(__DIR__.'../../globals.php');
require_once(__DIR__.'../../db.php');
try{
$db = _db();
}catch(Exception $ex){
_res(500, ['info'=>'System under maintainance','error'=>__LINE__]);
}
$userProduct = $_SESSION['user']['user_id'];
$q = $db->prepare('SELECT * FROM users WHERE user_id = :userID');
$q->bindValue(":userID", $userProduct);
$q->execute();
require "../lan/lang." . $_SESSION["lang"] . ".php";
?>
<form class="style_form" id="update_profile" onsubmit="return false">
<div>
<label for="name"><?=$_TXT[63]?></label>
<input type="text" name="name" value="<?php echo $_SESSION['user']['user_name']?>">
</div>
<div>
<label for="last_name"><?=$_TXT[64]?></label>
<input type="text" name="last_name" value="<?php echo $_SESSION['user']['lastName']?>">
</div>
<div>
<label for="email"><?=$_TXT[65]?></label>
<input name="email" value="<?php echo $_SESSION['user']['email']?>" type="text">
<input type="hidden" name="userId" value="<?php echo $_SESSION['user']['user_id'] ?>">
<button onclick="update()" id="updateButton"><?=$_TXT[60]?></button>
</form>
</section>
<?php
require_once(__DIR__.'../../components/footer.php');
?>
api-transaction.php
<?php
require_once(__DIR__.'../../globals.php');
// Validate name
if( ! isset( $_POST['name'] ) ){ _res(400,['name is required']); }
if( strlen( $_POST['name'] ) < _FRIST_NAME_MIN_LEN ){ _res(400,['name min '._FRIST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['name'] ) > _FRIST_NAME_MAX_LEN ){ _res(400,['name max '._FRIST_NAME_MAX_LEN.' characters']); }
// Validate last_name
if( ! isset( $_POST['last_name'] ) ){ _res(400,['last_name is required']); }
if( strlen( $_POST['last_name'] ) < _LAST_NAME_MIN_LEN ){ _res(400,['last_name min '._LAST_NAME_MIN_LEN.' characters']); }
if( strlen( $_POST['last_name'] ) > _LAST_NAME_MAX_LEN ){ _res(400,['last_name max '._LAST_NAME_MAX_LEN.' characters']); }
// Validate email
if( ! isset( $_POST['email'] ) ){ _res(400,['email is required']); }
if( ! filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL ) ){ _res(400,['email is invalid']); }
$db = require_once(__DIR__.'../../db.php');
try{
session_start();
// $userid = $_SESSION['userId'];
// $userid = $_SESSION['user']['user_id'];
$userid = $_POST['userId'];
$db->beginTransaction();
//Change name
$q = $db->prepare('UPDATE users SET user_name = :update_Name WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_Name', $_POST['name']);
$q->execute();
//Change last name
$q = $db->prepare('UPDATE users SET lastName = :update_lastName WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_lastName', $_POST['last_name']);
$q->execute();
//change email
$q = $db->prepare('UPDATE users SET email = :update_email WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_email', $_POST['email']);
$q->execute();
// change phone number
$q = $db->prepare('UPDATE users SET phone_number = :update_phone WHERE user_id = :userid');
$q->bindValue(':userid',$userid);
$q->bindValue(':update_phone', $_POST['phone_number']);
$q->execute();
$db->commit();
header('Content-Type: application/json');
$response = ["info" => "info has been updated"];
echo json_encode($response);
}catch(Exception $ex){
http_response_code(500);
echo $ex;
echo 'System under maintainance';
exit();
}
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();
}
?>
With this code, it can retrieve the values from the database with a checkbox on each row. What I want for it to do is to update the unchecked values (namely 0) in the database with 1 for each checkbox checked.
Here's the query for the database and some sample rows.
CREATE TABLE IF NOT EXISTS `job_order` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`SI_no` varchar(12) NOT NULL DEFAULT '1',
`Date_Issued` date NOT NULL,
`Date_completed` date DEFAULT NULL,
`checked` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `job_order` (`ID`, `SI_no`, `Date_Issued`, `Date_completed`,
`checked`) VALUES
(1, '2', '2018-12-19', '2018-12-26', 1),
(2, '5', '2018-11-06', '2018-12-04', 1),
(3, '7', '2018-12-01', '2018-12-13', 0),
(4, '8', '2018-12-20', '2018-12-12', 0);
COMMIT;
db_c.php - the class file
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($order['order-complete'])){
foreach($order['order-complete'] as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
I'm mostly having problems with the function complete_orders, which doesn't return anything on button press of the submit button. Nor does it check if the checkboxes are ticked.
Here's the HTML layout file
jobrequestfilter.php
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
The isset button returns the echo statement I put, however, most seems to be working fine except for the process order button. Is it wise to just use javascript for the checkbox on update?
Try this one
db_c.php
It should not be
$order['order-complete']
But
$orders
Because the array variable name from post already stored in variable $orders.
It should not be
$id
But
$ids
Because you declare it as
foreach($orders as $ids)
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'your_db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders)){
foreach($orders as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `id` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $ids);
if($stmt->execute()){
array_push($processed, $ids);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
jobrequestfilter.php
3.It should not
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
It should be
if(isset($_POST['order-complete']) &&
isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST['order-complete']) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
Please replace below complete_orders function code
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders['order-complete'])){
foreach($orders['order-complete'] as $id){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
Two problem in code:
Function argument $orders you are passing but while process you using order. So it's was not going inside into loop
in foreach iteration your are using ids but while updating query you using id. so change variable accordingly. Please check
I'm working on a blog website and i'm currently stuck at making a blog edit page. For some reason my blog UPDATE query doesn't work, and i can't figure out why it isn't working. I'm not getting an error. It is just not updating anything.
I'm collecting the data from an old blog and inserting it into my form. And then I'm trying to update it using my update query.
This is my code so far:
aanpassen.php
<?php
$error=false;
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if ( isset( $_POST ['id'], $_POST['title'], $_POST['content'] ) ) {
$id = $_POST ['id'];
$title = $_POST['title'];
$content = nl2br( $_POST['content'] );
if (empty($title) || empty($content) || empty($id)){
$error='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = :title,
article_content = :content WHERE id=:id");
if( $query ){
$id = $_POST ['id'];
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
} else {
exit('bad foo - unable to prepare sql query');
}
}
}
if ( isset( $_GET['id'] ) ) {
$id = $_GET['id'];
$data = $article->fetch_data( $id );
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="title" class="titleform" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea name="content" id="summernote" rows="15" cols="50"><?php echo $data['article_content'] ?></textarea>
<input type="submit" class="buttonclass" value="Aanmaken" />
</form>
<?php
if ($error)
printf('<h1>%s</h1>', $error);
?>
connection.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=cms', 'root', 'root');
} catch (PDOException $e) {
exit('Database error.');
}
?>
you missed ":" in all the bindValue arguments. should be like this:
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
and also if (empty($title) or empty($content) or empty($id)) this should be if (empty($title) || empty($content) || empty($id)) like this
When you access aanpassen.php initially it's in this format right - aanpassen.php?id=1??
Otherwise your code seems fine when I tested it.
Just Change:
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
To:
$success = $query->execute();
header( 'Location: index.php?status='.( $success ? 'ok' : 'failed' ) );exit();
$_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