Submitting session username back to database in query - php

Basically i want whoever creates a note on my website to be the "author" of that note.
So whoever is logged in when they create the note should be the author.
At the moment in login_form.php i have created a session which is the "included" in my general_notes.php. In general_notes.php i have the following code for when the user clicks to add a note:
<p class="fa fa-plus hover-cursor icon-spin noSelect" data-toggle="modal" data-target="#addGeneralNote" style="font-size: 16pt;"></p>
which runs:
<!-- Modal -->
<div id="addGeneralNote" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header header-notes">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add General Note</h4>
</div>
<!-- Form submission data -->
<form action="addNewNote.php" method="POST">
<div class="modal-body">
<p>Please enter the note you wish to create.</p>
<textarea id="addGeneralNoteName" placeholder="Enter a note name..." name="title" maxlength="100"></textarea>
<textarea id="addGeneralNoteText" placeholder="Enter note here..." name="content"></textarea>
<input type="checkbox" name="pinned"> Pin Note to your homepage
</div>
<div class="modal-footer footer-notes">
<button type="submit" class="btn btn-success">Create</button>
</div>
</form>
</div>
</div>
</div>
You'll see in the form there is addNewNote.php which runs:
<?php
if (isset($_POST['title'], $_POST['content'], $_SESSION['username']))
{
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_SESSION['username'];
$stmt = "INSERT INTO Notes (NoteName, Note, Author, DateCreated) VALUES (?, ?, ?, GETDATE())";
$params = array($title, $content, $author);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
header('location: general_notes.php');
}
else
{
echo "No Data";
}
?>
Before i added to the isset $_SESSION['username'] it ran fine.
At the moment it hits this part:
else
{
echo "No Data";
}
of the isset function
So how how do i pass through the session username into my addNewNote.php script?

The simple answer is that you didn't call session_start() in addNewNote.php. But I'd also like to elaborate on a comment you made above, hopefully to help future readers:
i for some reason presumed it would get the session from the previosu page
The "previous page" was a separate HTTP request entirely, and the two have no connection to one another. Much in the same way that a JavaScript application re-starts with each page load, so does a PHP application start anew with each page load.
Consider each individual HTTP request to be its own separate instance of the application. While these instances can share data via external data stores, such as a database or session state, the application itself retains nothing in-memory about any other running or previous instance.
So while the data may indeed be in the session data store (which is external to the application itself), each instance of the application needs needs to connect to that data store in order to use it. Just as one must connect to a database in order to use it, one must also invoke session_start() in order to use the session.

Related

PHP form validation not functioning having copied the tutorial code

I am hoping the community can give me a little insight into what is not working with my code, I am following a Udemy course. I have followed the accompanying video which developed an undefined variable error, which after doing some research I believe I have fixed by declaring variables as empty strings being able to be over-ridden by the form data.
The form sends data to the database if both are completed, and if one of the fields is empty then it doesn't, which is as it should be.
If one of the fields is empty it should return a statement asking the user to enter data into the respective field, but nothing is being sent.
The only difference between the tutorial and my code is I have used the materialize framework, where the tutorial used bootstrap, but I can't see that being the issue.
I have attached my code, and commented out redundant parts.
<?php
include('php/connection.php');
//validates data for create user form
if( isset( $_POST["createUserBtn"])){
$createUsername = "";
$createUserPassword = "";
function validateFormData( $formData ) {
$formData = trim( stripcslashes( htmlspecialchars( $formData)));
return $formData;
}
if( !$_POST["createUsername"]){
$createUsernameError = "Enter a username <br>";
} else {
$createUsername = validateFormData( $_POST["createUsername"]);
}
if( !$_POST["createUserPassword"]){
$createUserPasswordError = "Enter a Password <br>";
} else {
$createUserPassword = validateFormData( $_POST["createUserPassword"]);
}
if( $createUsername && $createUserPassword) {
$query = "INSERT INTO users (user_id, userName, userPassword) VALUES (NULL, '$createUsername', '$createUserPassword')";
// if( mysqli_query( $connection, $query)){
// echo "New User added";
// } else {
// echo "Error: ".$query."<br>".mysqli_error($connection);
// }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php require('static/header.php'); ?>
<?php
$createUsernameError = "";
$createUserPasswordError = "";
?>
<div class="col s8 m8 l5 valign-wrapper">
<div class="container">
<form action="<?php echo htmlspecialchars( $_SERVER["PHP_SELF"] ); ?>" method="post">
<div class="row">
<div class="col s12">
<span><h4>Create your user account - create user.php</h4></span>
<div class="row form-font">
<div class="col s12">
<div class="input-field">
<a class="red-text"><?php echo $createUsernameError; ?></a>
<input placeholder="Enter your username" type="text" name="createUsername">
<label for="email">Username</label>
</div>
<div class="input-field">
<a class="red-text"><?php echo $createUserPasswordError; ?></a>
<input placeholder="Enter your password" type="password" name="createUserPassword">
<label for="password">Password</label>
</div>
<div class="row left-align">
<div class="col s2"></div>
<div class="col s8">
<button class="btn-flat waves-effect waves-custom" type="submit" name="createUserBtn"><i class="material-icons left">create</i>Create Account</button>
</div>
<div class="col s2"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php require('static/footer.php'); ?>
</html>
Look carefully at your code and the places where you make use of - for example - the $createUsernameError variable.
If there's an error, you set a message in it with this line: $createUsernameError = "Enter a username <br>";. Great, just what you wanted.
However, later on in the code, you run $createUsernameError = "";, which resets it to empty again. And that happens in all circumstances, whether an error was identified or not. And it happens before you try to echo that variable onto the page.
So basically you're setting the value and then immediately blanking it again before you output it. You need to make sure it's only set blank in situations where there's no error. It's the same problem for the password error message.
An easy way to do that would simply be to set the value blank before you run the error checks. Then it'll stay blank if there's no error, but it won't overwrite any error messages which do get set.
So just move these lines:
$createUsernameError = "";
$createUserPasswordError = "";
to the top of your script.
P.S. Please pay attention to the security warnings posted in the comments and urgently fix your code to remove these vulnerabilities before using this code in any kind of live environment. Even if you don't plan to use this code for real, you should still fix these issues so that you learn to do things the correct, safe, reliable way and don't get into bad habits. If you copied this code from a course online, I suggest finding a better course.

How to update data using bootstrap modal in php

I'm trying to edit the profile of each user by the admin using bootstrap modal in php.
Here is the summary what I'm doing.
An anchor tag in admin.php page :
Modal at admin.php page.
<div id="theModal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
And javascript in the same page i.e admin.php
$('.li-modal').on('click', function(e){
e.preventDefault();
$('#theModal').modal('show').find('.modal-content').load($(this).attr('href'));
});
here is editprofile.php.
In this page I've selected that user's information who has been clicked to edit, on that above anchor tag.
<?php
$connect = mysqli_connect('localhost','root','','db');
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM user where id = '$id'";
$run = mysqli_query($connect,$query);
}
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
User Information
</div>
<form action="edit.php" method="POST" id = 'myform'>
<!-- body of the bootstrap modal -->
<?php
while($row = mysqli_fetch_assoc($run)){
?>
<label for="name">First Name</label>
<input type="text" name = 'fname' value = '<?php echo $row['fname'] ?>' class = 'form-control'>
<?php
}
?>
<div class="modal-footer">
<input type="button" name="save" class="btn btn-primary" data-dismiss="modal" value="Save Changes" form = 'myform'>
</div>
Here is I want to do:
I want to submit a form (which is there in modal) with updated data by clicking on button that says Save Changes
And I want to redirect the user back to the admin.php page when the admin click outside the modal or when s/he click on the close icon at the top right of the modal.
Also want to show the success message when the admin successfully update the data.
How would I do that?
I don't know how to use a form with in a modal and then how to submit that , there may be some non standard approach , bare me with that.
I never used bootstrap, but I have noticed that you have PHP syntax error in Your 'inline php' or mixed html/php portion inside while loop.
This:
<?php echo $row['fname'] ?>
Should look like this:
<?php echo $row['fname']; ?>
semicolon is missing in Your example.
Other than that, when You just want to echo something in mixed html/php, You don't need php open tag.
Although one should avoid mixing html/php directly as it is very old PHP fashion,
something like this is recommended (semicolon at the end is not needed in this case):
<?=$row['fname']?>
// wrapped in "()" is ok as well, kinda more readable
<?=($row['fname'])?>
And not only that..
You cannot write html tag argument values separated with blank space everywhere. Won't work.
Not like this:
name = 'fname' value =
But like this:
<tagname attribute='value' otherattribute='value'> ...
Try to fix those first.

Updating database with jEditable & mysqli

First of all, jEditable works for me - I can enter a value, hit enter and enjoy the sight of the new value in the table. However, this value is never inserted into the database.
As far as I understand, the jQuery code from the jEditable website
$(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
which I have changed to link to my update.php script
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['value'];
$id = $_POST['id'];
echo $value;
$updateTest=$conn->query("UPDATE table SET column='".$value."' WHERE ID='".$id."'");
should update the database, but nothing happens. When I look at the network log function of Firefox, I can see that there is no ID submitted (I do not know where this ID is supposed to come from in the first place, there is nothing in the example), but the value is there. There does not seem to be a response from the server, however.
Maybe the table itself is the problem:
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
print '<tr>';
print '<td><div class="edit" data-pk="'.$ID.'">'.$row["column"].'</div></td>';
print '</tr>';
(I left out the SELECT statement because everything else is displayed correctly)
Sadly, there is no explanation why the div should have an id - it's apparently not what is submitted in the POST request.
I have googled around a bit, but I could not find an answer to this. It's probably obvious, but I just can't find it. Ever since I changed my original prepared statement to this I don't get errors anymore, either.
I would be very grateful for any help, especially if you could explain my mistake to me so I won't repeat it in the future.
If there is any place on the internet with an actual complete (mysqli) example of what the save.php file mentioned in the Jeditable documentation looks like and you have the link (I certainly didn't find it...), I'd take that too.
This is incorrect:
print '<td><div class="edit" data-pk="'.ID.'">'.$row["column"].'</div></td>';
^^
There's no $, so ID is an undefined constant. PHP will probably try to be polite and assume you meant 'ID' isntead (a string containing the letters I and D), which means ALL of your rows are going to show up in the client as data-pk=ID, and not data-pk=1, data-pk=2, etc...
As there seems to be no solution to this (or, more precisely, I'm running out of time for this project), I switched to modals. If anyone comes across this and considers modals a viable option, here's what I've done:
I'm using a GET form and an update page that updates different tables depending on which page the request comes from - that's what "ref" is for.
update.php:
$updateID=$_GET['id'];
$updateRef=$_GET['ref'];
$col1=$_GET['col1'];
$col2=$_GET['col2'];
if($updateRef == "refpage"){
$updateTable=$conn->query("UPDATE my_table SET col1='".$col1."', col2='".$col2."' WHERE ID='".$updateID."'");
header("Location: refpage.php");
die();
}
My modals are generated with the table rows, which is probably the ugliest solution anyone ever used for anything, but it works... (Can't display the form in a table, though, because tables within divs within tables are a terrible idea.)
$results = $conn->query("SELECT col1, col2 ID FROM my_table");
while($row = $results->fetch_assoc()) {
$ID = $row["ID"];
$modalID = $modalID + 1;
print '<tr>';
print '<td>'.$row["col1"].'</td>';
print '<td>'.$row["col2"].'</td>';
print '<td><span class="glyphicon glyphicon-pencil" style="float: right !important"></span></td>';
print '</tr>';
echo '<div class="modal fade" id="editModal'.$modalID.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Delete</h2>
</div>
<div class="modal-body">
<form action="update.php" method="get">
<div class="row">
<div class="col-xs-6">
col1:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col1"].'" id="col1" name="col1" />
</div>
</div>
<div class="row">
<div class="col-xs-6">
col2:
</div>
<div class="col-xs-6">
<input type="text" value="'.$row["col2"].'" id="col2" name="col2" />
</div>
</div>
<input type="hidden" id="ref" name="ref" value="refpage" />
<input type="hidden" name="id" value="'.$ID.'" />
<input class="btn btn-md" type="submit" id="update" name="update" value="Update" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-md" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>';}
Hope this helps someone. And in case anyone has an idea what was wrong with my original idea, I'd be happy to read the answer. I still think in place updates would be much cooler.

PHP form not saving to table

I have a page called service.php that uses a modal window to open a form. The action on the form was service.php.
<div class="modal hide fade" id="myServiceModal" tabindex="-1" role="dialog" aria-labelleby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Service Failure Form</h3>
</div>
<div class="modal-body">
<p>
<form class="well-small" action="service.php" method="POST" id="serviceModalForm" name="serviceModalForm">
<label>Container Selected</label>
<input type="text" name="containerNumber" id="containerNumber" />
<label>Bol Selected</label>
<input type="text" name="bolNumber" id="bolNumber" />
<input type="submit" id="modal-form-submit" name="submit" class="btn btn-success btn-small" href="#" value="Save" />
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Added New Service Failure')
</script>");
}
?>
</form>
This form worked, and it saved to the appropriate table.
Here is my problem: I had to move that form to another page, called dispatch.php. All I did was copy the code, and put it on dispatch.php.
I changed the action of the form to dispatch.php, and that's where I think the problem starts. When I change the action back to service.php, it works for whatever reason.
When I remove the form completely from service.php, the form on dispatch.php no longer works.
I've tried everything to make this work. I removed all of the code from service.php. I even removed the whole file from the folder.
Any insight would be helpful.
You tell the script what to do but you don't tell it to do it.
In order to excecute a your SLQ-query you have to use mysql_query($sql_query_string);
You will also want to connect to your database. Take a look at http://php.net/manual/de/function.mysql-connect.php for more information.
so.. you change the action in service.php:
<form class="well-small" action="dispatch.php" method="POST" id="serviceModalForm" name="serviceModalForm">
Move to dispatch.php
<?php
if(isset($_POST['submit']))
{
$bol = (isset($_POST['bolNumber'])) ? $_POST['bolNumber'] : '';
$container = (isset($_POST['containerNumber'])) ? $_POST['containerNumber'] : '';
if (!empty($bol) && !empty($container))
{
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
// run the query here
print "<br/><br/>".$sql_query_string."<br/><br/>";
}
else { print "<br/><br/>empty values;<br/>"; }
}
else { print "<br/><br/>\$_POST info not received;<br/>"; }
?>
prints (after submit):
INSERT INTO import_view_svc_fail (bol, container_num) VALUES ('input one value', 'input two value');
you probably should check and make sure you got all your post values inside the if(isset($_POST['submit'])) statement, too. or re-work the logic as a whole... it depends if you want to allow blank values, too.
Also, read up on sql injection and why you should learn to use mysqli_ or pdo.

Creating a second login page that automatically logs in the user

I have a login page as follows:
<form action="?" method="post" id="frm-useracc-login" name="frm-useracc-login" >
<div id="login-username-wrap" >
<div class="login-input-item left">
<div class="div-search-label left">
<div id="div-leftheader-wrap">
<p class="a-topheader-infotext left"><strong>Username: </strong></p>
</div>
</div>
<div class="login-input-content left div-subrow-style ui-corner-all">
<input type="text" tabindex="1" name="txt-username" id="txt-username" class="input-txt-med required addr-search-input txt-username left">
</div>
</div>
</div>
<div id="login-password-wrap" >
<div class="login-input-item left">
<div class="div-search-label left">
<div id="div-leftheader-wrap">
<p class="a-topheader-infotext left"><strong>Password: </strong></p>
</div>
</div>
<div class="login-input-content left div-subrow-style ui-corner-all">
<input type="password" tabindex="1" name="txt-password" id="txt-password" class="input-txt-med required addr-search-input txt-password left">
</div>
</div>
</div>
<div id="login-btn-bottom" class="centre-div">
<div id="login-btn-right">
<button name="btn-login" id="btn-login" class="btn-med ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper left">Login</button>
<button name="btn-cancel" id="btn-cancel" class="btn-med ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper left">Cancel</button><br /><br />
</div>
</div>
</form>
And here my session.controller.php file:
Click Here
Basically, what I want to do is create a second login page that automatically passes the value to the session controller and logs in. For example, if I go to login-guest.php, I would put the default values for username and password and then have a jquery click event that automatically logs them in using $("#btn-login").trigger('click');
The problem is that the session controller automatically goes back to login.php if the session has timed out and I'm not sure how I could go about achieving this. Any help would be much appreciated!
As you've mentioned in your comment you have to know how user had logged in at the first place (login or login-guest), so you will need to have some sort of state for each user anyway.
Now if you can't increase session timeout to infinite, you probably need to store login type some where else like in cookies, or as query string in your urls.
In the case of cookie it will be something like this:
In login section of your login-guest.php:
...
$expire = 60 * 60 * 24 * 30 * 24 + time(); // 2 years
setcookie('logintype', 'guest', $expire);
And this where you send user to login page:
if(isset($_COOKIE['logintype']) && $_COOKIE['logintype']=='guest'){
header('Location: login-guest.php');
} else {
header('Location: login.php');
}
I don't think cookies can have infinite life, so I've set expiry to two years which you can change. Obviously It won't persist if user deletes cookies or use another browser.
You should solve your problem with an extra field on each login form with the login type (eg: registered, guest), and with this value do the desired redirect or any other logic you need?
You can also keep this login type at the session/cookie for further usage.
You could add a simple hidden input to each form:
<input type="hidden" name="login_type" value="guest" />
You would then redirect depending upon which type of login is performed:
if($_POST['login_type'] == 'guest') {
header('Location: login-guest.php');
}
else {
header('Location: login.php');
}
Of course there are nicer solutions, and you should always filter inputs etc, but for simplicity there you go.

Categories