I have a table in the database which contains 2 columns one for PLZ (zip code) and the other for Link
and I have a form that contains an input and a button.
the work required is when I type the PLZ in the form and I click on the button we will give the link corresponding to this PLZ
<?php
require('../../../wp-blog-header.php');
require('../../../wp-config.php');
if(isset($_POST['submit']))
{
// WP Globals
global $table_prefix, $wpdb;
// Customer Table
$customerTable = $table_prefix . 'customer';
$PLZ = $_POST['PLZ'];
// search in all table columns
$query = "SELECT Link
FROM $customerTable
WHERE PLZ = '$PLZ'
";
$search_result = submit($query);
}
else {
echo 'error';
}
// function to connect and execute the query
function submit($query)
{
global $wpdb ;
$search_result = $wpdb->get_results($query);
foreach($search_result as $row){
header('Location: '.$row['Link']);
}
}
?>
and this is the form
<?php
function oped_postcode_form_function() {
<form method="get" action="<?php echo plugins_url('action.php', __FILE__ ); ?>">
<label>Postleitzahl</label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
<button name="submit">submit</button>
</form>
<?php
}
// register shortcode
add_shortcode('oped_postcode_form', 'oped_postcode_form_function');
?>
the result always gives error
Your form send GET request to server, so you need to use $_GET array in PHP code:
<?php
require('../../../wp-blog-header.php');
require('../../../wp-config.php');
if(isset($_GET['submit']))
{
// WP Globals
global $table_prefix, $wpdb;
// Customer Table
$customerTable = $table_prefix . 'customer';
$PLZ = $_GET['PLZ'];
// search in all table columns
$query = $wpdb->prepare("SELECT Link FROM $customerTable WHERE PLZ = %s", $PLZ);
$search_result = submit($query);
}
else {
echo 'error';
}
// function to connect and execute the query
function submit($query)
{
global $wpdb ;
$search_result = $wpdb->get_results($query);
foreach($search_result as $row){
header('Location: '.$row['Link']);
}
}
?>
Also you should to use prepared statements to prevent SQL Injection
Related
I have created a table on a wordpress database, This database table should have 2 columns.
One for postcode and one for a URL
If the postcode is found in the database, redirect to the corresponding URL
I am inserting rows from my plugin but I cannot select from this table.
Select return always error.
The insert that is working this is the action.php`
this is the form with shortcode
<?php
if ( !defined( 'ABSPATH' ) ) exit;
register_activation_hook( __FILE__, "activate_myplugin" );
register_deactivation_hook( __FILE__, "deactivate_myplugin" );
function activate_myplugin() {
init_db_myplugin();
}
function postcode_form_function() {
?>
<form method="GET" action="<?php echo plugins_url('action.php', __FILE__ ); ?>">
<label>postcode</label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
<button name="submit">submit</button>
</form>
<?php
}
// register shortcode
add_shortcode('postcode_form', 'postcode_form_function');
?>
When I try to select from this table I am taking nothing
<?php require('../../../wp-blog-header.php');
if(isset($_POST['submit']))
{
$postcode = $_POST['postcode'];
// search in all table columns
$query = "SELECT url
FROM wp_4_customer
WHERE $postcode =postcode
";
$search_result = submit($query);
} else {
echo 'error';
}
// function to connect and execute the query
function submit($query)
{
global $wpdb ;
$search_result = $wpdb->get_results($query);
foreach($search_result as $row){`enter code here`
header('Location: '.$row['url']);
}
}
?>
This is a form within a PHP file saved as single.php
<form action="comments.php" method="post" >
<?php include(ROOT_PATH . "/app/helpers/formErrors.php"); ?>
<input type= "hidden" name="id" value= <?php echo $id; ?> >
<textarea rows="4" name="comment"class="text-input contact-input" placeholder="Comment here....."></textarea>
<button type='submit' name="postcomment" value="comment" class="btn"> Add Comment</button>
</form>
This is also the php file that is receiving the form. comments.php
<?php
include(ROOT_PATH . "/app/helpers/validateComment.php");
$errors = array();
if(isset($_POST['postcomment'])){
$errors = validateComment($_POST);
//USE MYSQLI_REAL_ESCAPE_STRING() TO ESCAPE SINGLE QUOTES
// AND AGAINST SQL INJECTION
$userid = mysqli_real_escape_string($conn, $_SESSION['id']);
$username = mysqli_real_escape_string($conn,$_SESSION['username']);
$postid = mysqli_real_escape_string($conn,$_POST['id']);
$comment = mysqli_real_escape_string($conn,$_POST['comment']);
//prepared statement
$sql = $conn->stmt_init();
$query = "INSERT INTO comments (user_id, post_id, username, comment)
VALUES (?,?,?,?)";
if($sql->prepare($query)){
$sql->bind_param('ssss',$userid,$postid,$username,$comment);
$sql->execute();
header("Location:single.php?id=" . $postid); }
}
?>
and lastly my validatecomment.php
<?php
function validateComment($comments)
{
$errors = array();
if (empty($comments['comment'])){
array_push($errors, 'Comment is required!' );
}
if(!isset($_SESSION['username'])){
array_push($errors, "Sign UP first!");
}
return $errors;
}
?>
I don't understand why the validation is not working. Any help to get this working will highly be appreciated.
Right now, you're creating an error array, and doing nothing with it. Basically, you're letting in anyone who knocks whether you want them in or not. What you need to do is actually decide what to do if there are any errors.
$errors = validateComment($_POST);
if(!empty($errors)) {
// Insert code here to redirect, print out errors, whatever you want
} else {
// And here is where you would put all of your database stuff
$sql = $conn->stmt_init();
$query = "INSERT INTO comments (user_id, post_id, username, comment)
VALUES (?,?,?,?)";
if($sql->prepare($query)){
$sql->bind_param('ssss',$userid,$postid,$username,$comment);
$sql->execute();
header("Location:single.php?id=" . $postid); }
}
}
Note that I did not use the real_escape_string functions. They are unnecessary when you're using prepared statements.
I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}
I want to delete links to delete images on an SQL database. I am tasked with creating a delete confirm option not using JavaScript just PHP.
require_once("photoalbum-common.php");
$pdo = connect();
if ( isset( $_GET['deletionid'])) {
$errorMessage = deletePhotograph( $pdo, $_GET['deletionid']);
if ( $errorMessage != "") {
print "<div class='errormessage'>$errorMessage</div>\n";
} else {
print "<div class='message'>Image deleted.</div>\n";
}
}
The code below is in "photoalbum-common.php".
<?php
function deletePhotograph( $pdo, $deletionid) {
$errorMessage = "";
// retrieve name of image file so we can delete it
$stmt = $pdo->prepare("SELECT `image` FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count( $rows) == 1) {
// delete file
unlink( "images/".$rows[0]['image']);
// delete database record
$stmt = $pdo->prepare("DELETE FROM `photographs` WHERE `photoid`=?");
$stmt->execute( array( $deletionid));
$affected_rows = $stmt->rowCount();
} else if (count( $rows) > 1) {
$errorMessage .= "ID matches more than one record. ";
} else {
$errorMessage .= "ID not found: nothing to delete. ";
}
return $errorMessage;
}
?>
Use something like this. An interstitial page, that accepts a GET request:
GET Request GET /delete.php?id=123
Are you sure you wanna delete?
POST Request POST /delete.php?id=123
Execute the PDO.
You are supposed to write the code for the PHP. If the answer is not enough for this, well, here we go:
<?php
if (count($_POST)) {
// POST Request
deletePhotograph();
} else {
// GET Request
?>
<p>Are you sure you wanna delete?</p>
<!-- Empty action will POST to the same page. -->
<form action="" method="POST"><input type="submit" value="I confirm, Delete" /></form>
<?php
}
?>
I have a function where I want to delete Photos form my database. But my function is not getting in the isset($_POST[]). I have tried it with an echo and I have checked the submit. I'm just a student in PHP so I hope its not a dumb question
These are my functions.
function showDeleteForm(){
global $connection;
$id = $_GET['id'];
if (isset($_SESSION["login"]) && $_SESSION["login"] == 2) {
echo
'<form id="deleteButton" action="photo.php?id='.$id.'" method="post">
<button type="submit" name="deletePhoto">Delete</button>
</form>';
}
}
function handleDeleteForm(){
global $connection;
if(isset($_POST['deletePhoto'])){
$id = $_GET['id'];
$result = mysqli_query($connection, "DELETE FROM `i296297_studie`.`photos` WHERE id= '$id'");
header('Location: categorie.php');
}
}
Add mysqli_error($connection); in your query.
and if that work. Means no error
Check may be you forget to call the function.