I'm struggling with integrating recaptcha in multipage form - php

Background info:
I have made a test form containing multiple pages. When recaptcha isn't intergrated I receive the info in my database. But when trying to integrate recaptcha (checkbox v2) it keeps failing and the info isn't sent to the database no more. I have tried to intergrate recaptcha on page2.php because it's the last page of the form the user has to fill in. I left my recaptcha keys in because it's just made as test.
Question:
How can I make it work? How can I integrate recaptch in a correct way?
Thanks!
The included pages are:
footer.php
<!-- Bootstrap Javascript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>function goBack() {window.history.back();}</script>
<!-- recaptcha -->
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</html>
header.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('config.php');
require_once('functions.php');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Multi-Page Form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<!-- recaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
</div>
</nav>
index.php
<?php include_once('header.php'); ?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Questionnaire</h3>
<p> Beste user,</p>
<p> Please fill in form A or B</p>
<br>
<p>Form A</p>
<br>
<p>Form B</p>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page1.php
<?php include_once('header.php');?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 1/2</h3>
<form action="page2.php" method="post">
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
echo "<br>";
text('Firstname', 'Firstname', '<b>Firstname</b>', ' ');
echo "<br>";
?>
<br>
<br>
<center>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" type="submit">Continue »</button>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page2.php
<?php
include_once('header.php');
// Store data from page 1 in SESSION
if ( ! empty( $_POST ) ) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Firstname'] = $_POST['Firstname'];
}
// recaptcha
$public_key = "6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S";
$private_key = "6LdojMIUAAAAALhEfrQFR3jExbPLubKjys6CZL_9";
$url = "https://www.google.com/recaptcha/api/siteverify";
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 2/2</h3>
<form action="page3.php" method="post">
<?php
// choices for checkbox
$options = array(
'No ' => 'No ',
'Neutral ' => 'Neutral ',
'Yes ' => 'Yes ',
);
// choices for checkbox2
$options2 = array(
'Internet ' => 'Internet ',
'Friends ' => 'Friends ',
'Work ' => 'Work ',
'Other' => 'Other' ,
);
echo "<br>";
checkbox2( 'Info_media', 'Info_media', '<b>How do you know this?</b>', $options2 );
echo "<br>";
text_non_required('Other', 'Other', 'Explain "Other"?', ' ');
echo "<br>";
checkbox( 'Question_1', 'Question_1', '<b>Do you agree with the answer?</b>', $options );
echo "<br>";
text('Remark', 'Remark', 'Do you have remarks?', ' ');
?>
<br>
<br>
<center>
<!-- recaptcha -->
<div class="g-recaptcha" data-sitekey="<?php print $public_key; ?>"></div>
<br>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" name="submit_form" type="submit">Continue »</button>
<!-- recaptcha -->
<?php
/* Check if the form has been submitted */
if(array_key_exists('submit_form',$_POST))
{
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
/* if success */
if($response->success == 1)
{
header("Location: http://localhost/recaptcha_test/page3.php");
}
else
{
echo "You are a robot.";
}
}
?>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page3.php
<?php
include_once('header.php');
// Store data in session
if ( ! empty( $_POST ) ) {
$_SESSION['Info_media'] = $_POST['Info_media'];
$_SESSION['Other'] = $_POST['Other'];
$_SESSION['Question_1'] = $_POST['Question_1'];
$_SESSION['Remark'] = $_POST['Remark'];
}
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">You are done.</h3>
<br>
<br>
<center>Thank you.</center>
<br>
<?php
whitelist_convert_send ();
?>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
functions.php
<?php
function __($text) {
return htmlspecialchars($text, ENT_COMPAT);
}
function checked($value, $array) {
if ( in_array( $value, $array ) ) {
echo 'checked="checked"';
}
}
function text( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function text_non_required( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function email( $name, $id, $label, $placeholder, $type = 'email' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function checkbox( $name, $id, $label, $options = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options as $value => $title ) : ?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php }
function checkbox2 ($name, $id, $label, $options2 = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options2 as $value => $title) :
?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]"
value="<?php echo $value; ?>"
<?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>
>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php
}
function whitelist_convert_send () {
//globalise variables
global $Email;
global $Firstname;
global $Info_media;
global $Other;
global $Question_1;
global $Remark;
global $MCQ_0;
global $MCQ_1;
// Whitelist
$Email = $_SESSION['Email'];
$Firstname = $_SESSION['Firstname'];
$Info_media = $_SESSION['Info_media'];
$Other = $_SESSION['Other'];
$Question_1 = $_SESSION['Question_1'];
$Remark = $_SESSION['Remark'];
// arrays to value in string for performing statistics
foreach ($Info_media as $value) {
$MCQ_0 = $value;}
foreach ($Question_1 as $value) {
$MCQ_1 = $value;}
// Connectie database (naam server, gebruikersnaam, wachtwoord, naam database)
$conn = new mysqli('localhost', 'root', '', 'Wolf');
/*Testing databaseconnection
if ($conn){
echo "we are connected";}
else {
die ('database connection failed');} */
if (!$conn){ die ('database connection failed' . msqli_error ());}
$stmt = $conn->prepare("INSERT INTO test_database (Email, Firstname, Info_media, Other, Question_1, Remark) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $Email, $Firstname, $MCQ_0, $Other, $MCQ_1, $Remark);
// Execute
$insert = $stmt->execute();
// Einde sessie
session_destroy();
}

You probably misunderstood how recaptcha is working.
You integrate the recaptcha code (js + div) in your form
On the result page you check if the captcha check was sucessful (php)
Currently you are doing both things in page2.php. When this page is loading, it checks if recaptcha was successful, but the recaptcha was not even included and the user didn't had the opportunity to solve it yet :-)
So you should integrate it in page1 and check it in page2.
page1.php
Integrate the recaptcha div in your form
<form action="page2.php" method="post">
<div class="g-recaptcha" data-sitekey="6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"></div>
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
...
ofc you can integrate the site key with php too (like you have done it on page2.php) or change the position inside the form
page2.php
Remove the recaptcha div from this page.
The recaptcha success check should be somewhere in the beginning of this page. You should render the whole form only when $response->success == 1 succeed (see the attached code). This probably requires some additional restructuring of page2.php
<?php
//recaptcha check
$response_key = "";
//get submitted recaptcha "user response" from last page
if(array_key_exists('g-recaptcha-response',$_POST)){
$response_key = $_POST['g-recaptcha-response'];
}
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
if($response->success == 1){
//render form from page 2
?>
<form action="page3.php" method="post">
...
<?php
}
else{
echo "You are a robot.";
//
}
?>
As an alternative you could integrate recaptcha in page2.php and check the result in page3.php - it just depends in which step you want the recaptcha checkbox

Related

PHP Not supporitng UTF-8? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 7 years ago.
Hello i have been trying to make { View / edit / add Script }
which i got from google..
but the main issue is it's not supporting arabic language [UTF-8] encode
here is the code:
<?php
ini_set('default_charset', 'UTF-8');
setlocale(LC_ALL, 'UTF-8');
date_default_timezone_set('Asia/Riyadh');
error_reporting(0);
require 'database.php';
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$uidError = null;
$actionError = null;
$reasonError = null;
// keep track post values
$name = utf8_encode($_POST['Name']);
$uid = utf8_encode($_POST['uid']);
$action = utf8_encode($_POST['Action']);
$reason = utf8_encode($_POST['Reason']);
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($uid)) {
$uidError = 'Please enter UID';
$valid = false;
}
if (empty($action)) {
$actionError = 'Please enter action';
$valid = false;
}
if (empty($reason)) {
$reasonError = 'Please enter reason';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO clan187 (name,uid,action,reason) values(?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($name,$uid,$action,$reason,));
Database::disconnect();
header("Location: index.php");
}
}
?>
<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">
<br>
</div>
<form class="form-horizontal" action="create.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="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($uidError)?'error':'';?>">
<label class="control-label">UID</label>
<div class="controls">
<input name="uid" type="text" placeholder="UUID" value="<?php echo !empty($uid)?$uid:'';?>">
<?php if (!empty($uidError)): ?>
<span class="help-inline"><?php echo $uidError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($actionError)?'error':'';?>">
<label class="control-label">Action</label>
<div class="controls">
<input name="Action" type="text" placeholder="Action" value="<?php echo !empty($action)?$action:'';?>">
<?php if (!empty($actionError)): ?>
<span class="help-inline"><?php echo $actionError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($reasonError)?'error':'';?>">
<label class="control-label">Reason</label>
<div class="controls">
<input name="Reason" type="text" placeholder="Reason" value="<?php echo !empty($reason)?$reason:'';?>">
<?php if (!empty($reasonError)): ?>
<span class="help-inline"><?php echo $reasonError;?></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>
Well no idea why it's not working for me
any help will be great <3
You haven't said why it doesn't work. You may need to be more verbose.
Unless you specify it, forms are sent in the user's locale encoding. You need to set your form with an encoding. UTF-8 will allow characters from any region/language:
<form class="form-horizontal" action="create.php" method="post" accept-charset="UTF-8">
Now your $_POST[] elements will be already UTF-8 encoded, so you don't need to convert them. Change them to:
$name = $_POST['Name'];
$uid = $_POST['uid'];
$action = $_POST['Action'];
$reason = $_POST['Reason'];
Make sure the following is present in your file:
header('Content-type: text/html; charset=utf-8');
There's also a meta tag for in the document head.
meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
Make sure your data source/destination is collated for UTF-8.
Then the only other thing it could be is your text editor encoding. Should be UTF-8 without BOM. No matter what is going on in the file, if the file itself isn't UTF-8 then it won't work.

PHP MySQL not updating for CRUD app

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'];

Get an error by changing a post, simple php editing form

All!
I can't change a form I did. It is all functional on my local host (xampp), but when I upload on the server it doesn't work.
I believe the problem is on the query, the login is working so I don't think it's on the database connection or getting the data. I'm getting that $message = "Error"; on the else statement, I also tried to see if the form is working by echo $titulli; echo $content; and it worked.
I user error_reporting(E_ALL & ~E_NOTICE); and got these problems (warnings)
Warning: mysql_real_escape_string(): Access denied for user 'user'#'localhost' (using password: NO) in /home/user/public_html/test/admin-panel.php on line 12
Warning: mysql_real_escape_string(): A link to the server could not be established in /home/user/public_html/test/admin-panel.php on line 12
here is the code:
<?php
session_start();
include_once 'db_connect.php';
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysql_real_escape_string($id);
$titulli = $_POST['emri'.$id];
$titulli1=mysql_real_escape_string($titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysql_real_escape_string($content);
$date = date('Y-m-d H:i:s');
// echo $titulli;
// echo $content;
$update_query = "UPDATE `lagjja`.`content` SET `titulli` = '".$titulli1."', `content` = '".$content1."', `data` = '".$date."' WHERE `content` .`ID` = ".$id1;
$update_result = $mysqli->query($update_query);
if($update_result) {
$message = "you changes succeeded";
}
else {
$message = "Error";
//header('Location: index.php');
//die();
}
}
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
}
else {
echo "Your are not connected return to homepage";
header('refresh:2; url=index.php') ;
die();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta charset="UTF-8" />
<?php include("head.php"); ?>
<link rel="stylesheet" type="text/css" href="css/style-adminpanel.css" />
<title>Admin-panel</title>
</head>
<body>
<header>
logout
return to page
<div id="logo-postimit">
<img src="img/logo.png" alt="logo" />
</div>
</header>
<?php if(isset($message) && !empty($message) ) {
echo $message
;} ?>
<div id="content">
<div id="krejt-forma">
<?php
$post_query = "SELECT * FROM content LIMIT 3";
$result = $mysqli->query($post_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) : ?>
<!-- 2.1 tab section -->
<div class="forma col-lg-4 col-md-4 col-sm-12">
<form id="post-forma" role="form" name="post-form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?update=<?php echo $row['ID']; ?>">
<input class=" form-control titulli col-lg-12 col-md-12 col-sm-12 col-xs-12" type="text" id="emri<?php echo $row['ID']; ?>" name="emri<?php echo $row['ID']; ?>" placeholder="Titulli" value="<?php echo $row['titulli']; ?>" />
<textarea class="form-control mesazhi col-lg-12 col-md-12 col-sm-12 col-xs-12" rows="12" id="mesazhi<?php echo $row['ID']; ?>" name="mesazhi<?php echo $row['ID']; ?>" placeholder="Mesazhi"><?php echo $row['content']; ?></textarea>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
</form>
</div>
<?php endwhile; } ?>
</div>
</div>
<!-- 3.0 footer -->
<footer>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- bootstrap implimentation -->
<script src="js/bootstrap.min.js"></script>
<!-- bootstrap imp end -->
<script src="js/navbar.js"></script>
</footer>
</body>
</html>
here is my db_conncet.php
<?php
/* Konfigurimi i databazes */
define("HOST", "localhost");
define("USER", "laxhja");
define("PASSWORD", "password");
define("DATABASE", "laxhja");
define("SECURE", FALSE);
/* Lidhja me databaze */
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$mysqli->set_charset("utf8");
?>
<input type="submit" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"></input>
change this to
<input type="submit" name="update" class="submit col-lg-12 col-md-12 col-sm-12 col-xs-12 btn btn-primary" value="Posto"/>
I solved it by changing the mysql_real_escape_string to mysqli_real_escape_string gave it 2 parameters and its done.
like this.
$con = mysqli_connect("localhost", "laxhja", "password", "laxhja");
if(isset($_GET['update']) && !empty($_GET['update'])) {
$id = $_GET['update'];
$id1=mysqli_real_escape_string($con, $id);
$titulli = $_POST['emri'.$id];
$titulli1=mysqli_real_escape_string($con, $titulli);
$content = $_POST['mesazhi'.$id];
$content1=mysqli_real_escape_string($con, $content);
$date = date('Y-m-d H:i:s');...

Wordpress Custom PHP failing at wpdb object

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(); ?>

Updation not working using pdo in php

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'];

Categories