Form does not go to action page on submit - php

Edit 2: I traced the code through the php, and realized that it was a faulty header that was causing it to bounce back. I've fixed the header and now the form behaves as it should. Thanks everyone for your help.
EDIT: I noticed the form is quickly refreshing when I submit, so I think it is going to the action page (createlist.php) and immediately bouncing back, so there must be some issue there. Here is the code for createlist.php:
<?php
if (!isset($_SESSION)) {
session_start();
}
if (!defined(__DIR__)) {
define(__DIR__, dirname(__FILE__));
}
require_once(__DIR__.'/../config.php');
//Connect to server and select database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Cannot connect to server');
//mysql_select_db(DB_DATABASE) or die('Cannot select database');
$tbl_name = 'lists'; //Table name
//Retreive data from form
$listname = $_POST['listName'];
$admin_id = $_SESSION['SESS_MEMBER_ID'];
$listtype = 'list';
//Create listname session variable for catinit.php
$_SESSION['listname'] = $listname;
//Insert new row
$sql = "INSERT INTO $tbl_name(admin_id, listname, listtype) VALUES ('$admin_id', '$listname', '$listtype')";
$result = mysqli_query($link, $sql);
if ($result) {
header("location: catinit.php");
} else {
die("Could not create list");
}
//mysql_close();
?>
I have 2 forms on a page, and while it was working before, since adding the backend handling of the information it has broken. Now when I submit either of the forms on the page nothing happens, it does not even attempt to load the action pages. I am completely lost as to what is stopping it from submitting, as everything looks like its working.
<h1>Create a New List</h1>
<form action = "createlist.php" method = "POST" id = "formId" onsubmit = "formValidate(0, 0, 0, 1, 'formId', 'submitError', event)">
<p>List Name:
<input type = "text" id = "listName" name = "listName" placeholder = "New List" onblur = "listNameValidate('listName','errorName1')" required><span class = "error" id = "errorName1"></span></p>
</form>
<h2>Categories</h2>
<ul class = "catList" id = "list">
<table>
<?php
$cats = array('Produce', 'Meat/Dairy', 'Baked Goods', 'Dry/Canned Goods', 'Household Items');
//Check to see if Session version of array has different values
if (isset($_SESSION['catArray']) && $_SESSION['catArray'] != $cats) {
$cats = $_SESSION['catArray'];
} else {
$_SESSION['catArray'] = $cats;
}
foreach ($cats as $cat) {
$index = array_search($cat, $cats);
echo '<tr><td><li>'.$cat.'</li></td><td> Remove</td></tr>';
}
?>
</table>
</ul>
New Category: <br>
<form action = "addcat.php" method = "POST" id = "addcat">
<input type = "text" id = "newCategory" name = "newCat" placeholder = "Category name" onblur = "listNameValidate('newCategory','errorName2')">
<input type = "hidden" name = "catArray" value = "<?php echo htmlentities(serialize($cats)); ?>" >
<input type = "submit" value= "Add" class = "add"><span class = "error" id = "errorName2"></span>
</form>
<h2>Invite Members</h2>
Add a new Member: <br>
<input type = "email" id = "email" name = "Email" placeholder = "Email Address" onblur = "emailValidate('email', 'errorEmail')">
<input type = "button" value = "Add" class = "add" ><span class = "error" id = "errorEmail"></span>
<p><input type = "submit" form = "formId" value = "Create"></p>
<p class = "submitError" id = "submitError"></p>

Related

User value used instead of PHP value in textbox

I have a webpage thats purpose is to edit entries from a database. Its populated using PHP but i need the user to be able to change the value in these and update the database with the new value.
The problem im having is when i POST the data back from the form to the data base, the new information is NOT used, instead the PHP is. How do i fix this?
Each dropdown, text box and text field is populated from the text box using php:
<div class="col-lg-6">
<div class="form-group">
<label>Version</label>
<input type="text" class="form-control" name="forensic_tool_version" placeholder="Version" value="<?php
$session_name = $_SESSION['first_name']." ".$_SESSION['surname'];
$sql_query = "SELECT fi_forensic_tool_ver FROM asset_tracker WHERE asset_id = ? LIMIT 1";
$db_field = "fi_forensic_tool_ver";
$asset_id = $_GET['assetid'];
get_db_field($mysqli, $sql_query, $db_field, $asset_id, $session_name);
?>"/>
</div>
The get_db_field just gets the data and echos it to screen. This all works.
The user will then change one or more fields and click submit, where the following update will occur:
<!-- DATABASE INPUT - Input form elements into database -->
<?php
if(!empty($_GET['requestor']) ){
$asset_id = $_GET['assetid'];
$add_requestor = $_GET['requestor'];
$add_kc_number = $_GET['kc_number'];
$add_project_name = $_GET['project_name'];
$add_custodian = $_GET['custodian'];
$add_business_area = $_GET['business_area'];
$add_task = $_GET['task'];
$add_utl_reference = $_GET['utl_reference'];
$add_purchase_price_value = $_GET['purchase_price_value'];
$add_request_date = $_GET['request_date'];
$add_return_date = $_GET['return_date'];
$add_device_type = $_GET['device_type'];
$add_manufacturer = $_GET['manufacturer'];
$add_username = $_GET['username'];
$add_model = $_GET['model'];
$add_pinOrPassword = $_GET['pinOrPassword'];
$add_vf_asset_num = $_GET['vf_asset_num'];
$add_serial_num = $_GET['serial_num'];
$add_imei = $_GET['imei'];
$add_forensic_tool = $_GET['forensic_tool'];
$add_forensic_tool_version = $_GET['forensic_tool_version'];
$add_bitlocker_key = $_GET['bitlocker_key'];
$add_image_verified = $_GET['image_verified'];
$add_case_notes = $_GET['case_notes'];
$add_case_photos = $_GET['case_photos'];
if($query = $mysqli->prepare("UPDATE asset_tracker SET ci_requesting_employee=?, ci_kc=?, ci_project_name=?, ci_custodian=?, ci_business_area=?, ci_task=?, ci_utl_reference=?, ci_purchase_price_value=?, ci_date_requested=?, ci_date_returned=?, di_type=?, di_manufacturer=?, di_model=?, di_username=?, di_password=?, di_vf_asset=?, di_serial=?, di_imei=?, fi_forensic_tool=?, fi_forensic_tool_ver=?, fi_bitlocker_key=?, fi_image_verified=?, cn_notes=?, cn_photos=? WHERE asset_id = ? LIMIT 1")){
$query->bind_param('ssssssssssssssssssssssssi', $add_requestor, $add_kc_number, $add_project_name, $add_custodian, $add_business_area, $add_task, $add_utl_reference, $add_purchase_price_value, $add_request_date, $add_return_date, $add_device_type, $add_manufacturer, $add_username, $add_model, $add_pinOrPassword, $add_vf_asset_num, $add_serial_num, $add_imei, $add_forensic_tool, $add_forensic_tool_version, $add_bitlocker_key, $add_image_verified, $add_case_notes, $add_case_photos, $asset_id);
$query->execute();
$query->close();
echo "<script type='text/javascript'>alert('Asset updated Successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('Cannot access database');</script>";
}
}else{
//echo "<script type='text/javascript'>alert('Post not set');</script>";
}
?>
Any help on this would be much appreciated!
Thanks!

Performing OOP style in Login System

I know my question is easy to anyone. Just learning this PHP almost one month. I tried to perform my login system using OOP style. Where I need to login as a default user where the username and password is admin. When I tried to login it's saying object not found.
So here my code below.
Table:
CREATE TABLE loginmodule
(
loginId INT PRIMARY KEY AUTO_INCREMENT,
loginUsername VARCHAR(50),
loginPassword VARCHAR(50)
)
Here is my login script.
loginMe.php
<?php
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
require_once('../process/createProcess.php');
?>
<!doctype html>
<html>
<head>
<title>Login Frame</title>
</head>
<body>
<div id = "container">
<h1>Login</h1>
<form action = "post" action = "../process/createProcess.php">
<div class = "form-field">
<input type = "text" id = "username" name = "loginUsername" placeholder = "Enter Username">
</div>
<div class = "form-field">
<input type = "password" id = "password" name = "loginPassword" placeholder = "Enter Password">
</div>
<div class = "form-field">
<input type = "submit" id = "submit" name = "submit" value = "Login">
</div>
</form>
</div><!--- end container --->
</body>
</html>
So I set aside my CRUD in another file.
loginCRUD.php
<?php
error_reporting(0);
class CRUD
{
public function readLogin($dbusername,$dbpassword)
{
global $myDatabase;
$result = $myDatabase->query("SELECT * FROM loginmodule WHERE loginUsername = '$dbusername' AND loginPassword = '$dbpassword'");
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
return $row;
}
}
}
?>
Last where I set aside also my process where my validation happens.
createProcess.php
<?php
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
session_start();
$dbusername = $_POST['loginUsername']; //Get the value from textfield.
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword))
{
if($loginUsername == $dbusername && $loginPassword == $dbpassword)
{
$create = loginCRUD::readLogin($dbusername,$dbusername);
echo "You are logged in!";
#$_SESSION['loginUsername'] = $loginUsername;
}
}
?>
Guide me if I missed something. If there's a shortcut style than this let me know :)
There are several errors in your code, such as:
There are two action attribute in your form tag.
<form action = "post" action = "../process/createProcess.php">
^ ^
It should be,
<form method="post" action="../process/createProcess.php">
On createProcess.php page, look at the following lines,
1) if($loginUsername == $dbusername && $loginPassword == $dbpassword)
^ ^
There are no variables named $loginUsername and $loginPassword
2) $create = loginCRUD::readLogin($dbusername,$dbusername);
^ ^
both the arguments are same
You're calling readLogin() method in a wrong way. You should first create an instance of class CRUD and then call it's instance method readLogin(), like this way:
(new CRUD)->readLogin($dbusername,$dbpassword);
3) $_SESSION['loginUsername'] = $loginUsername;
As I said, there is no variable named $loginUsername. It should be,
$_SESSION['loginUsername'] = $dbusername;
Always start session at your very top of your PHP script, right after the opening PHP tag, like this:
<?php
session_start();
// your code
Your query is susceptible to SQL injection. Use prepared statements for mysqli to prevent any kind SQL injection. And this is how you can prevent SQL injection in PHP.
Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
Suggestion: Don't use global in your code. Why Globals are evil?
So your code should be like this:
CRUD class:
class CRUD{
public function readLogin($dbusername,$dbpassword){
global $myDatabase;
$statement = $myDatabase->prepare("SELECT * FROM loginmodule WHERE loginUsername = ? AND loginPassword = ? LIMIT 1");
$statement->bind_param("ss", $dbusername, $dbpassword);
if($statement->execute()){
$result = $statement->get_result();
if($result->num_rows){
$row = $result->fetch_assoc();
return $row;
}else{
return false;
}
}else{
return false;
}
}
}
createProcess.php
if(isset($_POST['submit'])){
$dbusername = $_POST['loginUsername'];
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword)){
if((new CRUD)->readLogin($dbusername,$dbpassword)){
echo "You are logged in!";
$_SESSION['loginUsername'] = $dbusername;
// redirect the user to the home page
}else{
echo "Incorrect username and/or password";
}
}
}
HTML
<div id = "container">
<h1>Login</h1>
<form method = "post" action = "../process/createProcess.php">
<div class = "form-field">
<input type = "text" id = "username" name = "loginUsername" placeholder = "Enter Username">
</div>
<div class = "form-field">
<input type = "password" id = "password" name = "loginPassword" placeholder = "Enter Password">
</div>
<div class = "form-field">
<input type = "submit" id = "submit" name = "submit" value = "Login">
</div>
</form>
</div>

Cannot add values in Database using PHP

I am currently doing a project in adding values using database but I seem to have a problem. I am sure that my query is correct since I tried adding it manually in mysql. Only some of the fields seem to be able to get what I input. I get the error
"Error: INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row) VALUES ('', '', '', 'White', '', '5', '', 'C', 'C')"
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "gracydb";
if (isset($_POST['addInventory']))
{
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
$sql = "INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row)
VALUES ('$itemcode', '$datereceived', '$fabric', '$details', '$measurement', '$amount', '$order', '$section', '$row')";
if (mysql_query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($conn);
}
mysql_close($conn);
//header ('Location: .php');
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
Item Code: <input type = "text" name = "itemcode"><br>
Date Received: <input type = "date" name = "inventoryDateReceived"><br>
Type of Fabric: <input type = "text" name = "fabric"><br>
Unit of Measurement:
<select name = "measurement">
<option value = "Grams">Grams</option>
<option value = "Kilograms">Kilograms</option>
</select><br>
Amount: <input type = "number" name = "amount"><br>
Assigned Order/Use: <input type = "text" name = "order"><br>
Section: <input type = "text" name = "section"><br>
Row: <input type = "text" name = "row"><br>
<input type = "submit" value = "submit" name = "addInventory">
</form>
These indexes not matched with your input form names:
$_POST['itemCode']
$_POST['dateReceived']
$_POST['typeOfFabric']
These should be:
$_POST['itemcode']
$_POST['inventoryDateReceived']
$_POST['fabric']
Check your form inputs:
<input type = "text" name = "itemcode">
<input type = "date" name = "inventoryDateReceived">
<input type = "text" name = "fabric">
I don't see any sense in this part of the code:
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
Your are just setting values (if isset) to new variables - but if they not exists you will still use undefined variables. Also there is no escaping to prevent sql-injections and validation of the given values!
I think you will get this error because of a missing variable.

no response when form is sent

I am trying to crewate a form fro listing databases on mysql, select one from the radio list and create a table with required parameters but it acts like it isn't even submitting. I see the url change but my code isn't running at all.
This is the form data:
SELECT DATABASE TO WORK WITH
<form action = "createtable.php" action = "post">
<?php
$query = "SHOW DATABASES";
$result = mysql_query($query, $connect);
if(!$result){echo mysql_error(); var_dump($result);
var_dump($connect); var_dump($query);}
while ($row = mysql_fetch_array($result))
{echo '<input type = "radio" name = "db"/>' . $row[0] . "<br>";}
?>
<input type = "text" name = "text" />
<input type = "submit" name = "submit" value = "submit" />
</form>
and the code to execute is:
<?php
if(isset($_POST['submit'])){
echo 'submit done';
$db = $_POST['db'];
$query = "USE $db";
$result = mysql_query($query, $connect);
if(!$result){echo 'no' . mysql_error();}
echo 'working';
$table = 'rio';
$id = 'id';
$idtype = 'int';
$idno = '11';
$staffmenu = 'staffmenu';
$stafftype = 'varchar';
$staffno = '255';
$null = 'NOT NULL';
$ai = 'auto_increment';
$key = 'id';
$query ="CREATE TABLE staff
($id $idtype($idno) $null $ai,
$staffmenu $stafftype($staffno) $null,
subj varchar(255) NOT NULL,
PRIMARY KEY ($key))";
var_dump($query);
$result2 = mysql_query($query, $connect);
if(!$result2){echo mysql_error();}
//session_destroy();
}
?>
i tried to use a different variable to trigger the code asides submit but that didn't work either. Any help will be appreciated. I am also aware of the deprecation of mysql, but i'm not totally sure how to migrate to mysqli so please bear with me.
To post your form you need method = "post" instead of action = "post"
<form action = "createtable.php" method = "post">
instead of
<form action = "createtable.php" action = "post">
Also, You need to add the value in your radio input as well,
echo '<input type = "radio" name = "db" value="'.$row[0].'" />' . $row[0] . "<br>";
Change your form's method type to post
you haven't mentioned your form's submission type

$_POST array empty php update fails

I am trying to build admin side of small website which consists of 2 pages: index.php and update php. On index.php I run query, that per-fills html form with data from database, which works fine.
Then I send data via $_POST to update.php page, where I try to get those values into variables and then make an update query. Which fails. I suspect something is wrong with $_POST array - some values are messed up or empty, but I don't understand why.
Here is the code for index.php:
<?php
if (!isset($page_id)) {
echo " <p>Please select page to be edited:</p>";
$query = mysql_query("SELECT page_id, title FROM pages");
$res = mysql_fetch_array($query);
do {
printf("<p><a href='index.php?page_id=%s'>%s</a></p>", $res['page_id'], $res['title']);
} while ($res = mysql_fetch_array($query));
} else { $query = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'");
$res = mysql_fetch_array($query);
require_once 'parts/form.php';}
?>
This is code for update.php:
<?php
//Here I try to get POST values and assign them to variables for update
//Ths is validation that those values are not empty,
require_once 'parts/guard.php';
if (isset($_POST['page_id'])) {
$page_id = $_POST['page_id'];
}
if (isset($_POST['title'])) {
$title = $_POST['title'];
}
if ($title == '') {
unset($title);
}
if (isset($_POST['description'])) {
$description = $_POST['description'];
}
if ($description == '') {
unset($description);
}
if (isset($_POST['keywords'])) {
$keywords = $_POST['keywords'];
}
if ($keywords == '') {
unset($keywords);
}
if (isset($_POST['text'])) {
$text = $_POST['text'];
}
if ($text == '') {
unset($text);
}
//variables are set
require_once 'parts/meta.php';
?>
<?php
//Here is all the values exist, the query is executed.
//Obviousely this query works in phpmyadmin, but not here - some fields come empty or messed up????
if (isset($title) && isset($keywords) && isset($description) && isset($text) && isset($page_id)) {
$query = mysql_query("UPDATE pages SET title = '$title', description = '$description', keywords = '$keywords', text = '$text' WHERE page_id = '$page_id' ");
if ($query == TRUE) {
echo "<p>Page Updated</p>";
echo "<p><a href = 'http://localhost:8888/travel.ru/admin/index.php'>
Edit Another Page</a></p>";
} else {
echo "<p>Page Is Not Updataed</p>";
}
} else {
echo "<p>You Left Some Fields Empty. Page Will Not Be Updated.</p>";
}
?>
And this is the form I use:
<form name="update" action = "update.php" method= "post">
<p> Page Name<br>
<input value = "<?php echo $res['title']; ?>" type = "text" name = "title"></p>
<p> Page Description<br>
<input value = "<?php echo $res['description']; ?>" type = "text" name = "title"></p>
<p> Page Keywords<br>
<input value = "<?php echo $res['keywords']; ?>" type = "text" name = "title"></p>
<p> Page Content<br>
<textarea type = "text" name ="text" cols = "68" rows = "15"><?php echo $res['text']; ?>
</textarea></p>
<input type = "hidden" name="page_id" value =$res[page_id]>
<p><input type = "submit" name ="submit" value ="Save Changes" id="submit"</p>
</form>
Any help will be most appreciated as I dont have a clue why I have this problem?
Most of your form fields are named title. Thus you don't actually have a field called description or page_id or keywords.
Mate also raises a valid point.
Try added php tag to your input value
<input type = "hidden" name="page_id" value ="<?php echo $res['page_id']; ?>" />
As mentioned Amadan , also check the names for all controls in your form.

Categories