$wpdb SELECT query errors - php

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']);
}
}
?>

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

Search Script for PHP website with MySQL Database

I have a PHP website to display products. I need to introduce a 'Search' feature whereby a keyword or phrase can be found among number of products.
I went through number of existing scripts and wrote/modified one for me which though able to connect to database, doesn't return any value. The debug mode throws a warning " mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ". Seems I am not collecting the query value correctly. The PHP Manuals says that mysqli_query() returns FALSE on failure and for successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object and for other successful queries mysqli_query() will return TRUE ".
Any suggestions?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
# $db = mysqli_connect('localhost','username','password','database' );
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
To do your literal search as you have it, you would need to change the code '%{searchterm}%' to '%$searchterm%', since the brackets aren't needed and you were searching for the phrase "{searchterm}." Outside of that you might want to take a look at FULLTEXT search capabilities since you're doing a literal search in your current method.
To make the output look like Google's output you would simply code a wrapper for each search result and style them with CSS and HTML.
I think it should be something like '%$searchterm%', not '%{searchterm}%' in your query. You are not searching for your variable $searchterm in your example.
Google's display uses LIMIT in the query so it only displays a certain amount of results at a time (known as pagination).
This is tested and works. You will need to change 1) db connection info in the search engine class. 2) If you want it to be on separate pages, you will have to split it up. If not, copy this whole code to one page and it will work on that one page.
<?php
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
class SearchEngine
{
protected $searchterm;
public function execute($searchword)
{
$this->searchterm = htmlentities(trim($searchword), ENT_QUOTES);
}
public function display()
{ ?>
<h1>Results</h1>
<?php
//If they forget to enter a search term display an error
if(empty($this->searchterm)) { ?>
<h3>Search Empty</h3>
<p>You must fill out search field.</p>
<?php }
else {
$con = new DBEngine('localhost','database','username','password');
$results = $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");
if($results !== 0 && !empty($results)) { ?>
<p>Number of match found: <?php echo count($results); ?> on search:<br />
<?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
<?php
foreach($results as $rows) {
echo '<pre>';
print_r($rows);
echo '</pre>';
}
}
else { ?>
<h3>No results found.</h3>
<?php
}
}
}
}
if(isset($_POST['submit'])) {
$searcher = new SearchEngine();
$searcher->execute($_POST['searchterm']);
$searcher->display();
} ?>
<form name="search" method="post" action="">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>

Why does this SQL execute but not update anything?

For some reason or another, this sql is executing and outputting:
successfully added the following paypal button to this product... But it's not updating. I'd appreciate any help on this.
if(isset($_REQUEST['submitedform'])) {
if ($_POST['paypal']) {
$paypal=$_POST['paypal'];
$id = $_GET['id'];
$query = "UPDATE `video_info` SET paypal_button_html='".$paypal
."' WHERE id='".mysql_real_escape_string($id) ."'";
mysql_query($query) or die(mysql_error());
echo "successfully added the following paypal button to this product:
<br /><br />
{$paypal}";
}
}
?>
<?
if ($_GET['id']) {
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
A few problems:
You were not being consistent in sanitising your Database Input
You did not have clear validation rules
Your form was not setting the $_GET['id'] field (so the database submission was always failing)
Amended code:
<?php
// Init an Array to hold any error messages
$errors = array();
if( isset( $_REQUEST['submitedform'] ) ){
// Validate the required fields
if( !isset( $_POST['paypal'] ) || $_POST['paypal']=='' )
$errors['paypal'] = 'No value for "paypal"';
if( !isset( $_GET['id'] ) || !is_numeric( $_GET['id'] ) )
$errors['id'] = 'No value for "id"';
// If Validation was successful
if( !$errors ){
// Prepare the Variables for Database Usage
$paypal = mysql_real_escape_string( $_POST['paypal'] );
$id = (int) $_GET['id'];
// Template and Complete the SQL Query
$sqlTpl = 'UPDATE `video_info` SET paypal_button_html="%s" WHERE `id` = %s';
$sqlStr = sprintf( $sqlTpl , $paypal , $id );
// Submit the Query
if( !mysql_query( $sqlStr ) ){
// Something went wrong
$errors[] = 'An error occured when submitting the data to the database';
}else{
// Submitted OK
echo 'Successfully added the following paypal button to this product:'.$paypal;
}
}
}
// Check for any errors
if( $errors ){
// Show errors to user
echo 'The following errors occurred:';
echo '<ul><li>'.implode( '</li><li>' , $errors ).'</li></ul>';
}
?>
<?
if( isset( $_GET['id'] ) && is_int( $_GET['id'] ) ){
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php?id=<?php echo $_GET['id']; ?>" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
This code...
Includes the id in the form's action URL
Checks for the submission
Validates the submitted values
Creates the Database Query
Submits the Query
Checks the Query worked OK
AMENDED: Replaced is_int() with is_numeric() as, after RTFMing, I found that a string, comprised of only digits, will apparently return false if tested with is_int().
UPDATE
Please, use $_REQUEST OR $_GET OR $_POST but not all 3 of them.
Also, why don't you mysql_real_escape_string the variable $_POST['paypal'] ?
You mix $_GET and $_POST variables. You should use either GET or POST, but not both. If this is a post request, change $_GET['id'] to $_POST['id'].
In this case, the update doesn't fail because of where id = ''. This doesn't update anything, because there's no id with an empty string. But it also doesn't fail, since it is a valid update statement.

Categories