PHP/MYSQL Log-in update troubles - php

I have been working on this Login script for awhile and everything works, except this update function. I have tried changing variable name and everything else. On UpdateUser.php, the code works if I insert variables instead of the $[POST] variables. I am at a loss. Any help would be greatly appreciated. Sorry for the messy code, this is a class assignment, so I wasn't worried about password security at the moment.
This is index4.php
<form id="form" action="index4.php" method="post">
<h2>Update Your Login</h2>
UserName:<br>
<input type="text" id="useuserName" required />
<br>
Password:<br>
<input type="text" id="usepassWord" required />
<br>
First Name:<br>
<input type="text" id="usefirstName" required />
<br>
Last Name:<br>
<input type="text" id="uselastName" required />
<br>
<input id="updateuser" type ="submit" />
</form>
<script>
$('#updateuser').click(function() {
var useID = $_SESSION["id"];
var useuserName = $("#useuserName").val();
var usepassWord = $("#usepassWord").val();
var usefirstName = $("#usefirstName").val();
var uselastName = $("#uselastName").val();
var usePermissions = $_SESSION["Permissions"];
$.ajax({
type : 'POST',
url : '',
data :{action:'updateuser', useID:useID, useuserName:useuserName, uselastName:uselastName, usePermissions:usePermissions},
error: function (html) {
alert( "What the duck" );
},
});
});
</script>
This is the UpdateUser.php file
<?php
//Update
if($_POST['action'] == 'updateuser'){
//Set Variables
$servername = "localhost";
$username = "root";
$password = "";
$db = "userdb";
//Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection: Failed! " . $conn->connect_error);
}
//Actual Code
$useID = $_POST['useID'];
$useuserName = $_POST['useuserName'];
$usepassWord = $_POST['usePassword'];
$usefirstName = $_POST['usefirstName'];
$uselastName = $_POST['uselastName'];
$usePermissions = $_POST['usePermissions'];
//Create Query
$sql = "UPDATE users SET userName = '$useuserName', Pass = '$usepassWord', firstName = '$usefirstName', lastname = '$uselastName', Permissions = '$usePermissions' WHERE id =" . $useID ."";
//Did it work Check
if ($conn->query($sql) === TRUE) {
echo "Cool";
} else {
echo "What " . $conn->error;
}
//Close Out
$conn->close();
}
?>

Related

Having PHP code in one page rather than two

I have a number of registration pages on my web application and a number of textboxes in a form that pushes the values enter to another php page which writes it to the database. The code for it looks like this
<form action = "submitEvent.php" method = "post">
Event Name: <br>
<input type = "text" name = "eventname" >
<br>
Event Type: <br>
<input type = "text" name = "eventtype" >
<br>
Charity Number: <br>
<input type = "text" name = "charityid" >
<br>
Contact Details: <br>
<input type = "text" name = "contactdetails" >
<br>
Location: <br>
<input type = "text" name = "eventlocation" >
<br>
Date : <br>
<input type ="date" name ="eventdate">
<br>
<input type = "submit" value = "Submit">
</form>
and then the submitEvent.php file looks like this
<?php
$eventname = filter_input(INPUT_POST, 'eventname');
$eventtype = filter_input(INPUT_POST, 'eventtype');
$charitynumber = filter_input(INPUT_POST, 'charityid');
$contactdetails = filter_input(INPUT_POST, 'contactdetails');
$eventlocation = filter_input(INPUT_POST, 'eventlocation');
$eventdate = filter_input(INPUT_POST, 'eventdate');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
//Create new connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT
INTO event (eventname, eventtype, charityid, contactdetails, location, date) VALUES ('$eventname', '$eventtype', '$charitynumber', '$contactdetails', '$eventlocation', '$eventdate')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
?>
Is there an easier way to do this as I have a number of pages like this? Would I be able to put it into one page?
Yes, it is possible to have all this in one page. You can use isset($_POST) to check if there is data available and then process it.
But modulation (having separate files) makes it easy. It helps to debug when you have php and html codes in diff files.
You can check if the form is submitted or not and act accordingly.
To check if you the form is submitted you can check if $_POST['Submit'] is set.
<?php
if(isset($_POST['Submit'])){
/* PHP code here */
}
?>
<!-- And point the form to submit to itself. -->
<form action="thisPage.php" method="post">
<!-- Rest of form here -->
The most basic way is add a hidden field to your form and on the form page check for that in php.
HTML
<form action = "form_page.php" method = "post">
<input type="hidden" name="submitted" value="1">
.....
</form>
PHP:
<?php
if(isset($_POST["submitted"])){
/*PHP processing code goes here*/
}
?>

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

How possibly HTML files to retrieve database from MYSQL (using php on the server)?

I want to create form in HTML files. let say it calls index.html ( client will see this page), and the HTML will be included some ajax codes where it links to php (server connect to Mysql)
So that client can do (insert delete edit) to database by inserting form in the index.html. How possibly to do that?. Please give me a simple code so that I can learn. Thank you so much. I found that PHP can link to others php to retrieve the data. But I would love to use HTML instead ,to link to php on the server.
Thank you so much.
edited code
enter code here (this is index.html)
<html>
<head>
<title>Submit Form Using AJAX PHP and javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var contact = document.getElementById("contact").value;
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if (name == '' || email == '' || password == '' || contact == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "https://../test2.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}</script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<h2>Submit Form</h2>
//div starts here
<form id="form">
<h3>Fill Your Information!</h3>
<div>
<label>Name :</label>
<br/>
<input type="text" id="name" /><br/>
<br/>
<label>Email :</label>
<br/>
<input type="text" id="email"/><br/>
<br/>
<label>Password :</label>
<br/>
<input type="password" id="password" /><br/>
<br/>
<label>Contact No :</label>
<br/>
<input type="text" id="contact" /><br/>
<br/>
<input type="button" id="submit" onclick="myFunction()" value="Submit"/>
</div>
</form>
<div id="clear"></div>
</div>
</body>
</html>
and this is the php.
//Fetching Values from URL
$name2 = $_POST['name1'];
$email2 = $_POST['email1'];
$password2 = $_POST['password1'];
$contact2 = $_POST['contact1'];
$servername = "localhost";
$username = "user";
$password = "userpwd";
$dbname = "dbname";
// Establishing connection with server..
$dbc = mysqli_connect($servername, $username, $password , $dbname)
or die('Error connecting to MySQL server.');
// Selecting Database
if (isset($_POST['name1'])) {
//Insert query
$query = mysqli_query("insert into form_element(name, email, password, contact) values ('$name2', '$email2', '$password2','$contact2')");
echo "Form Submitted succesfully";
}
//connection closed
mysqli_close($dbc);
?>
I don't get it work.
I don't have all the div's you had in there before, but you should be able to add them!
This should work once you put in the right username, password and database name in connection.php
If this doesn't work or isn't what you wanted, please let me know!
This is also up and running at http://emmetstudios.com/form, if you want to see it in operation.
Here's the code, (put it all in the same folder, different files):
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
success.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$password = $conn->real_escape_string($_POST['password']);
$contact = $conn->real_escape_string($_POST['contact']);
$query = "INSERT into form_element (name,email,password,contact) VALUES('" . $name . "','" . $email . "','" . $password . "','" . $contact . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Successful!";
$conn->close();
?>
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form id="form" action="success" method="post" onsubmit="return validateForm()" name="upload">
Name:<br>
<input type="text" name="name"> <br><br>
Email:<br>
<input type="text" name="email"> <br><br>
Password:<br>
<input type="password" name="password"> <br><br>
Phone Number:<br>
<input type="text" name="contact"> <br><br>
<input id="submit" type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
var contact = document.forms["form"]["contact"].value;
if (contact == "") {
alert("contact must be filled out");
return false;
}
}
</script>
</body>
</html>

Fetch and insert data into mysql using angularjs

I am unable to connect insert the date into sql server using angularjs & php.
I want to know how to insert data in sql and fetch the data from db.
<body>
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<input type="button" value="submit" ng-click="insertdata()"/> <br/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
var app = angular.module('myapp',[]);
app.controller('empcontroller', function($scope, $http){
$scope.insertdata=function(){
$http.post("insert.php",{'emp_no':$scope.emp_no,'first_name':$scope.first_name,'last_name':$scope.last_name,'dept_name':$scope.dept_name})
.success(function(data,status,headers,config){
console.log("data insert succesfully");
});
}
});
</script>
</body>
PHP CODE:
$data = json_decode(file_get_contents("php://input"));
$empno = mysql_real_escape_string($data->emp_no);
$fname = mysql_real_escape_string($data->first_name);
$lname = mysql_real_escape_string($data->last_name);
$dept = mysql_real_escape_string($data->dept_name);
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("company", $con);
mysql_query("INSERT INTO employee('emp_no', 'first_name', 'last_name', 'dept_name')VALUES('".$empno."','".$fname."','".$lname."','".$dept."')");
Here You go Try this
HTML
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<button ng-click="postData()">Submit</button><br>
</form>
</div>
CONTROLLER:
app.controller('empcontroller', function ($scope, $http) {
/*
* This method will be called on click event of button.
*/
$scope.postData = function () {
var request = $http({
method: "post",
url: window.location.href + "insert.php",
data: {
emp_no: $scope.emp_no,
first_name: $scope.first_name,
last_name: $scope.last_name,
dept_name: $scope.dept_name,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
PHP CODE:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$emp_no = $request->emp_no;
$first_name = $request->first_name;
$last_name = $request->last_name;
$dept_name = $request->dept_name;
$servername = "localhost";
$username = "root";
$password = "root"; //Your User Password
$dbname = "myDB"; //Your Database Name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO employee (emp_no, first_name, last_name, dept_name)
VALUES ($emp_no, $first_name, $last_name , $dept_name)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Three problems with your code:
When executing $scope functions with ng-click, best practice is to pass in the variables as you use them.
Since your PHP controller is expecting JSON, you should form a JSON object and indicate it in the headers.
.success() is being deprecated. You should use the promise .then() instead.
HTML:
<!-- need to pass model in the ng-click function -->
<input type="button" value="submit" ng-click="insertdata(emp_no, first_name, last_name, dept_name)"/>
Controller:
$scope.insertata = function(empNo, firstName, lastName, deptName) {
//make json payload object
var payload = {
emp_no: empNo,
first_name: firstName,
last_name: lastName,
dept_name: deptName
};
//pass to API
$http.post('insert.php', payload, {
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function(data, status, headers, config) {
//success
}, function(data, status, headers, config) {
//an error occurred
});
}
well, using the code of KKKKKKKK now you need a php code.
To retrieve information from a json file posted using post to php you should do something like this:
$json = file_get_contents('php://input');
$obj = json_decode($json); // this will retrieve the json.
And now manipulate as you want.

Trying to add items to a database using php

I am trying to a items to my database (sql) using php and a form, however the data is not being added and nothing seems to happening i just stay on the create.php page.
php code
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "PolyTest";
// Create connection
$conn = mysql_connect($servername, $username, $password);
mysql_select_db($dbname)
$doorName = $_POST['doorName'];
$doorDes = $_POST['doorDes'];
$doorPrice = $_POST('doorPrice');
$doorColour = $_POST('doorColour');
$doorImage = $_POST['doorImage'];
if(!$_POST['submit']){
echo "please fill in the boxs";
header('Location: dooradd.php');
} else {
mysql_query("INSERT INTO Doors ('ID', 'name', 'description', 'price', 'colour', 'image') VALUES(NULL, '$doorName', '$doorDes', '$doorPrice', '$doorColour', '$doorImage')") or die(mysql_error());
echo "Door been added!";
header('Location: doorlist.php');
}
?>
HTML FORM
<form class="add" action="doorCreate.php" method="post">
<input type="text" name="doorName" value="doorName">
<input type="text" name="doorDes" value="doorDes">
<input type="text" name="doorPrice" value="doorPrice">
<input type="text" name="doorColour" value="doorColour">
<input type="text" name="doorImage" value="doorImage">
<input type="submit" name="submit">
</form>
change mysql_select_db($dbname) with mysql_select_db($dbname);
and change;
$doorPrice = $_POST('doorPrice');
$doorColour = $_POST('doorColour');
with
$doorPrice = $_POST['doorPrice'];
$doorColour = $_POST['doorColour'];

Categories