Data not inserting in custom table with code in functions.php - 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

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

$wpdb SELECT query errors

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

My php comment validation function is not working whenever i call it

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.

get post Id in plugin

I am making a plugin in wordpress. And I am trying to get the post id when I click the publish button on the add new post. And now, I get an internal error(500) when I use the get post function.
I am using_POST['post'] now, but how can I use the wordpress function to get the post id?
Here is my code:
//require the php
require_once( FACEBOOK_API_PLUGIN_DIR . 'js/databaseConnection.php' );
Code on databaseConnection.php:
function get_post()
{
global $wp_query;
$thePostID = $wp_query->post->ID;
return $thePostID;
}
function try_insert($post_id)
{
$test02 = 333243;
$test03 = 222;
$link = #mysqli_connect(
'localhost',
'root',
'',
'wordpress'
) or die("connection failed");
$sql = "INSERT INTO post_data02 (post_id, condition_code) VALUES ('$post_id','$test03')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
$link->close();
}
add_action( 'publish_post', 'try_insert', get_post());
Also, when I disable the get_post() function I error will be gone. What am I doing wrong?
thanks,
You don't need get_post at all and you are using the publish_post hook and add_action function incorrectly.
Additionally, have a look at the WPDB class. If your table is in the same database and schema as your WordPress tables you don't need to use mysqli_connect - WordPress has already connected to the database for you!
Note also that you should NEVER pass values into a string to be used as part of an SQL statement! This is a MASSIVE security risk! ALWAYS use prepared statements and parameters (WPDB provides this as well).
Try this:
function try_insert($post_id, $post)
{
// Pull in the global WPDB variable WordPress creates
global $wpdb;
$test02 = 333243;
$test03 = 222;
/*
* Insert record into the table "post_data02" with the values:
* "post_id" => The ID in $post_id passed by WordPress,
* "condition_code" => The number in $test03 (currently 222)
*/
$insert = $wpdb->insert( 'post_data02',
[ 'post_id' => $post_id, 'condition_code' => $test03 ],
[ '%d', '%d' ]
);
if( $insert !== false ) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
}
add_action( 'publish_post', 'try_insert', 10, 2);
Please re-read the links I provided above as they provide excellent examples and show you how to use the functions, methods, hooks, etc.

Trigger PHP function with HTML button

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

Categories