Hello I am working with a predefined template and I am trying to fetch some data from the input space in form of POST/GET request using php. But I am unable to do so, How can I integrate the database and handle the php parameters?
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
?>
}
Hello change your code to this
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</div>
For the database connection it depends on which database you are working with but you can start here. A simple Google query with provide you what you are looking for
I put together an example for you that may come in handy. This shows how you can use PHP to submit a form print some values that the user enters on the page. I also included some commented out code that you can copy and move to a seperate script and call by changing the action value to the file path.
The PHP script:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
$data = [
"BOB" => "AWESOME",
"JOE" => "AVERAGE",
"TOM" => "COOL"
];
}
?>
Next, we have the form. I added this form because you need it to submit to the page. (Well you don't "need" it but it makes life easy.)
<div class="container">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Adhaar"
name="adhaar"
required
value="<?= isset($_POST['adhaar']) ? $_POST['adhaar'] : '' ?>">
</div>
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Town/City"
name="city"
required
value="<?= isset($_POST['city']) ? $_POST['city'] : '' ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">CLICK ME!</button>
</div>
</form>
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
</div>
Last piece of the file simply outputs information onto the page if it finds it in the $_POST global array.
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
This commented out part here you can use to pull data from the database and pass it back to your page. If you are just starting it's cool to tinker but ideally you DO NOT want to make calls to the db on the same page as your view. It should live in it's own file.
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
You should Try This Code ..This is working i Simply add a submit button to it
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<form method="GET" action="xxx.php">
<input type="text" placeholder="Adhaar" name="Adhaar" required="" />
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="" />
<input type="submit" name="submit" value="show">
<?php
if(isset($_GET['submit']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</form>
</div>
Related
I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>
I have a form that users can utilize to introduce some data to create a badge. I'm using session so that i can keep like a little history list for the users, and also if they click on one element from that list the data will be sent to the form automatically. My problem is that when i click on one element from the list a new row is inserted containing the same data, and also if i complete the form with identical data that i already have in my list again it creates another line containing the same data that i already have once. Can i do something so that my history list to contain only unique values, basically to not have the same line multiple times.
This is my code for the form:
<form method="get" autocomplete="off">
<h3>Creaza ecuson</h3>
<label>
Nume:<br><input type="text" name="nume" id="nume" required value="<?php echo $search->nume ?>"><br>
Prenume:<br><input type="text" name="prenume" id="prenume" required value="<?php echo $search->prenume ?>"><br>
Sex:<br><div class="autocomplete" style="width:300px;">
<input id="sex" type="text" name="sex" required value="<?php echo $search->sex ?>">
</div><br><br>
Rol:<br><div class="autocomplete" style="width:300px;">
<input id="rol" type="text" name="rol" required value="<?php echo $search->rol ?>">
</div><br><br>
Culoare text:<br><input type="color" name="cul" id="cul" value="<?php echo $search->cul ?>"><br><br>
Font ecuson:<br><div class="autocomplete" style="width:300px;">
<input id="font" type="text" name="font" required value="<?php echo $search->font ?>">
</div><br><br>
Format ecuson (portrait or landscape):<br><div class="autocomplete" style="width:300px;">
<input id="format" type="text" name="format" required value="<?php echo $search->format ?>">
</div><br><br>
</label>
<input type="submit" name="history" value="History" />
<button type="button" onclick="create()">Creaza</button><br><br>
</form>
My session code:
<?php
session_start();
$search = parseRequest();
storeSearch($search);
include "form.php";
$searches = $_SESSION['searches'];
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty()) {
$_SESSION['searches'][] = $search;
}
}
function parseRequest() {
$search = new SearchRequest;
$search->nume = !empty($_GET['nume']) ? $_GET['nume'] : "";
$search->prenume = !empty($_GET['prenume']) ? $_GET['prenume'] : "";
$search->sex = !empty($_GET['sex']) ? $_GET['sex'] : "";
$search->rol = !empty($_GET['rol']) ? $_GET['rol'] : "";
$search->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$search->font = !empty($_GET['font']) ? $_GET['font'] : "";
$search->format = !empty($_GET['format']) ? $_GET['format'] : "";
return $search;
}
/**
* search request
*/
class SearchRequest
{
public $nume = "";
public $prenume = "";
public $sex = "";
public $rol = "";
public $cul = "";
public $font = "";
public $format = "";
function toQueryString() {
$params = [
'nume' => $this->nume,
'prenume' => $this->prenume,
'sex' => $this->sex,
'rol'=> $this->rol,
'cul'=> $this->cul,
'font'=> $this->font,
'format'=> $this->format
];
return http_build_query($params);
}
function isEmpty() {
return !$this->nume || !$this->prenume || !$this->sex || !$this->rol || !$this->cul || !$this->font || !$this->format;
}
}
?>
And the so called history code:
<?php
foreach ($searches as $s) {
?>
<li><a href="creare.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->nume?> - <?php echo $s->prenume?> - <?php echo $s->sex?> - <?php echo $s->rol?> - <?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?>
</a></li>
<?php
}
?>
I don't think the script with the autocomplete function needs to be posted here for the question that i asked. If needed i will provide.
perhaps something as simple as
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty() && !in_array($search,$_SESSION['searches') {
$_SESSION['searches'][] = $search;
}
}
Building on CFP Support's answer, here's a slightly different approach to how I would create the form and handler. It's very similar to yours but I structured the logic a bit differently. I only added 3 fields from your form but you can easily add the remaining fields.
Fiddle - http://phpfiddle.org/lite/code/354t-6sgn
<?php
session_start();
// Initialize the cart if it needs it.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Should we show cart?
$showCart = isset($_GET['cart']) && $_GET['cart'] === 'true';
// Should we clear the cart?
if (isset($_GET['clear']) && $_GET['clear'] === 'true') {
$_SESSION['cart'] = [];
}
// Grab the current cart.
$cart = $_SESSION['cart'];
// The form was submitted
if (isset($_POST['submit'])) {
// Copy the POST data into a variable so we can modify it without side effects.
$formData = $_POST;
// Remove the submit button from the form data
unset($formData['submit']);
// Check if it is in the cart already.
if (!in_array($formData, $cart)) {
// If not, then add it.
$cart[] = $formData;
}
// Store the cart in the session.
$_SESSION['cart'] = $cart;
}
?>
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form method="post" autocomplete="off">
<h3>Creaza ecuson</h3>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="nume">Nume:
<input type="text" name="nume" id="nume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="prenume">Prenume:
<input type="text" name="prenume" id="prenume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="sex">Sex:
<input type="text" name="sex" id="sex" class="form-control" required>
</label>
</div>
</div>
<button class="btn btn-primary" name="submit" type="submit">Create</button>
<?php
// Toggle show/hide history
if ($showCart) { ?>
<a class="btn btn-primary" href="?" role="button">Hide Cart</a>
<?php } else { ?>
<a class="btn btn-primary" href="?cart=true" role="button">Show Cart</a>
<?php }
// If the cart is not empty, allow user to clear it.
if (!empty($cart)) { ?>
<a class="btn btn-primary" href="?clear=true" role="button">Clear Cart</a>
<?php }
?>
</form>
<?php
// Show the cart.
if ($showCart) {
echo '<pre>';
var_dump($cart);
echo '</pre>';
}
?>
</div>
</body>
</html>
Here's a way and little pseudo-code, you could implement something similar with your codebase.
The idea is, since from one computer only one person can sign up, store a unique ID for that person in session. Then when entering the data into session, check if that ID is present or not.
If it's present, do not add, if it's not, add.
Pseudo-code
$uniqueID = hash("sha256", $_SERVER['REMOTE_ADDR']); //generate a unique ID depending on IP since that would be unique for each computer
//insert into your session
if(!in($sessionHandler, $uniqueid)
{
//insert now
}
I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];
I am trying to create a form on wordpress that automatically updates a custom table in the database. The form works with the "POST" method and calls the PHP file fine, and any code (such as echos) I enter at the beginning work fine. The problem is every time I try and use the wpdb object, the screen is just white and the code stops. It won't run anything including or past where I call wpdb. I have tried both using insert and get results and neither is working. Also, I am getting absolutely no errors in the console output even though I turned debugging on and everything.
This is my php file (which has a permission value of 755):
<?php
global $wpdb;
error_reporting(E_ALL);
echo "New Plant has been submitted.\n";
$plantname = $_POST["name"];
echo "Before";
$myrows = $wpdb->get_results( "SELECT * FROM wp_users" );
exit( var_dump( $wpdb->last_query ) );
echo " After: " . $myrows;
$wpdb->insert('Plants',array('PlantName' => $plantname),array('%s'));
echo $plantname . " has been submitted.";
?>
</body>
</html>
Also, this is my form:
<form action="cgi-bin/add_plant.php" method="post">
Plant Name: <input name="name" type="text" />
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" />
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" />
Lowest Ideal pH: <input name="IdealpHLow" type="text" />
Highest Ideal pH: <input name="IdealpHHigh" type="text" />
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" />
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" />
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" />
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" />
<input type="submit" />
</form>
By the way, I know I need to sanitize my code, but for right now I just want to be able to get it to work in the first place. I know that nothing is getting added because I logged in to PHPMyAdmin and there is nothing in the table. I also tried getting results from the standard wp tables, but that failed as well.
Edit 1
I have moved everything into a custom template file. I had gotten it working with the separate php file, but I moved it so that I could do form validation and everything all without switching pages. However, now I am having the same error. I had used "require_once" to include wp-load.php in the original and it worked, however now wpdb is still failing and I can't figure out how to include wp-load without it also failing. Originally loading up the page works: I can submit the form however on submit the page fails.
<?php
require_once(ABSPATH . '/wp-config.php');
require_once(ABSPATH . '/wp-load.php');
?>
<?php global $asteria;?>
<?php
get_header();
?>
<?php global $wpdb;?>
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function selfURL()
{
$ret = substr(strtolower($_SERVER['SERVER_PROTOCOL']),0,strpos( strtolower($_SERVER['SERVER_PROTOCOL' ]), "/") );
$ret .= ( empty($_SERVER['HTTPS']) ? NULL : ( ($_SERVER['HTTPS'] == "on") ? "s" : NULL) );
$ret .= "://" . $_SERVER['SERVER_NAME'];
$ret .= ( $_SERVER['SERVER_PORT'] == 80 ? "" : ":".$_SERVER['SERVER_PORT'] );
$ret .= $_SERVER['REQUEST_URI'];
return $ret;
}
function submitPlant($a, $b, $c, $d, $e, $f, $g, $h, $i)
{
$wpdb->show_errors();
// $wpdb->replace('Plants',
// array(
// 'PlantName' => $a,
// 'IdealTempLow' => $b,
// 'IdealTempHigh' => $c,
// 'IdealPHLow' => $d,
// 'IdealPHHigh' => $e,
// 'IdealHumidityLow' => $f,
// 'IdealHumidityHigh' => $g,
// 'IdealMoistureLow' => $h,
// 'IdealMoistureHigh' => $i
// ),
// array(
// '%s',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f',
// '%f'
// )
// );
// $a = $wpdb->insert_id;
// if ($a == false) {
// $SubmitMsg = "Plant entry failed. Please contact system admin.";
// echo "Error: " . $wpdb->print_error();
// } else {
$SubmitMsg = "New Plant has been submitted.";
// }
return $SubmitMsg;
}
... Validation Functions...
?>
<?php
$PlantName = $IdealTempLow = $IdealTempHigh = $IdealpHLow = $IdealpHHigh = $IdealHumLow = $IdealHumHigh = $IdealMoistLow = $IdealMoistHigh = "";
$NameErr = $LTempErr = $HTempErr = $LpHErr = $HpHErr = $LHumErr = $HHumErr = $LMoistErr = $HMoistErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$SubmitMsg = "";
...Form Validation...
if (($NameErr == "") && ($LTempErr == "") && ($HTempErr == "") && ($LpHErr == "") && ($HpHErr == "") && ($LHumErr == "") && ($HHumErr == "") && ($LMoistErr == "") && ($HMoistErr == ""))
{
$SubmitMsg = submitPlant($PlantName, $IdealTempLow, $IdealTempHigh, $IdealpHLow, $IdealpHHigh, $IdealHumLow, $IdealHumHigh, $IdealMoistLow, $IdealMoistHigh);
}
}
?>
<!--Content-->
<div class="fixed_site">
<div class="fixed_wrap singlefx">
<?php if(($asteria['page_type_id']) == '1'){ ?>
<div class="page_tt">
<div class="center"><h1 class="postitle"><?php the_title(); ?></h1></div>
</div>
<?php } ?>
<div id="content">
<div class="center">
<div class="single_wrap no_sidebar">
<div class="single_post">
<?php if(have_posts()): ?>
<?php while(have_posts()): ?><?php the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<?php if ( is_user_logged_in() || is_admin() ) { ?><div class="edit_wrap"><i title="<?php _e('Edit This','asteria'); ?>" class="fa-edit"></i></div><?php } ?>
<div class="single_post_content">
<?php if(($asteria['page_type_id']) == '2'){ ?><h1 class="postitle"><?php the_title(); ?></h1><?php } ?>
<div class="thn_post_wrap"><?php the_content(); ?> </div>
<div style="clear:both"></div>
<div class="thn_post_wrap"><?php wp_link_pages('<p class="pages"><strong>'.__('Pages:').'</strong> ', '</p>', 'number'); ?></div>
</div>
</div>
<?php endwhile ?>
</div>
<?php endif ?>
<span style="color:blue"><?php echo $SubmitMsg;?></span>
<form action="<?php echo selfURL(); ?>" method="POST">
Plant Name: <input name="PlantName" type="text" value="<?php echo $PlantName;?>"/><span style="color:red"> * <?php echo $NameErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Temperature: <input name="IdealTempLow" type="text" value="<?php echo $IdealTempLow;?>"/><span style="color:red"> * <?php echo $LTempErr;?></span>
</br><div height="5"> </div>
Highest Ideal Temperature: <input name="IdealTempHigh" type="text" value="<?php echo $IdealTempHigh;?>"/><span style="color:red"> * <?php echo $HTempErr;?></span>
</br><div height="5"> </div>
Lowest Ideal pH: <input name="IdealpHLow" type="text" value="<?php echo $IdealpHLow;?>"/><span style="color:red"> * <?php echo $LpHErr;?></span>
</br><div height="5"> </div>
Highest Ideal pH: <input name="IdealpHHigh" type="text" value="<?php echo $IdealpHHigh;?>"/><span style="color:red"> * <?php echo $HpHErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Humidity Level: <input name="IdealHumLow" type="text" value="<?php echo $IdealHumLow;?>"/><span style="color:red"> * <?php echo $LHumErr;?></span>
</br><div height="5"> </div>
Highest Ideal Humidity Level: <input name="IdealHumHigh" type="text" value="<?php echo $IdealHumHigh;?>"/><span style="color:red"> * <?php echo $HHumErr;?></span>
</br><div height="5"> </div>
Lowest Ideal Moisture Level: <input name="IdealMoistLow" type="text" value="<?php echo $IdealMoistLow;?>"/><span style="color:red"> * <?php echo $LMoistErr;?></span>
</br><div height="5"> </div>
Highest Ideal Moisture Level: <input name="IdealMoistHigh" type="text" value="<?php echo $IdealMoistHigh;?>"/><span style="color:red"> * <?php echo $HMoistErr;?></span>
</br><div height="5"> </div>
<input type="submit" name="submitted"/>
</form>
</div>
<!--PAGE END-->
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];