Why doesn't my MySQL update query work? - php

I'm making a blog edit page, but my edit page doesn't do anything. Why doesn't my update query work? I'm collecting the data from an old blog and inserting it into my form. And then I'm trying to update it using my update query.
I think this is the code you need:
<?php
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (empty($title) or empty($content)){
$error ='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ? WHERE id=:id");
$id = $_POST ['id'];
$query->bindValue(1, $title);
$query->bindValue(2 ,$content);
$query->bindValue ('id', $id);
$query->execute();
header('Location: index.php');
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$data = $article->fetch_data($id)
?>
<?php
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="" name="id" value="<?php echo $data['article_id']; ?>">
<input class="titleform" type="text" name="title" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea id="summernote" name="content" rows="15" cols="50">
<?php echo $data['article_content'] ?> </textarea>
<input class="buttonclass" type="submit" value="Aanmaken" /> </form>

You have a "Invalid parameter number: mixed named and positional parameters" error.
Change ? to placeholders, and change to bindValue():
$query = $pdo->prepare("UPDATE articles SET article_title = :title,
article_content = :content WHERE id=:id");
$id = $_POST ['id'];
$query->bindValue('title', $title);
$query->bindValue('content', $content);
$query->bindValue('id', $id);
$query->execute();
Or use only positional parameters.

The form element id was missing a type attribute - probably defaulted to text
Whilst probably not going to cause errors the mixing of placeholder types in the prepared statement is unusual. The id placeholder was missing the colon in the bindValue call - again possibly OK though to my mind it should always be used in named placeholders.
If the prepared statement failed the initial stage there was no logic to test for it.
<?php
$error=false;
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if( $_SERVER['REQUEST_METHOD']=='POST' && $pdo ){
if ( isset( $_POST ['id'], $_POST['title'], $_POST['content'] ) ) {
$id = $_POST ['id'];
$title = $_POST['title'];
$content = nl2br( $_POST['content'] );
if ( empty( $title ) or empty( $content ) or empty( $id ) ){
$error='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = :title, article_content = :content WHERE id=:id");
if( $query ){
$query->bindValue( ':title', $title );
$query->bindValue( ':content' ,$content );
$query->bindValue( ':id', $id );
$result=$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
} else {
exit('bad foo - unable to prepare sql query');
}
}
} else {
exit( sprintf( "<pre>check all required fields are named correctly\n\n%s</pre>", print_r( $_POST, true ) ) );
}
}
if ( isset( $_GET['id'] ) && $article ) {
$id = $_GET['id'];
$data = $article->fetch_data( $id );
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="title" class="titleform" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea name="content" id="summernote" rows="15" cols="50"><?php echo $data['article_content'] ?></textarea>
<input type="submit" class="buttonclass" value="Aanmaken" />
</form>
<?php
if( $error )printf('<h1>%s</h1>',$error);
?>

Related

Why is htmlentities not working in my Autosdb code?

All I am trying to do is escape html injection into my input text boxes. Am I not using htmlentities correctly?
Code:
<?php
require_once "pdo.php";
// Demand a GET parameter
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die('Name parameter missing');
} else {
$username = $_GET['name'];
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$year = isset($_POST['year']) ? $_POST['year'] : '';
$mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
$make = isset($_POST['make']) ? $_POST['make'] : '';
$failure = false;
$success = false;
if ( isset($_POST['make']) && isset($_POST['year'])
&& isset($_POST['mileage'])) {
//$year = $_POST['year'];
//$mileage = $_POST['mileage'];
//$make = $_POST['make'];
if ( strlen($make) < 1){
$failure = "Make is Required";
} else {
if (is_numeric($year) and is_numeric($mileage) ){
error_log("year is a number ".$_POST['year']);
error_log("Mileage is a number ".$_POST['mileage']);
$sql = "INSERT INTO autos (make, year, mileage)
VALUES (:make, :year, :mileage)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $make,
':year' => $year,
':mileage' => $mileage));
$success = "Record Inserted";
} else {
$failure = "Mileage and Year must be numeric";
error_log("year or mileage is not a number year=".$_POST['year']);
error_log("Mileage or year is not a number mileage=".$_POST['mileage']);
}
}
}
if ( isset($_POST['delete']) && isset($_POST['auto_id']) ) {
$sql = "DELETE FROM autos WHERE auto_id = :zip";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':zip' => $_POST['auto_id']));
}
$stmt = $pdo->query("SELECT make, year, mileage, auto_id FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Douglas Osborne's Automobile Tracker</title>
</head>
<body>
<table border="0">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['year']);
echo(" /");
echo("</td><td>");
echo($row['make']);
echo("</td><td>");
echo($row['mileage']);
echo(" miles");
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="auto_id" value="'.$row['auto_id'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
<body>
<div class="container">
<h1>
<?php
if ( isset($_REQUEST['name']) ) {
echo "<p>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</p>\n";
}
?>
</h1>
<p>
<?php
// Note triple not equals and think how badly double
// not equals would work here...
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
</p>
<form method="post">
<p>Make:
<input type="text" name="make" size="60" value="<?= htmlentities($make) ?>"/>
</p>
<p>Year:
<input type="text" name="year" value="<?= htmlentities($year) ?>"/>
</p>
<p>Mileage:
<input type="text" name="mileage" value="<?= htmlentities($mileage) ?>"/>
</p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<p>
</ul>
</div>
</html>
Output wont escape see screenshot:
Adding htmlspecialchars to (make) gave me the result I was looking for. Thanks for anyone's attempt to help me.

How can I update my entries with pdo::FETCH_CLASS and query it into my database?

Iam trying to update my form fields with a simple update statement. However when I execute the statement it wont update.
Iam using PDO::FECTH_CLASS to store my values into my object, and thats how I check if the id is equal to the id I want to update.
This is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try{
$firstname = $_POST['firstname'];
$paragraph = $_POST['paragraph'];
$company = $_POST['companyName'];
$q = 'UPDATE `testimonials` SET paragraph`= :paragraph,
`name`= :name,
`company`=:company,
`dateAdded`= NOW()
WHERE `id` =:id';
$stmt = $pdo->prepare($q);
$stmt->execute(array( ':id' => $testimonials->getId(), ':paragraph' => $paragraph, ':name' => $firstname, ':company' => $company));
}catch( PDOException $Exception ) {
throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}
}
?>
<section>
<form action="" method="POST">
<label for=""></label>
<input type="text" name="firstname" value="<?php echo $testimonials->getName();?>">
<input type="text" name="companyName" value="<?php echo $testimonials->getCompany(); ?>">
<textarea name="paragraph"><?php echo $testimonials->getParagraph(); ?></textarea>
<input type="submit" name="submit">
</form>
</section>

PHP not redirecting to required page

My add_comment.php has a input type button with value "cancel" its not redirecting the user back to the post on which he wants to comment if he press cancel .My add comment button however works perfectly .Please advise.
<?php
require_once 'app/helper.php';
session_name('mypaperplane');
session_start();
if (!verify_client()) {
header('location: signin.php');
}
$title='Add new comment';
$error="";
if(isset($_POST['submit'])){
$comments = filter_input(INPUT_POST,'comment', FILTER_SANITIZE_STRING);
$comments = trim($comments);
$post_id = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );
$post_id = trim( $post_id );
if (! $comments) {
$error='*Comment field is required';
}else{
$com_link = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PWD, MYSQL_DB);
$uid = $_SESSION['user_id'];
$post_id = mysqli_real_escape_string( $com_link, $post_id );
$comments = mysqli_real_escape_string( $com_link, $comments );
$comsql="INSERT INTO comments VALUES('',$post_id,$uid,'$comments', NOW())";
$comresult = mysqli_query($com_link,$comsql);
if($comresult && mysqli_affected_rows($com_link)>0){
header("location:readMore.php?id=$post_id");
}else{
header("location:readMore.php?id=$post_id");
}
}
}
?>
<div class="content">
<?php include'tpl/header.php'; ?>
<form name="comment" method="post">
<label for="comment">Comment here:</label><br><br>
<textarea rows="15" cols="15" name="comment" id="comment"></textarea><br><br>
<input type="submit" name="submit" value="Add comment" onclick="window.location='readMore.php?id= <?= $post['id']; ?>';">
<input type="button" value="Cancel" onclick="window.location.href='readMore.php?id=$post_id'"><br><br>
<span class="errorB"><?= $error; ?></span>
</form>
<?php include'tpl/footer.php'; ?>
</div>
You need to put short tags around $post_id
'readMore.php?id=<?= $post_id ?>'

Why input from the form is not being passed

I am new to php and have created two forms. One form takes in the user's first name and the second takes in the user's last name. I am not sure why that when the user inputs text into the forms nothing is being passed.
The php with the forms
<?php include '../view/header.php'; ?>
<div id="main">
<h1>Add Athlete</h1>
<form action="index.php" method="post" id="add_product_form">
<input type="hidden" name="action" value="add_product" />
<label>Country:</label>
<select name="category_id">
<?php foreach ( $categories as $category ) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select>
<br />
<label>Code:</label>
<input type="input" name="code" />
<br />
<label>First Name:</label>
<input type="input" name="first_name" />
<br />
<label>Last Name:</label>
<input type="input" name="last_name" />
<br />
<label> </label>
<input type="submit" value="Add Athlete" />
<br /> <br />
</form>
<p>View List of Olympic Athletes</p>
</div>
<?php include '../view/footer.php'; ?>
The php that takes in input from the forms
<?php
require('../model/database.php');
require('../model/product_db.php');
require('../model/category_db.php');
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_products';
}
if ($action == 'list_products') {
// Get the current category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
// Get product and category data
$category_name = get_category_name($category_id);
$categories = get_categories();
$products = get_products_by_category($category_id);
// Display the product list
include('product_list.php');
} else if ($action == 'delete_product') {
// Get the IDs
$product_id = $_POST['product_id'];
$category_id = $_POST['category_id'];
// Delete the product
delete_product($product_id);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
} else if ($action == 'show_add_form') {
$categories = get_categories();
include('product_add.php');
} else if ($action == 'add_product') {
$category_id = $_POST['category_id'];
$first_name = "";
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
$last_name = "";
if(isset($_POST['last_name'])){$last_name = $_POST['LastName'];}
// Validate the inputs
if (empty($first_name) || empty($last_name)) {
$error = "Invalid product data. Check all fields and try again.";
include('../errors/error.php');
} else {
add_product($category_id, $first_name, $last_name);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
}
} else if ($action == 'list_categories') {
$categories = get_categories();
include('category_list.php');
} else if ($action == 'add_category') {
$first_name = $_POST['FirstName'];
// Validate inputs
if (empty($name)) {
$error = "Invalid category name. Check name and try again.";
include('view/error.php');
} else {
add_category($name);
header('Location: .?action=list_categories'); // display the Category List page
}
} else if ($action == 'delete_category') {
$category_id = $_POST['category_id'];
delete_category($category_id);
header('Location: .?action=list_categories'); // display the Category List page
}
?>
The add_product function
function add_product($category_id, $first_name, $last_name) {
global $db;
$query = "INSERT INTO products
(categoryID, FirstName, LastName)
VALUES
('$category_id', '$first_name', '$last_name')";
$db->exec($query);
}
?>
Besides #MahfuzulAlam's answer, another problem is:
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
^^^^^^^^^
if(isset($_POST['last_name'])){$last_name = $_POST['LastName'];}
^^^^^^^^
It should be:
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$last_name = $_POST['last_name'];}
Also, in PHP 7, there's a shorthand for what you are currently doing:
$first_name = $_POST['first_name'] ?? "";
$last_name = $_POST['last_name'] ?? "";
It's called Null Coalesce Operator.
Try using type = text not input. <input type="text" name="last_name" /> and so on.
And there are problems in this code.
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
if(isset($_POST['last_name'])){$first_name = $_POST['LastName'];}
Whatever you pass as first_name and last_name your $first_name and $last_name variables will be empty. Because you are using $_POST['FirstName'], $_POST['LastName'] to set their values respectively, this don't really exists and both returning NULL. Rewrite these line as below:
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$first_name = $_POST['last_name'];}

Why is this UPDATE query not working on php

Hi I am struggling to see why this isn't updating the database. It reloads the page directed to by the HEADER but does not update the any field. Any help would be grealty appreaciated.
Update Form
<?php
include("../script/dbconnect.php");
include("../script/addprodcat.php");
$post = get_posts($_GET['id']);
if ( isset($_POST['name'], $_POST['description'], $_POST['price'], $_POST['sale'], $_POST['picture'], $_POST['category']) ) {
$errors = array();
$name = trim($_POST['name']);
$description = trim($_POST['description']);
if ( empty($name) ) {
$errors[] = 'You need to supply a title';
} else if ( strlen($name) > 255 ) {
$errors[] = 'Title cannot be longer than 255 characters';
}
if ( empty($description) ) {
$errors[] = 'You need to supply text';
}
if ( empty($price) ) {
$errors[] = 'You need to supply text';
}
if ( empty($sale) ) {
$errors[] = 'You need to supply text';
}
if ( empty($picture) ) {
$errors[] = 'You need to supply text';
}
if (! category_exists('id', $_POST['category']) ) {
$errors[] = 'Category does not exist';
}
if ( empty($errors) ) {
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
header("Location: ../admin/edit_products.php?id={$post[0]['post_id']}");
die();
}
}
?>
<div style="width:100%; height:150px; background-color:white;"><span style="font-family:saxMonoRegular; letter-spacing:2px; display:block; font-size:4.5em; text-align:center; padding-top:15px;"> Edit <?php echo $post[0]['name']; ?> </span></div>
<div class="link" style="width:100%; background-color:#ccc;">
<form action="" method="post">
<?php
if ( isset($errors) && ! empty($errors) ) {
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<label for="name">Title</label>
<input type="text" name="name" value="<?php echo $post[0]['name']; ?>"><br/>
<label for="price">Price</label>
<input type="text" name="price" value="<?php echo $post[0]['price']; ?>"><br/>
<label for="sale">Sale</label>
<input type="text" name="sale" value="<?php echo $post[0]['sale']; ?>"><br/>
<label for="picture">Picture</label>
<input type="text" name="picture" value="<?php echo $post[0]['picture']; ?>"><br/>
<label for="description">Description</label>
<textarea name="description" rows="15" cols="50"><?php echo $post[0]['description']; ?></textarea><br/>
<label for="prod_id">Category</label>
<select name="prod_id">
<?php
foreach ( get_categories() as $category ) {
$selected = ( $category['name'] == $post[0]['name'] ) ? " selected" : '';
?>
<option value="<?php echo $category['id']; ?>" <?php echo $selected; ?>> <?php echo $category['name']; ?></option>
<?php
}
?>
</select><br/>
<input class="button-link" type="submit" value="Edit Post">
</form>
</div>
addprodcat.php
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category) {
$id = (int) $id;
$prod_id = (int) $prod_id;
$prod_sub_id = (int) $prod_sub_id;
$name = mysql_real_escape_string($name);
$description = mysql_real_escape_string($description);
$price = mysql_real_escape_string($price);
$sale = mysql_real_escape_string($sale);
$picture = mysql_real_escape_string($picture);
$category = (int) $category;
mysql_query("UPDATE `products` SET
`cat_id` = {$category},
`prod_id` = {$prod_id},
`prod_sub_id ` = '{$prod_sub_id}',
`name` = '{$name}',
`description` = '{$description}',
`price` = '{$price}',
`sale` = '{$sale}',
`picture` = '{$picture}'
WHERE `id` = {$id}");
echo mysql_error();
}
Your update form passes only 7 parameters to the edit_products function; this function, however, expects 9.
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
...
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category)
You need to pass $prod_id and $prod_sub_id as well.
As an extra note, it's worth commenting out any redirects when debugging code as any (non-fatal) errors/warnings that would otherwise be shown are missed.
Number of function parameters differ. The function expects 9 but you provided 7.
This is a common user error that happens in lengthy lines.
Use the coding standard like this:
function edit_product(
$id,
$prod_id,
$prod_sub_id,
$name,
$description,
$price,
$sale,
$picture,
$category
) {
/*function code */
}
Follow same standard when you 'call' the function too.

Categories