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.
Related
I have ajax which takes data (id, companyName, owed, oldRem) from a table in categorylist.php which is used in remit.php. Below is my ajax code categorylist.php which gets data from table row and it works well.
<script>
function payCompany(id, companyName, owed, oldRemit){
swal("Enter Amount:", {
title: companyName,
buttons: true,
closeModal: true,
content: "input",
})
.then((amount) => {
if (amount === "") {
swal("Oops!! You need to enter value.");
return false
}else{
$.ajax({
type: 'POST',
url: 'remit.php',
data:{
rid: id,
pay: amount,
company_Name: companyName,
old_Remit: oldRemit,
debt_owed: owed,
<?php
echo ' currentDate : "'.$savedate.'",'
?>
},
success: function(data){
swal(`Paid: ${amount} to ${companyName}`);
},
error: function(data){
swal(`Error remitting: ${amount} to ${companyName}`);
}
});
}
});
}
</script>
my code in remit.php. I couldn't confirm if the code is passed to remit.php from ajax. there was no error displayed when it was run.
<?php
#remit.php
/*
If you are using sessions you need to start a session!
*/
error_reporting( E_ALL );
session_start();
if( empty( $_SESSION['useremail'] ) OR empty( $_SESSION['role'] ) OR $_SESSION['role']=="Admin" ){
exit( header('Location: index.php') );
}
/*
Check that all fields that are required in the SQL have been submitted
*/
if( isset(
$_POST['rid'],
$_POST['pay'],
$_POST['currentDate'],
$_POST['compnyName'],
$_POST['old_remit'],
$_POST['debt_owed']
) ){
try{
include_once 'connectdb.php';
/*
When inserting, updating multiple tables there is some sense in using a transaction
so that if one part fails the db is not littered with orphan records
*/
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->beginTransaction();
$remitID = $_POST['rid'];
$new_remit = (double)$_POST['pay'];
$company = $_POST['compny_Name'];
$old_rem = (double)$_POST['old_remit'];
$total_debt = (double)$_POST['debt_owed'];
$current_date = $_POST['currentDate'];
$paid = $new_remit + $old_rem;
$currentDebt = $total_debt - $paid;
/*
The SQL command should use placeholders rather than embedded variables - the names are arbitrary
*/
$sql='INSERT INTO `tbl_category_remits` ( `payment_date`, `category`, `remitted` )
VALUES
( :pay_date, :comp, :remit )';
$stmt=$pdo->prepare( $sql );
$args=array(
':pay_date' => $current_date,
':comp' => $company,
':remit' => $new_remit
);
if( !$stmt->execute( $args ) )echo 'stmt#1 failed';
$sql='UPDATE `tbl_category` SET `remitted` =:payment , `debt` =:current_debt WHERE `catid`=:rid';
$stmt=$pdo->prepare( $sql );
$args=array(
':current_debt' => $currentDebt,
':payment' => $paid,
':rid' => $remitID
);
if( !$stmt->execute( $args ) )echo 'stmt#2 failed';
/*
If it all went well, commit these statements to the db
*/
if( !$pdo->commit() )echo 'commit failed';
}catch( PDOException $e ){
/*
Any problems, rollback the transaction and report issues -
not necessarily with the full `getMessage()` ~ perhaps just
'Error!' etc
*/
$pdo->rollBack();
echo $e->getMessage();
}
}else{
echo $e->getMessage();
}
?>
On the above code, I have an insert statement as well as update statements, both to different tables as shown below:
Please, what's wrong with my code? It doesn't seem to update and insert into the database. Please, I need help with this code!!
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
after connecting wordpress with another server, I get a special ID from that other server, but it is related to the ID from the wordpress user, how can I save this second ID to the base, and submit it to the user who after the login ?
$user_id = $arr['id'];
if($user_id){
$_SESSION['user_id'] = $user_id;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "localm");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//
// Attempt insert query execution
$sql = 'INSERT INTO wp_users (user_id) VALUES ("'.$user_id=$_SESSION['user_id'].'");';
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
I am currently using $ _SESSION and this id is saved while in that browser, but when the time it is signed it is gone. That is why I have to keep it in the base .. Which resets would be the easiest for this case? Thanks everyone
This will work with you if I understood the question ..
You will save the another ID to the add_user_meta, Then call it using the current Wordpress user ID and get_user_meta
function save_ID( $user )
{
//get current user details
if( !$user ) { $user = wp_get_current_user(); }
//check if session registered
if( !isset($_SESSION['user_id']) ){ return; }
//store the 2nd ID to user_meta
$user_id = $user->ID;
$another_id = esc_html( esc_js( $_SESSION['user_id'] ) );
add_user_meta( $user_id, 'user_2nd_id', $another_id);
}
add_action( 'wp_login', 'save_ID');
I hope I helped you.
Thanks.
If I run this code , the value in the SQL base is added 5x.
Code:
function token($u) {
include('../config.php');
$token=md5(rand()+$u);
$date = date('Y-m-d H:i:s');
$tokenQuery = 'INSERT INTO '.$prefix.'tokens(`token`, `user`, `date`) VALUES ("'.$token.'","'.$u.'","'.$date.'")';
$mysqli->query($tokenQuery);
}
token ('filips');
See how it look my SQL base
My config is:
$host = 'my server';
$user = 'my username';
$pass = 'my password';
$data = 'pn_16734995_filipcms_demo';
$prefix = 'fc_';
$mysqli = new mysqli($host,$user,$pass, $data);
$mysqli->query("SET NAMES 'utf8'" );
if ($mysqli->connect_errno) {
echo "Server not working: (" . $mysqli->connect_errnor. ") " . $mysqli->connect_error;
}
Nothing in your code will make the INSERT statement happen 5 times. However, if you echo "function called"; inside of your function, you can see if the function is being called 5 times, then you can figure out where up the line your function is being called 5 times.
you don't need to include the whole file just pass $mysqli as a parameter or put it in a global scope;
function token($u,$mysqli) {
}
OR
function token($u) {
global $mysqli;
}
So I can not figure out why this is not adding the content to the DB. I need to add the itemcode and item into the database then be able to read it. This is what i have:
add.php
include('dbconnect.php');
function get_posts() {
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
mysqli_close($con);
dbconnect.php
$con = mysqli_connect("localhost","root","root","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Connected to Database. Please Continue.";
}
Is anyone able to help?? This is weird to me that it is not working.
It looks like you are calling your insert query from inside of a function yet $con is in the global scope. To include $con within your function you must do this:
include('dbconnect.php');
function get_posts() {
global $con;
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<h1>record added</h1>;
window.location.href='index.php';</script>";
}
get_posts(); // you can call get_posts() here
mysqli_close($con);
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
And, be sure to call your function, it is as simple as typing the following:
get_posts();