This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I am trying to make a posting system for a project I am working on. Problem is, for some reason, all $_POST values are null, even if they are supposed to be set. As a result, my PHP script does not work.
I can't tell why this is the case, as it was working fine just yesterday. How can I fix this?
<?php
function show_posts($posts, $parent_id = -1) {
$html = '';
if ($parent_id != -1) {
// If the posts are replies sort them by the "submit_date" column
array_multisort(array_column($posts, 'submit_date'), SORT_ASC, $posts);
}
$resultCount = 0;
// Iterate the posts using the foreach loop
foreach ($posts as $post) {
if (($_GET['search_query']) != "") {
if ($post['parent_id'] == $parent_id) {
if (strpos(implode($post), $_GET['search_query'])) {
$resultCount++;
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
ob_clean();
echo(strval($resultCount) . ' result(s) found for "' . $_GET['search_query'] . '"'); //display number of results
}
}
}
else
{
//add each post to HTML variable
if ($post['parent_id'] == $parent_id) {
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<h2></h2>
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
}
}
}
return $html;
}
// This function is the template for the write post form
function show_write_post_form($parent_id = -1) {
$rand = randomIdentifier(); //generate random identifier string
$html = '
<div class="write_post" data-post-id="' . $parent_id . '">
<form>
<h2 style="color: white;">New Post</h2>
<br>
<input name="parent_id" type="hidden" value="' . $parent_id . '">
<label for="name">Title:</label>
<input style="width: 100%;" id="name" name="name" type="text" placeholder="Enter a title..." required>
<br><br>
<label for="screenshot">Screenshot (if applicable):</label>
<input style="width: 100%;" id="screenshot" name="screenshot" type="url" placeholder="Screenshot URL">
<br><br>
<label for="type">URL:</label>
<input style="width: 100%;" id="url" name="url" type="url" placeholder="Download URL" required>
<br><br>
<label for="type">Description:</label>
<textarea name="content" id="content" placeholder="Write a description..." required></textarea>
<br><br>
<label for="type">Original Source (if known):</label>
<input style="width: 100%;" id="source" name="source" type="url" placeholder="Original Source URL">
<br><br>
<label for="type">Serial (if applicable):</label>
<input style="width: 100%;" id="serial" name="serial" type="text" placeholder="Serial">
<br><br>
<label for="name">Your Name/Nickname:</label>
<input style="width: 100%;" id="postauthor" name="postauthor" type="text" placeholder="Enter your name..." required>
<br><br>
<br>
<label for="type">Choose a type:</label>
<select name="type" id="type">
<option value="freeware">Freeware</option>
<option value="abandonware">Abandonware</option>
<option value="self-made">I wrote it myself</option>
</select>
<label for="category">Category:</label>
<select name="category" id="category">
<option value="app">App</option>
<option value="game">Game</option>
<option value="driver">Driver</option>
<option value="manual">Manual</option>
<option value="setup">Setup</option>
<option value="ROM">ROM</option>
<option value="other">Other</option>
</select>
<br><br>
<h2 style="color: white;">Post identifier string</h2>
<input name="identifier" id="identifier" style="width: 100%;" readonly="true" type="text"" value="' . $rand . '">
<br>
<p style="color: red;">This is your post identifier string. It can be used to delete this post in the future without having to contact an admin. <b>Make sure you do not lose it!</b></p>
<br><br>
<h2 style="color: white;">Make sure your submission meets the following criteria:</h2>
<br>
<p>๐ This submission is appropriate and doesn\'t have any mature content. - We want PPC Planet to be a safe place for people of all ages. Inappropriate submissions will be removed!</p>
<p>๐ This submission is either freeware, abandonware, or self-made. - No piracy! It\'s not fair to the developer(s).</p>
<p>๐ป This submission has been tested, and works as advertised. - We don\'t want to have a bunch of broken software on the archive.</p>
<p>๐งพ This submission is not already on the archive. - Be sure that you are posting something unique!</p>
<p>๐ฑ This submission is related to Pocket PCs. - Remember, this is an archive of Pocket PC software.</p>
<br>
<p><b>By following these rules, we can make the archive a fun (and totally rad) place for everyone!</b></p>
<br><br>
<p style="color: red; font-size: xx-large; "><b>Make sure you have proofread your post, as you will not be able to edit it once it has been posted. Additionally, make sure you write your down identifier string somewhere if you have not already.</b></p>
<br><br>
<button type="submit">Create Post</button>
<br><br>
</form>
</div>
';
return $html;
}
if (isset($_GET['search_query'])) {
// Check if the submitted form variables exist
if (($_POST['name']).trim() != "") {
$stmt = $pdo->prepare('INSERT INTO posts (page_id, parent_id, name, screenshot, url, content, serial, type, category, identifier, source, postauthor, submit_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())');
$stmt->execute([ 1, $_POST['parent_id'], $_POST['name'], $_POST['screenshot'], $_POST['url'], $_POST['content'], $_POST['serial'], $_POST['type'], $_POST['category'], $_POST["identifier"], $_POST["source"], $_POST["postauthor"] ]);
exit('Your post has been submitted! You can reload the page to see it.');
}
else
{
// Get all posts by the Page ID ordered by the submit date
$stmt = $pdo->prepare('SELECT * FROM posts WHERE page_id = ? ORDER BY submit_date DESC');
$stmt->execute([ 1 ]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the total number of posts
$stmt = $pdo->prepare('SELECT COUNT(*) AS total_posts FROM posts WHERE page_id = ?');
$stmt->execute([ 1 ]);
$posts_info = $stmt->fetch(PDO::FETCH_ASSOC);
}
} else {
exit('No search query specified!');
}
function randomIdentifier() {
$pass = 0;
$complete = false;
while (!$complete)
{
//generate random identifier string until it is unique
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()';
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 100; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
include('mysqlconnect.php');
$pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
$data = implode($pass);
$stmt = $pdo->prepare( "SELECT identifier FROM posts WHERE identifier =:id" );
$stmt->bindParam(':id', $data, PDO::PARAM_STR);
$stmt->execute();
$myIdentifier = $stmt->fetch();
if (!$myIdentifier) {
//identifier is unique
$complete = true;
}
}
return $data;
}
?>
<?=show_write_post_form()?>
<?=show_posts($posts)?>
You can try it out for yourself here. All help is appreciated!
$_POST in PHP collects any variables submitted in the body of a HTTP POST request.
However your HTML form is submitting a GET request (which is the default if you don't specify the method). You can fix this by specifying the method attribute of the form:
<form method="post">
$_POST superglobal is only available in POST requests. You seem to be rendering your content in a GET request.
Related
I'm try to send the value from the value attribute in button using a form that use the method POST in "landlord_home.php". The problem was that when I click on the button to go to the next page which is "edit_post.php", it execute the php validation code in that page and display the validation error in that page.
How can I pass the value to "edit_post.php" without using a form(POST or GET method) or is there any other way?
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr>
<td>' . $row['property_id'] . '</td>
<td>' . $row['username']. '</td>
<td>' . $row['property_type']. '</td>
<td>RM' . $row['property_price']. '</td>
<td>' . $row['address']. '</td>
<td>' . $row['location']. '</td>
<td>
<img src="data:property_type;base64,' .
$row['property_picture'] .
'" class="img-thumbnail" width="100" height="100">
</td>
<td>' . $row['title'] . '</td>
<td>' . $row['description'] . '</td>
<td>' . date('F d, Y h:mA', strtotime($row['reg_date'])) . '</td>
<td>
<form action="edit_post.php" method="POST">
<button class="btn btn-success btn-sm" name="edit" value="' .
$row['property_id'] . '">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete"
value="'.$row['property_id'] . '">
Delete
</button>
</form>
</td>
</tr>';
}
echo '</table>';
Above is the code from "landlord_home.php". Below is the part of code that I am talking about from above code.
<form action="edit_post.php" method="POST">
<button class="btn btn-success btn-sm" name="edit" value="' .
$row['property_id'] . '">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete" value="' .
$row['property_id'] . '">
Delete
</button>
</form>
And below is the code of the next page "edit_post.php"
session_start();
$user = $_SESSION['username'];
if(!isset($_SESSION['username'])) {
require('login_tools_landlord.php');
load();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Edit Property</title>
<link rel="stylesheet" href="css/add_property.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</head>
<body>
<?php include 'includes/header_landlord.php' ?>
<div class="container wrapper">
<div class="text-center title_bar">
<h3>Fill in your property details</h3>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('core/connect_db.php');
$errors = array();
if (isset($_POST['edit'])) {
$edit = $_POST['edit'];
$q = "SELECT * FROM property WHERE property_id = '$edit'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$prop_type = $row['property_type'];
$price = $row['property_price'];
$address = $row['address'];
$location = $row['location'];
$pic = $row['property_picture'];
$title = $row['title'];
$desc = $row['description'];
$dt = $row['reg_date'];
if (empty($_POST['property_type'])) {
$errors[] = 'Choose property type.';
} else {
$pr = mysqli_real_escape_string($dbc, trim($_POST['property_type']));
}
if (empty($_POST['price'])) {
$errors[] = 'Enter your property price.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['price']));
}
if (empty($_POST['address'])) {
$errors[] = 'Enter your address.';
} else {
$ad = mysqli_real_escape_string($dbc, trim($_POST['address']));
}
if (empty($_POST['location'])) {
$errors[] = 'Choose your location.';
} else {
$lo = mysqli_real_escape_string($dbc, trim($_POST['location']));
}
// if (empty($_POST['picture'])) {
// $errors[] = 'Pick a picture.';
// } else {
// $pc = mysqli_real_escape_string($dbc, trim($_POST['picture']));
// }
if (isset($_POST['submit'])) {
if (getimagesize($_FILES['picture']['tmp_name']) == FALSE) {
$errors[] = "Please select an image.";
} else {
$picture = addslashes($_FILES['picture']['tmp_name']);
$name = addslashes($_FILES['picture']['name']);
$picture = file_get_contents($picture);
$picture = base64_encode($picture);
}
}
if (empty($_POST['title'])) {
$errors[] = 'Enter your title.';
} else {
$ti = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['description'])) {
$errors[] = 'Enter your description.';
} else {
$de = mysqli_real_escape_string($dbc, trim($_POST['description']));
}
if (empty($errors)) {
$qa = "
UPDATE property
SET property_type = '$pr', property_price = '$p', address = '$ad',
location = '$lo', property_picture = '$picture', title = '$ti',
description = '$de', reg_date = NOW()
WHERE property_type = '$prop_type', property_price = '$price',
address = '$address', location = '$location',
property_picture = '$pic', title = '$title',
description = '$desc', reg_date = '$dt'
";
$ra = mysqli_query($dbc, $qa);
if ($ra) {
echo '<h1 class="sccs_msg">Successful</h1>
<p class="sccs_msg">REDIRECTING YOU TO DASHBOARD in 3 SECOND</p>
<meta http-equiv="refresh" content="3;URL=landlord_home.php" />';
}
mysqli_close($dbc);
exit();
} else {
echo '<h1 class="err_msg">ERROR!</h1>
<p class="err_msg">The following error(s) occurred:<br>';
foreach ($errors as $msg) {
echo "- $msg<br>";
}
echo 'Please try again.</p>';
mysqli_close($dbc);
}
}
}
?>
</div>
<form method="post" action="edit_post.php" enctype="multipart/form-data">
<div class="form-group">
<label for="property_type">Property Type</label>
<select class="form-control" name="property_type" id="property_type"
value="<?php
if (isset($_POST['property_type'])) {
echo $_POST['property_type'];
}
?>">
<option></option>
<option>Room</option>
<option>Whole Unit</option>
</select>
</div>
<div class="form-group">
<label for="price">Unit Price(RM)</label>
<input type="text" class="form-control" name="price" id="unit_price"
placeholder="Unit Price" value="<?php
if (isset($_POST['price'])) {
echo $_POST['price'];
}
?>">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" name="address" id="address" rows="3"
value="<?php
if (isset($_POST['address'])) {
echo $_POST['address'];
}
?>"></textarea>
</div>
<div class="form-group">
<label for="location">Location</label>
<select class="form-control" name="location" id="location"
value="<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
}
?>">
<optgroup label="Kuala Lumpur">
<option></option>
<option>Puchong</option>
<option>Salak Selatan</option>
<option>Segambut</option>
<option>Sentul</option>
<option>Seputih</option>
</optgroup>
<optgroup label="Selangor">
<option>Cheras</option>
<option>Damansara</option>
<option>Cyberjaya</option>
<option>Kajang</option>
<option>Kelana Jaya</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="picture">Picture</label>
<input type="file" class="form-control-file" name="picture"
id="picture" aria-describedby="fileHelp"
value="<?php
if (isset($_POST['picture'])) {
echo $_POST['picture'];
}
?>">
<small id="fileHelp" class="form-text text-muted">
Please provide a photo of your property.
</small>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title"
placeholder="Post Title" value="<?php
if (isset($_POST['title'])) {
echo $_POST['title'];
}
?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description"
rows="3" value="<?php
if (isset($_POST['description'])) {
echo $_POST['description'];
}
?>"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit">
Submit
</button>
</form>
</div>
</body>
</html>
How can I pass the value to "edit_post.php" without using a form(POST or GET method) or is there any other way?
I'm not sure to understand what you mean above, unless you wanted to say without using an additional visible form input.
If so, then the answer is contained in the question: you have merely to add a hidden input to your form (and give up buttons value):
<form action="edit_post.php" method="POST">
<input type="hidden" name="property-id" value=" . $row['property_id'] . '">
<button class="btn btn-success btn-sm" name="edit">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete">
Delete
</button>
</form>
Then in edit_post.php you can use $_POST['property-id'] as you want.
BTW I'm a bit surprised looking at your $qa query in edit_post.php: unless I missed something subtle, its WHERE clause is invalid, since it's built like a comma-separated list of condition (while they probably should be ANDed).
I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;
My database manages to retrieve values when I navigate from the previous page.
When I click the 'Update Product' button, the line Update product appears. What I want is when I click the 'Update Product' button, and have modified a record beforehand, I would hope to update the database with the values as well and a confirmation message is displayed to confirm this.
Code:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<input id="Producer" name="productDescription" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Year Published</label>
<input id="updateFormProductPrice" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(£)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
So I need the database to update what new value I have entered and it once the 'Update product' Button is pressed, the original value appears and the value is not updated on the database. Why is this? I don't get any error messages. Thanks
The error is that you dont POST the ID but you GET the ID value. input boxes with the readonly attribute don't post values.
change:
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
to:
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
Edit: Total changes to make to make this work:
HTML:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductID">ID</label>
<input id="updateFormProductID" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductProducer">Producer</label>
<input id="updateFormProductProducer" name="Producer" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductYearPublished">Year Published</label>
<input id="updateFormProductYearPublished" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Price:(£)</label>
<input id="updateFormProductPrice" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
Try setting the name and id of your input fields to the same respective values. I see you call id from one and name from another input field in your php and it might be causing the function to fail.
Like so for example:
<label for="ID">ID</label>
<input id="ID" name="ID" type="text" readonly value="<?php echo $productDetails["ID"]; ?>">
you should be fine using $_POST[], since the method of your form is POST. (If you change it to GET it will put all the values in the url)
I want to insert an array of checkboxes, dropdowns, and dates into database. If I checked all the checkbox, all works fine. However, when I checked certain checkboxes, the value of checkboxes can be inserted but not the value of dropdown and date.
This is code for the checkbox, dropdown, and date:
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<input type='checkbox' id='spesimen$i' name='spesimen[]' value='$JenisSpesimen' required minlength='1'/><label>$JenisSpesimen</label><br>
</div>
<div class='select'>
<select id='bilangan$i' name='bilangan[]' class='med' style='display: none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<br>
<div class='input' id='tarikh_ambil$i' style='display: none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='tarikh_ambil_spesimen[]' class='small' readonly/>
</div>
</div>
</div>
And this the process:
$spesimen = $_POST['spesimen'];
$countSpesimen = count($_POST['spesimen']);
$bilangan = $_POST['bilangan'];
//$countBilagan = count($_POST['bilangan']);
$tarikh_ambil = $_POST['tarikh_ambil_spesimen'];
//$countTarikh = count($_POST['tarikh_ambil_spesimen']);
for ( $x = 0; $x < $countSpesimen; $x++)
{
$xx = $x+1;
$SubIDMohon = $IDMohonx.'-'.$xx;
$dd=substr($tarikh_ambil[$x], 0, 2);
$mm=substr($tarikh_ambil[$x], 3, 2);
$yy=substr($tarikh_ambil[$x], 6, 4);
$tarikh_ambil[$x] = $yy."-".$mm."-".$dd;
if($tarikh_ambil[$x] == '--') { $tarikh_ambil[$x] = '0000-00-00'; }
$pdo->exec("insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values ('".$IDMohonx."','".$SubIDMohon."','".$spesimen[$x]."','".$bilangan[$x]."','".$tarikh_ambil[$x]."','".$tarikh_hantar_spesimen."','".$tarikh_terima_spesimen."')");
}
I would recommend to wrap your fields into an common name, so that you can run a foreach over each 'fieldset' and then access its corresponding fields, instead of having them separate and independent as you have them now.
HTML would be something like this: (Implement the counter as you wish, but be sure to increment it before adding another set)
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<label><input type='checkbox' id='spesimen$i' name='fieldset[$counter][spesimen]' value='$JenisSpesimen' required minlength='1'/>$JenisSpesimen</label>
</div>
<div class='select'>
<select id='bilangan$i' name='fieldset[$counter][bilangan]' class='med' style='display:none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<div class='input' id='tarikh_ambil$i' style='display:none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='fieldset[$counter][tarikh_ambil_spesimen]' class='small' readonly/>
</div>
</div>
</div>
and your PHP code as follows:
foreach($_POST['fieldset'] as $i=>$fields){
$SubIDMohon = $IDMohonx .'-' . ($i + 1) ;
//If specimen is checked, the value comes with post, otherwise set it to default ''
$specimen = ( isset($fields['specimen']) ) ? $fields['specimen'] : '';
//check if the date is valid format
$date = '';
if(preg_match('^([0-9]{2}-){2}[0-9]{4}$', $fields['tarikh_ambil_spesimen'])){
$date = implode('-', array_reverse( explode('-', $fields['tarikh_ambil_spesimen']) ) );
}
else{
$date = '0000-00-00';
}
$pdo->exec(
"insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values (
'" . $IDMohonx . "',
'" . $SubIDMohon . "',
'" . $spesimen . "',
'" . $fields['bilangan'] . "',
'" . $date . "',
'" . $tarikh_hantar_spesimen . "',
'" . $tarikh_terima_spesimen . "'
)"
);
}
Try doing a print_r to your $_POST so you can see how it is structured.
Good luck!
I'm trying to integrate CKEditor into my simple CMS. I got it to show up on the page, but it's just above everything. I'm wondering how to get it into the correct spot, below my title textbox? Here is my code:
require_once 'conn.php';
include_once 'ckeditor/ckeditor.php';
$CKEditor = new CKEditor();
$CKEditor->editor('body');
$title= '';
$body= '';
$article= '';
$author_id= '';
if (isset($_GET['a'])
and $_GET['a'] == 'edit'
and isset($_GET['article'])
and $_GET['article']) {
$sql = "SELECT title, body, author_id FROM cms_articles " .
"WHERE article_id=" . $_GET['article'];
$result = mysql_query($sql, $conn) or
die ('Could not retrieve article data: ' . mysql_error());
$row = mysql_fetch_array($result);
$title = $row['title'];
$body = $row['body'];
$article = $_GET['article'];
$author_id = $row['author_id'];
}
require_once 'header.php';
?>
<form method="post" action="transact-article.php">
<h2>Compose Article</h2>
<p>
Title: <br />
<input type="text" class="title" name="title" maxlength="255" value="<?php echo htmlspecialchars($title); ?>" />
</p>
<p>
Body: <br />
<textarea class="body" name="body" id="body" rows="10" cols="60"><?php echo htmlspecialchars($body); ?></textarea>
</p>
<p>
<?php
echo '<input type="hidden" name="article" value="' .
$article . "\" />\n";
if ($_SESSION['access_lvl'] < 2) {
echo '<input type="hidden" name="author_id" value="' .
$author_id . "\" />\n";
}
if ($article) {
echo '<input type="submit" class="submit" name="action" ' .
"value=\"Save Changes\" />";
} else {
echo '<input type="submit" class="submit" name="action" ' .
"value=\"Submit New Article\" />";
}
?>
</p>
</form>
Personally I don't think you need the PHP library. Just add
<div contenteditable="true">
Editable text
</div>
as your editable and then just the script to get it running:
<script type="text/javascript" src="/path/to/ckeditor/ckeditor.js"></script>
That said, you may be able to pass the id of your textarea to the PHP library. To avoid confusion with the body tag, rename the id and name of this control to editable_content or similar. And as I mention above, try using a div instead.