Wordpress Custom PHP failing at wpdb object - php

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

Related

I'm struggling with integrating recaptcha in multipage form

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

keeping history of form data using session

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
}

Unable to connect the Database and Handle the POST request

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>

PHP Adding Data to Database

I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>

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

Categories