Notice: Undefined index: post_id in [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 9 years ago.
Hello i am a beginner on php and stuck on this moment. i can not find the problem.
Notice: Undefined index: post_id in C:\XA\htdocs\Passie Blog\post.php on line 22
this is line 22 where the problem should be:
$id = $_POST['post_id'];
this my php code
<?php
if(!isset($_GET['id'])){
header('Location: index.php');
exit();
}else{
$id = $_GET['id'];
}
include('includes/db_connect.php');
if(!is_numeric($id)){
header('Location: index.php');
}
$sql = "SELECT title, body FROM posts WHERE post_id='$id'";
$query = $db->query($sql);
if($query->num_rows !=1){
header('Location: index.php');
exit();
}
if(isset($_POST['submit'])){
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$id = $_POST['post_id'];
if($email && $name && $comment){
//
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$id = $db->real_escape_string($id);
$comment = $db->real_escape_string($comment);
if($addComment = $db->prepare("INSERT INTO comments(name, post_id, email_add, comment) VALUES (?,?,?,?)")){
$addComment->bind_param('ssss', $id, $name, $email, $comment);
$addComment->execute();
echo "Bedankt! uw bericht is toegevoegd";
$addComment->close();
} else{
echo "Error";
}
} else{
echo "ERROR";
}
}
?>
and this is the rest of my page
<div id="container">
<div id="post">
<?php
$row = $query->fetch_object();
echo "<h2>".$row->title."</h1>";
echo "<p>".$row->body."</p>";
?>
</div>
<hr />
<div id="add-comments">
<form action="<?php echo $_SERVER['PHP_SELF']."?id=$id"?>" method="post">
<div>
<label>Email Adres</label><input type="text" name="email" />
</div>
<div>
<label>Naam</label><input type="text" name="name" />
</div>
<div>
<label>Commentaar</label><textarea name="comment"></textarea>
</div>
<input type="hidden" name="post_id" value="<?php echo $id?>" />
<input type="submit" name="submit" value="Toevoegen"/>
</form>
</div>
<hr />
<div id="comments">
<?php
$query = $db->query("SELECT * FROM comments WHERE post_id='$id' ORDER BY comment_id DESC");
while($row = $query->fetch_object()):
?>
<div>
<h5><?php echo $row->name?></h5>
<blockquote><?php echo $row->comment?></blockquote>
</div>
<?php endwhile;?>
</div>
</div>

No field with the name post_id eists in your form. You are however passing the ID manually through the URL in your form action. To get the ID, you would use $_GET['id'] rather than $_POST['post_id']

The variable post_id isn't set (in post anyway). I'd change these
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$id = $_POST['post_id'];
to something like
$email = !empty($_POST['email']) ? $_POST['email'] : '';
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$comment = !empty($_POST['comment']) ? $_POST['comment'] : '';
$id = !empty($_POST['post_id']) ? $_POST['post_id'] : '';
This way you have a fall-back value if the form isn't completely filled out.

Related

It tried updating to database but it is not working

<?php
include('config/db_connect.php');
$title = $email = $ingredients ='';
$errors = array('email'=>'', 'title'=>'', 'ingredient'=>'');
if(isset($_POST['update'])){
//Check email
if(empty($_POST['email'])){
$errors['email'] ='an email is required <br />';
} else{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors['email'] = 'Email must be a valid email address';
}
}
//Check title
if(empty($_POST['title'])){
$errors['title'] ='a title is required <br />';
} else{
$title = $_POST['title'];
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$errors['title'] = 'Title must be letters and spaces only';
}
}
//Check ingredients
if(empty($_POST['ingredients'])){
$errors['ingredient'] = 'at least one ingredent is required <br />';
} else{
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$errors['ingredient'] = 'ingredients must be a comma separated list';
}
}
if(array_filter($errors)){
//echo 'errors in the form';
}else{
$id_to_update = mysqli_real_escape_string($conn, $_POST['$id_to_update']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
//create SQL
$sql = "UPDATE pizzas SET email='$email', title='$title', ingredients='$ingredients' WHERE id=$id_to_update";
echo $sql;
//save to db and check
if(mysqli_query($conn, $sql)){
//sucess
header('Location: index.php');
}else{
//errors
echo 'query error =' .mysqli_error($conn);
}
}
}
//check GET Request id param
if(isset($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);
// make sql
$sql = "SELECT * FROM pizzas WHERE id = $id";
//get query result
$result = mysqli_query($conn, $sql);
//fetch result in array format
$pizza = mysqli_fetch_assoc($result);
mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<section class="container grey-text">
<h4 class="center">Edit Pizza</h4>
<form class="white" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<label >Your Email:</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($pizza['email']); ?>">
<div class="red-text"><?php echo $errors['email']; ?></div>
<label >Pizza Title:</label>
<input type="text" name="title" value="<?php echo htmlspecialchars($pizza['title']); ?>">
<div class="red-text"><?php echo $errors['title']; ?></div>
<label >ingredients(comma separated):</label>
<input type="text" name="ingredients" value="<?php echo htmlspecialchars($pizza['ingredients']); ?>">
<div class="red-text"><?php echo $errors['ingredient']; ?></div>
<div class="center">
<input type="submit" name="update" value="Update Pizza" class="btn brand z-depth-0">
Back
</div>
</form>
</section>
<?php include('templates/footer.php');?>
</html>
Undefined index: $id_to_update in C:\xampp\htdocs\pizza\edit.php on line 36
UPDATE pizzas SET email='ajisafejerry#gmail.com', title='fish Supreme', ingredients='fish, tomatoes, cheese, pepper' WHERE id=query error =You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
You missed to post the "id" in your form you should add it.
<input type="hidden" name="id_to_update" value="<?php echo $id ?>">
And you have a typo, remove the dollar sign, it is a name not a variable.
$id_to_update = mysqli_real_escape_string($conn, $_POST['id_to_update']);
// ^ here
And if you want, depending on your specifications, you can tweak your redirect after the update to smth. like this.
header('Location: sql.php?id='.$id_to_update);

How to solved this kind of undefined variable problem in PHP [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
I had written the code in below but i saw Undefined variable problem:
In this code, there is 2 file. One file is for login and another file is for the classes. its about create and login page. Registration is not a problem its work correctly but when i want to do in existing login i face the problem. they told Undefined variable problem.
login.php(file name)
<?php include "inc/header.php"; ?>
<?php
$cmr = new Customer();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
$custLogin = $cmr->customerLogin($_POST);
}
?>
<div class="main">
<div class="content">
<div class="login_panel">
<?php
if (isset($custLogin)) {
echo $custLogin;
}
?>
<h3>Existing Customers</h3>
<p>Sign in with the form below.</p>
<form action="" method="post">
<input name="email" placeholder="Enter your email" type="text"/>
<input name="pass" placeholder="Enter your password" type="password"/>
<p class="note">If you forgot your passoword just enter your email and click here</p>
<div class="buttons"><div><button class="grey" name="login">Sign In</button></div></div>
</div>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
$customerReg = $cmr->customerRegistration($_POST);
}
?>
<div class="register_account">
<?php
if (isset($customerReg)) {
echo $customerReg;
}
?>
<h3>Register New Account</h3>
<form action="" method="post">
<table>
<tbody>
<tr>
<td>
<div>
<input type="text" name="name" placeholder="Name"/>
</div>
<div>
<input type="text" name="city" placeholder="City"/>
</div>
<div>
<input type="text" name="zip" placeholder="Zip-Code"/>
</div>
<div>
<input type="text" name="email" placeholder="Email"/>
</div>
</td>
<td>
<div>
<input type="text" name="address" placeholder="Address"/>
</div>
<div>
<input type="text" name="country" placeholder="Country"/>
</div>
<div>
<input type="text" name="phone" placeholder="Phone"/>
</div>
<div>
<input type="text" name="pass" placeholder="Password"/>
</div>
</td>
</tr>
</tbody></table>
<div class="search"><div><button class="grey" name="register">Create Account</button></div></div>
<p class="terms">By clicking 'Create Account' you agree to the Terms & Conditions.</p>
<div class="clear"></div>
</form>
</div>
<div class="clear"></div>
</div>
</div>
<?php include "inc/footer.php"; ?>
//////////////////////////////////////////////////
Customer.php (file name)
/////////////////////////////////////////////////
<?php
$filepath = realpath(dirname(__FILE__));
include_once ($filepath."/../lib/Database.php");
include_once ($filepath."/../helpers/Format.php");
?>
<?php
class Customer{
private $db;
private $fm;
public function __construct(){
$this->db = new Database();
$this->fm = new Format();
}
public function customerRegistration($data){
$name = $this->fm->validation($data['name']);
$address = $this->fm->validation($data['address']);
$city = $this->fm->validation($data['city']);
$country = $this->fm->validation($data['country']);
$zip = $this->fm->validation($data['zip']);
$phone = $this->fm->validation($data['phone']);
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$name = mysqli_real_escape_string($this->db->link, $data['name']);
$address = mysqli_real_escape_string($this->db->link, $data['address']);
$city = mysqli_real_escape_string($this->db->link, $data['city']);
$country = mysqli_real_escape_string($this->db->link, $data['country']);
$zip = mysqli_real_escape_string($this->db->link, $data['zip']);
$phone = mysqli_real_escape_string($this->db->link, $data['phone']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
if ($name == "" || $address == "" || $city == "" || $country == "" || $zip == "" || $phone == "" || $email == "" || $pass == ""){
$msg = "<span class='error'>Field must not be empty !</span>";
return $msg;
}
$mailquery = "select * from tbl_customer where email='$email' limit 1";
$mailchk = $this->db->select($mailquery);
if ($mailchk != false) {
$msg = "<span class='error'>Email already exist!</span>";
return $msg;
} else {
$query = "insert into tbl_customer(name,address,city,country,zip,phone,email,pass)
values ('$name','$address','$city','$country','$zip','$phone','$email','$pass')";
$userinsert = $this->db->insert($query);
if ($userinsert) {
$msg = "<span class='success'>Customer Data Added Successfully !</span>";
return $msg;
} else {
$msg = "<span class='error'>Customer Data not added !</span>";
return $msg;
}
}
}
public function customerLogin($date){
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
if (empty($email) || empty($pass)) {
$msg = "<span class='error'>Field must not be empty !</span>";
return $msg;
}
$query = "select * from tbl_customer where email = '$email' AND pass = '$pass'";
$result = $this->db->select($query);
if ($result != false) {
$value = $result->fetch_assoc();
Session::set("cuslogin",true);
Session::set("cmrId",$value['id']);
Session::set("cmrName",$value['name']);
header("Location:order.php");
} else {
$msg = "<span class='error'>Email or Password doesnot match!</span>";
return $msg;
}
}
}
?>
public function customerLogin($date){
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
these 4 line i faced a problem and the problem is below:
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 60
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 61
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 63
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 64
on row 59 - type-o
change this
public function customerLogin($date){
to
public function customerLogin($data){

PHP - PDO app error [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I'm trying to extend my PDO knowledge and at the moment I'm working at php app. Actually is a simple CMS, and I got a problem on the admin page, when you try to update the existing pages I got an error about ID [$_POST].
The error looks like:
Notice: Undefined index: id in /Applications/MAMP/htdocs/cms/admin/edit.php on line 6 object(PDOStatement)#2 (1) { ["queryString"]=> string(138) " UPDATE pages SET label = :label, title = :title, slug = :slug, body = :body, updated = NOW(), WHERE id = :id " } Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/cms/admin/edit.php:6) in /Applications/MAMP/htdocs/cms/admin/edit.php on line 28
EDIT.php
<?php
require '../app/start.php';
if (!empty($_POST)) {
$id = $_POST['id'];
$label = $_POST['label'];
$title = $_POST['title'];
$slug = $_POST['slug'];
$body = $_POST['body'];
$updatePage = $db->prepare('
UPDATE pages
SET label = :label, title = :title, slug = :slug, body = :body, updated = NOW(),
WHERE id = :id
');
$updatePage->execute([
'id' => $id,
'label' => $label,
'title' => $title,
'slug' => $slug,
'body' => $body,
]);
var_dump($updatePage);
header('Location: ' . BASE_URL . '/admin/list.php');
exit();
}
if(!isset($_GET['id'])){
header('Location:' . BASE_URL . '/admin/list.php');
exit();
}
$page = $db->prepare('
SELECT *
FROM pages
WHERE id = :id
');
$page->execute(['id' => $_GET['id']]);
$page = $page->fetch(PDO::FETCH_ASSOC);
require VIEW_ROOT . '/admin/edit.php';
START.php
<?php
require ('functions.php');
ini_set('display_errors', 1);
define('APP_ROOT', __DIR__);
define('VIEW_ROOT', APP_ROOT . '/views');
define('BASE_URL', 'http://localhost/cms');
$db = new PDO('mysql:host=localhost;dbname=cms', 'root', 'root');
?>
EDIT.PHP (form page)
<?php require VIEW_ROOT . '/templates/header.php'; ?>
<h2>Add page</h2>
<form action="<?php echo BASE_URL; ?>/admin/edit.php" method="POST" autocomplete="off">
<label for="title">
Title
<input type="text" name="title" id="title" value="<?php echo e($page['title']); ?>">
</label>
<label for="label">
Label
<input type="text" name="label" id="label" value="<?php echo e($page['label']); ?>">
</label>
<label for="slug">
Slug
<input type="text" name="slug" id="slug" value="<?php echo e($page['slug']); ?>">
</label>
<label for="body">
Content
<textarea name="body" id="body" cols="30" rows="10"><?php echo e($page['body']); ?></textarea>
</label>
<input type="hidden" value="<?php echo e($page['id']);?>">
<input type="submit" value="Edit article">
</form>
check following code:
<input type="hidden" value="<?php echo e($page['id']);?>">
as you see this code does not have name , according to your samples it should have name="id"

Undefined index: firstname in C:\xampp\htdocs\form_require1.php on line 53/55 [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
Hello everyone!
can someone guide me for the following problem? I was trying to make a php form, but it shows the error ( Undefined index: firstname in C:\xampp\htdocs\form_require1.php on line 53/55) when I run it. please help me
enter code here <?php // define valiables and set to empty values $firstnameErr = $lastnameErr = ""; $firstname = $lastname = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "Name is required";
} else {
$firstname = test_input($_POST["firstname"]); }
if (empty($_POST["lastname"])){
$lastnameErr = "Name is require"; } else { $lastname = test_input($_POST["lastname"]); } } function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
return $data; } ?> `enter code here` <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]) ?>" method="post"> Your firstname <input type="text" name="firstname" /> <span class="error">* <?php echo $firstnameErr;?></span> <br><br> Your Lastname <input type="text" name="lastname" /> <span class="error">* <?php echo $lastnameErr;?></span> <br><br> <input type="submit" value="Submit" /> </form> <?php // } else {
echo 'Your Details';
echo "<br>";
echo 'Fistname: ' . $_POST["firstname"];
echo "<br>";
echo 'Lastname: ' . $_POST["lastname"];
Basically the $_POST variables you want to use are not set. To be sure the form passes the right variables use var_dump($_POST); to see what variables it passes on.
For more information about your error see: php notice undefined variable and notice undefined index

PHP Undefined variable with POST [duplicate]

This question already has answers here:
Undefined index error PHP
(9 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
I am getting this...
Notice: Undefined index: cost, sku, costMethod
I think it is the validation part that is breaking this. I have tested sending these variables without the validation and they are received fine. I believe it is when everything is valid and the header gives it the destination is where it is losing the variables.
Here is my Form code:
<!DOCTYPE HTML>
<html>
<head>
<title>Shipping Overrides Client</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#additive").click(function(){
$("#cost").attr("value","0.00");
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$message = "SKU is required!";
$skuErr = "";
$sku = "";
$costErr ="";
$cost = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$valid = true;
if (empty($_POST["sku"]))
{$skuErr = "SKU is required";
$valid = false;}
else
{$sku = $_POST["sku"];}
if (empty($_POST["cost"]))
{$costErr = "Cost is required";
$valid = false;
}
else
{$cost = $_POST["cost"];}
if(isset($_POST['costMethod'])){
$costMethod = $_POST["costMethod"];
}
if($valid){
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
exit();
}
}
?>
<h1>Shipping Override Client</h1>
<form method="post" action="index.php" >
SKU: <input type="text" name="sku" value="<?php echo $sku ?>">* <?php echo $skuErr;?><br>
STD Shipping Cost: $ <input type="text" name="cost" id="cost" value="<?php echo $cost ?>">* <?php echo $costErr;?><br>
<input type="radio" name="costMethod" id="exclusive" value="Exclusive" checked>Override
<input type="radio" name="costMethod" id="additive" value="Additive" >Delete Existing Override <br>
<input type="submit" name= "submit" value="Submit">
</form>
</body>
</html>
Here is SubmitFeedSample.php:
<?php
$shippingCost = $_POST["cost"];
$sku = $_POST["sku"];
$costMeth = $_POST["costMethod"];
echo $shippingCost . "<br>";
echo $sku . "<br>";
echo $costMeth . "<br>";
var_dump($_POST);
?>
How can I get the variables to send when valid?
You are making a GET request here -
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
Try changing this -
<?php
$shippingCost = $_GET["cost"];
$sku = $_GET["sku"];
$costMeth = $_GET["costMethod"];
echo $shippingCost . "<br>";
echo $sku . "<br>";
echo $costMeth . "<br>";
var_dump($_POST);
?>
You cannot redirect with header once headers have already been sent:
header('Location: SubmitFeedSample.php?sku=$sku&cost=$cost&costMethod=$costMethod');
That's why you are probably not getting the result there. Also that's not a proper way to fetch the post data. If you are passing arguments in URL like that you are using GET not POST.

Categories