no response when form is sent - php

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

Related

Form does not go to action page on submit

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>

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.

Have 4 'ands' in a select statement

I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

$_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