Trigger PHP function with HTML button - php

I have a simple function that deletes a row from a database...
<?php
function messaging_remove_message($tmp_mid) {
global $wpdb;
$wpdb->query( $wpdb->prepare("DELETE FROM " . $wpdb->base_prefix . "messages WHERE message_ID = %d", $tmp_mid ));
}
?>
What I am trying to do now is have this trigger when a delete button is pressed. I know that you can't trigger PHP functions with HTML so what are my options?

The simplest of the options would be to use AJAX. Use the following example:
page.php
<?php
// ...... include necessary config etc files
messaging_remove_message($_GET['mid']);
function messaging_remove_message($tmp_mid) {
global $wpdb;
$wpdb->query( $wpdb->prepare("DELETE FROM " . $wpdb->base_prefix . "messages WHERE message_ID = %d", $tmp_mid ));
}
?>
index.php
<button onclick="call_remove_msg(<?php echo $msg_id; ?>)">Delete</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function call_remove_msg(id){
$.get("page.php?mid=" + id, function(){alert("Comment deleted!");});
}
</script>
This is technically be improved with AJAX. Learn more for your development here: http://www.w3schools.com/ajax/

You can use the $_POST array to check if the button is clicked:
<?php
if (isset($_POST['buttonname'])) {
messaging_remove_message($var);
}
?>

Related

Getting SQL error when submitting form in wordpress

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

Data not inserting in custom table with code in functions.php

I have a custom HTML form in WordPress which inserts data into a custom table. I have written code in the functions.php file to insert data.
The HTML code is as below:
<form id="regForm" method="POST" action="">
My PHP function is as below:
function xx_data_insert() {
session_start();
require_once "wp-load.php";
require_once "dbconfig.php";
global $wpdb, $current_user;
$current_user = wp_get_current_user();
$table_name = 'xx_table';
//Form variables defined too many to add here
//insert statement
$flag = $wpdb->query( $wpdb->prepare(
(field1,field2,field3) VALUES(%s,%s,%s)",
$field1,
$field2,
$field3
));
if ($flag) {
echo "<script>";
echo " alert('Data saved successfully');
window.location.href='".site_url('http://xxx/xxx')."';
</script>";
exit();
}
if( isset($_POST['submit']) ) xx_data_insert();
When the submit button is clicked, there is no error. The page just refreshes. How do I check if the code is even going to the if statement? Any way to trap ?
David
$flag = $wpdb->query( $wpdb->prepare(
(field1,field2,field3) VALUES(%s,%s,%s)",
$field1,
$field2,
$field3
));
check this (field1,field2,field3) VALUES(%s,%s,%s)", starting quote is missing

How to remove a row from MySQL table data using html delete button in PHP

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);
}

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

Return later ? PHP View file

Lets say I have a view file that is built like this:
<html>
...
<title><?= Functions::Text('title'); ?></title>
....
<body>
....
<?= Functions::Text('sometext'); ?>
</body>
</html>
Functions::Text - would give me a db entry in table texts with search_string of title and sometext.
I want to pull out the data at once, and not per request (which mean - to collect an array of strings given to Texts (which is not that hard) - but I want the data, after the select query, to go to the exact places which requested the data.
which mean -
$query = select ... ;
... fetch ...
$results_of_fetch = array ('title'=>'Welcome!','sometext' => 'sometext!!');
And the view file -
<html>
...
<title>Welcome!</title>
....
<body>
....
sometext!!
</body>
</html>
I think your question is more related to Object rather than MVC.
So, i would like to make suggestion.
Don't use static method if you have to reuse object more that one time.
By using non static method efficiently, you don't have to query database over and over again.
//create an object that takes parameter
//from a constructor or some other public method
class Function{
public $title;
public $text;
public $footer;
function _construct($id)
{
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname", $con)) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT * FROM table1 WHERE id=".$id." LIMIT 1";
//if you are using id, then don't forget to add limit 1
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$row = mysql_fetch_assoc($result);
//alternatively you can add loop check it at php manual
$this->title = $row['title'];
$this->text = $row['text'];
$this->footer = $row['footer'];
}
}
And in you layout(or view) file
//the first thing you need to do is instantiate an object
//don't use static method if you are reusing object again
<?php
$function = new Function($id);
//pass some id or other parameter
?>
<html>
...
<title>
<?= $function->title; ?>
<!-- alternatively you can do with some method also -->
</title>
....
<body>
....
<?= $function->text; ?>
</body>
</html>
And I might not be understanding your necessity, you can comment, and please review your question.
You can do this with AJAX and jQuery. jQuery, so that it'll be much easier.
jQuery
$.post("fetchstuff.php", function(data){
document.title = data.title;
$("#txt1").html(data.sometext);
});
fetchstuff.php
<?php
$sometext = "sometext";
$title = "sometitle"
?>
Totally untested but output should look like this.
<title>sometitle</title>
....
<div id="txt1">sometext</div>

Categories