PHP - PDO app error [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 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"

Related

PHP form post undefined index on line 9, 10, 11, 12 [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 1 year ago.
PHP file is:
<?php
require_once("connexion.php");
$nom = $prenom = $adresse = $age = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$nom = $_GET["nom"];
$prenom = $_GET["prenom"];
$adresse = $_GET["adresse"];
$age = $_GET["age"];
}
$sql = "INSERT INTO etudiant (nom, prenom, adresse, age) VALUES (?, ?, ?, ?)";
$stmt = mysqli_prepare($connexion, $sql);
mysqli_stmt_bind_param($stmt, "ssss", $param_nom, $param_prenom, $param_adresse, $param_age);
$param_nom = $nom;
$param_prenom = $prenom;
$param_adresse = $adresse;
$param_age = $age;
if (!empty($param_nom) && !empty($param_prenom) && !empty($param_adresse) && !empty($param_age)) {
$stmt -> execute();
}
mysqli_close($connexion);
?>
My HTML :
<html>
<style>
</style>
<body>
<h2> Ajouter un nouveau étudiant</h2>
<p>Merci de remplir tous les champs afin d'ajouter un nouveau étudiant</p>
<form method="GET" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="">Nom :</label>
<input type="text" name="nom" placeholder=" Nom *" value="<?php echo $nom; ?>">
</br></br>
<label for="">Prénom :</label>
<input type="text" name="prenom" placeholder=" Prénom *" value="<?php echo $prenom; ?>">
</br></br>
<label for="">Adresse :</label>
<input type="text" name="adresse" placeholder=" Adresse *" value="<?php echo $adresse; ?>">
</br></br>
<label for="">Age :</label>
<input type="numeric" name="age" placeholder=" Age *" value="<?php echo $age; ?>">
</br></br>
<input type="submit" name="envoyer" value="Submit" onclick="self.location.href='affichage_etudiant.php'">
<input type="reset" name="reset" value="Annuler">
</form>
</body>
</html>
I'm working on php forms using the GET method an I got this error, please help !
When I complete my form and I send my form, result is:
Notice: Undefined index in line 9, 10, 11, 12.
I used the GET method because they asked me to do with like that, Grr.
Change your GET method like below:
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$nom = isset($_GET["nom"]) ? $_GET["nom"] : '';
$prenom = isset($_GET["prenom"]) ? $_GET["prenom"] : '';
$adresse = isset($_GET["adresse"]) ? $_GET["adresse"] : '';
$age = isset($_GET["age"]) ? $_GET["age"] : '';
}

Can't figure out php insert [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.
The first section is from my updatecompany.php page, this is looking for the passed vars to update or display.
I keep getting errors that no ID is set, I can't for the life of me figure out where i went wrong. Any help would be great!
if (isset($_POST["id"]) && is_numeric($_POST["id"])){
$id = $_POST["id"];
$vid = \Fr\LS::getCompany("id", $id);
$vname = \Fr\LS::getCompany("name", $id);
$vlogo = \Fr\LS::getCompany("logo", $id);
$vinfo = \Fr\LS::getCompany("info", $id);
$vsite = \Fr\LS::getCompany("site", $id);
$vest = \Fr\LS::getCompany("est", $id);
}elseif ( isset($_POST["update"]) ){
\Fr\LS::updateCompany(array(
"name" => $_POST["name"],
"logo" => $_POST["logo"],
"info" => $_POST["info"],
"site" => $_POST["site"],
"est" => $_POST["est"]),
$_POST["idnum"]);
echo "<center>Company updated!";
echo "<br><a href='updatecompany.php" . $_POST["idnum"] ."'>go back</a></center>";
}else {
die("No server with that id.");
}
This is from my include with the function.
public static function updateCompany($toUpdate = array(), $company = null){
self::construct();
if( is_array($toUpdate) && !isset($toUpdate['id']) ){
if($company == null){
echo "No company ID set!";
}
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "`$k` = :$k, ";
}
$sql = self::$dbh->prepare("UPDATE companys SET {$columns} WHERE `id` = :id");
$sql->bindValue(":id", $company);
foreach($toUpdate as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
$sql->execute();
}else{
return false;
}
}
Here are the errors.
2017/01/06 16:39:19 [error] 9682#9682: *2752 FastCGI sent in stderr:
"PHP message: PHP Notice: Undefined index: logo in
/xxx/xxx/xxxxxxxxxxx/master/updatecompany.php on line 17 PHP message:
PHP Notice: Undefined index: idnum in
/xxx/xxx/xxxxxxxxxxx/master/updatecompany.php on line 21 PHP message:
PHP Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'WHERE id =
NULL' at line 1' in /xxx/xxx/xxxxxxxxxxx/inc/inc.php:917 Stack trace:
0 /xxx/xxx/xxxxxxxxxxx/inc/inc.php(917): PDOStatement->execute()
1 /xxx/xxx/xxxxxxxxxxx/master/updatecompany.php(21): Fr\LS::updateCompany(Array, NULL)
2 {main} thrown in /xxx/xxx/xxxxxxxxxxx/inc/inc.php on line 917" while reading response header from upstream, client: 75.189.195.82,
server: www.xxxxxxxx.com, request: "POST /master/updatecompany.php
HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host:
"www.xxxxxxxx.com", referrer:
"http://www.xxxxxxxx.com/master/updatecompany.php"
Here is the html form
<form action="updatecompany.php" method='POST'>
<div class="form-group">
<label for="ID">ID:</label>
<input name="idnum" type="" class="form-control" id="" value="<?php echo $vid; ?>" disabled>
</div>
<div class="form-group">
<label for="Name">Name:</label>
<input name="name" type="" class="form-control" id="name" value="<?php echo $vname; ?>">
</div>
<div class="form-group">
<label for="Logo">Logo:</label>
<input type="" class="form-control" id="logo" value="<?php echo $vlogo; ?>">
</div>
<div class="form-group">
<label for="Info">Info:</label>
<textarea name="info" class="form-control" rows="5" id="info"><?php echo $vinfo; ?></textarea>
</div>
<div class="form-group">
<label for="Site">Site:</label>
<input name="site" type="" class="form-control" id="site" value="<?php echo $vsite; ?>">
</div>
<div class="form-group">
<label for="EST">EST:</label>
<input name="est" type="" class="form-control" id="est" value="<?php echo $vest; ?>">
</div>
<button type="submit" value="update" name="update" id="update" class="btn btn-lg btn-primary">Save</button>
</form>
At first glance it appears this
$columns = "";
foreach($toUpdate as $k => $v){
$columns .= "$k= :$k, ";
}
is generating something like this
`name` = :name, `foo` = :foo,
That trailing comma at the end would generate incorrect SQL.

Undefined index [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 7 years ago.
I get Undefined index: image error in this code. Can I know the exact solution? I wanna know workflow from line abc to xyz that I commented in the code using //.Thanks for your help..
<?php session_start();
include("config.php");
if(isset($_SESSION['name']))
{
if(!$_SESSION['name']=='admin')
{
header("Location:login.php?id=You are not authorised to access this page unless you are administrator of this website");
}
}
?>
<?php
$name=$_FILES['image']['name'];
$tmp=$_FILES['image']['tmp_name'];
$err=$_FILES['image']['error'];
}
if($err==0)
{
move_uploaded_file($tmp, $name);
//xyz}
$category=$_POST['category'];
$title=$_POST['title'];
$image=$_FILES["image"]["name"];
$content=$_POST['content'];
}
<?php
$qry=mysql_query("INSERT INTO articles(title,image,content,category)VALUES('$title','$image','$content','$category')");
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
else
{
echo "Article Added Successfully";
}
?>
The form code is here:
<?php
include("config.php");
$sql=mysql_query("select * from category");
if(!$sql)
{
mysql_error();
}
?>
<form action="created_article.php" method="post">
Category:
<select name="category">
<?php
while($row=mysql_fetch_array($sql))
{
echo"<option value='".$row['category']."'>".$row['category']."</option>";
}
?>
</select>
Title:
<input type="text" name="title"/>
Upload Image:
<input type="file" name="image" id="image" />
Contents:
<textarea name="content" cols="100" rows="12" ></textarea>
<input type="submit" name="button" value="Submit" />
</form>
I need help with these code, I need to make project and I'm stuck here, so please kindly I request for your help,
<form action="created_article.php" method="post" enctype="multipart/form-data">
define enctype in your form tag otherwise its not work for image
While Dealing with input File always put form attribute enctype='multipart/form-data'
<?php
session_start ();
include ("config.php");
if (isset ( $_SESSION ['name'] )) {
if (! $_SESSION ['name'] == 'admin') {
header ( "Location:login.php?id=You are not authorised to access this page unless you are administrator of this website" );
}
}
if (!empty($_POST))
{
$name = $_FILES ['image'] ['name'];
$tmp = $_FILES ['image'] ['tmp_name'];
$err = $_FILES ['image'] ['error'];
if($err==0) {
move_uploaded_file($tmp, $name);
$category=$_POST['category'];
$title=$_POST['title'];
$image=$_FILES["image"]["name"];
$content=$_POST['content'];
}
$qry=mysql_query("INSERT INTO articles(title,image,content,category)VALUES('$title','$image','$content','$category')");
if(!$qry){
die("Query Failed: ". mysql_error());
} else {
echo "Article Added Successfully";
}
}
include("config.php");
$sql=mysql_query("select * from category");
if(!$sql){
mysql_error();
}
?>
The form code is here:
<form action="created_article.php" enctype='multipart/form-data' method="post">
Category: <select name="category">
<?php
while($row=mysql_fetch_array($sql))
{
echo"<option value='".$row['category']."'>".$row['category']."</option>";
}
?>
</select> Title: <input type="text" name="title" /> Upload Image: <input
type="file" name="image" id="image" /> Contents:
<textarea name="content" cols="100" rows="12"></textarea>
<input type="submit" name="button" value="Submit" />
</form>

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.

Notice: Undefined index: post_id in [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 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.

Categories