Basically, I have a table with 8 million codes for promotion. The contestant will enter the code on a gravity form, which will then query the database for code, once it is there the code will be marked as used, and the contestant should be redirected to the entry form. If not the form should tell the user code is invalid. This is my code below which I pulled from other sources because I am not a coder. However, when I submit, the correct code, it says incorrect. Any help will be appreciated just bear in mind I am not a programmer
add_filter( 'gform_field_validation_4', 'validate_code' );
function validate_code($validation_result){
$form = $validation_result['form'];
foreach( $form['fields'] as &$field ) {
if ( strpos( $field->cssClass, 'validate-code' ) === false ) {
continue;
}
}
$field_value = rgpost( "input_1" );
$is_valid = is_code( $field_value );
$validation_result['is_valid'] = false;
$field->failed_validation = true;
$field->validation_message = 'The code you have entered is not valid. Please enter another.';
$validation_result['form'] = $form;
return $validation_result;
}
function is_code($code){
$info = 'mysql response';
require_once(ABSPATH . '/wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo 'Unable to connect to server, please use the back button in your browser and resubmit the form';
exit();
}
$code = mysqli_real_escape_string($conn, $_POST['codes']);
$sql_check = mysqli_query($conn, "SELECT * FROM entrycode WHERE codes = '$code' AND valid = 0");
$sql_checkrows = mysqli_num_rows($sql_check);
if ($sql_checkrows > 0) {
$sql_update = "UPDATE entrycode SET used = 1 WHERE codes ='$code'";
if (mysqli_query($conn, $sql_update)) {
$info = mysqli_affected_rows($conn) . " Row updated.\n";
$info = 'success';
return true;
} else {
return false;
}
mysql_close($conn);
}
}
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://sample.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
so I modified the code from Phill, I am no longer getting the error, but the code is not being validated, as a matter of fact, any code I type in is valid., I am at a lost. My table is structured like this
entry codes table
ID
Codes
Used
34
98j65XF16
O
add_filter('gform_validation_4_1', 'validate_code');
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if($is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
// use this function to validate codes
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( $matched_codes > 0) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://demo.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
Updated function to validate codes:
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
this code i have still is not checking the database with codes for validation ,, all codes returning invalid code message
add_filter('gform_validation_2', 'validate_code');
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if(!is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
function is_code_valid($thiscode){
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_2', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$country = ($_POST['input_3']);
$success_url = 'https://sample.com/enter' . '/?code=' .$lead[1] .'&country=' .$country;
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
Related
I'm looking to (programmatically) edit/alter the title of a page when its created and before its saved. I've tried a couple hooks to no avail. I can access the title being saved along with other info which ill be used to alter the title, but can not find the right call to save the altered title.
It is for a private/local lan wiki (currently MediaWiki version 1.38.1 ).
When a new article is created with in a certon category I want to number it with a prefix of #### - based on the number of articles already in the category. At the top of the category page itself I have a <inputbox> which pulls a template that has the wiki syntax for the category in it [[Category:BlaBla]]. When the article is saved I'm doing a check to make sure its a new article and some ofther checks for the info I need, which is working fine, but I can not save the new altered page name.
I've tried the following hooks to no avail.
onMultiContentSave
onArticlePrepareTextForEdit
https://www.mediawiki.org/wiki/Manual:Hooks/MultiContentSave
https://www.mediawiki.org/wiki/Manual:Hooks/ArticlePrepareTextForEdit
Heres acouple snippets ive been testing with, both do as i want, aside from saving the altered page name.
public static function onArticlePrepareTextForEdit( WikiPage $wikiPage, ParserOptions $parserOptions ) {
return;
$exists = $wikiPage->exists();
if ($exists == 1) {
#return true;
}
$getTitle = $wikiPage->getTitle();
# check if title starts with 0000, exit if so, no work needs to be done
if (self::titleCheck($getTitle)) {
#return true;
}
$checkCategories = $wikiPage->getCategories();
$inMalak = false;
foreach ($checkCategories as $value) {
if ($value == "Category:Malak") {
$inMalak = true;
}
}
if ($inMalak == 1) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
print(">" . $newTitle . "<br>");
}
self::pr($newTitle);
}
public static function onMultiContentSave(RenderedRevision $renderedRevision, UserIdentity $user, CommentStoreComment $summary, $flags, Status $hookStatus){
#return;
$revision = $renderedRevision->getRevision();
$getTitle = $revision->getPageAsLinkTarget();
if (self::titleCheck($getTitle)) {
return true;
}
#$titleOBJ = $revision->Title();
$title = $revision->getId();
$parent_id = $revision->getId();
$content = $revision->getContent( SlotRecord::MAIN );
$new_content = $content->getText();
#$test = $revision->ParserOutput();
$parent_id = "";
if ($parent_id == "") {
$pos = strpos($new_content, "[[Category:Malak]]");
if ($pos) {
$newTitle = self::newTitlePre() . $getTitle;
#$wikiPage->setTitle($newTitle);
}
}
self::pr($newTitle);
}
EDIT........
Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}
Still have not found the proper way to do this, but came up with a work around (hackery) which works for my needs.
Using the onEditFormPreloadText hook, change the url and added a new parameter ('MalakHere'), edited the 'title' parameter to the altered title, then do a redirect with the new page name. In the hook function there is a check for the 'MalakHere' parameter, if found (only cause of redirect) then it will exit the function so not to create a loop.
public static function onEditFormPreloadText(string &$text, Title &$title ) {
global $wgOut;
if ( isset( $_GET["MalakHere"] ) ) {
return true;
}
$pos = strpos($text, "[[Category:Malak]]");
if ($pos) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlTitle = urlencode($_GET["title"]);
$newURL = str_replace("title=" . $urlTitle,"MalakHere=yes",$url);
$newTitle = self::newTitlePre() . $title->prefixedText;
$url = $newURL . "&title=" . $newTitle;
return $wgOut->redirect($url);
}
return true;
}
I have this working function meant to be used for a WordPress Multisite Database query. It's perfectly okay but I want to know if it is possible to output the desired results using return instead of echo.
Every solution and example I've come across uses echo.
function akwQueries_byMembership( $memID ){
switch_to_blog( akw_memSiteID() );
global $wpdb;
$user_id = get_current_user_id();
$prefix = $wpdb->prefix;
$membershipTable = $prefix.'membership_users_table';
$query="SELECT members_id, status
FROM $membershipTable
WHERE members_id=$memID AND user_id=$user_id AND status='active'";
$req_memid=$wpdb->get_row($query);
if( $req_memid !== null ){
// My question arises from here...
echo 'Good to go';
} else {
echo 'Not ok';
}
restore_current_blog();
}
I tried using return and it's so lifeless. I would love, for instance, to return true.
Move the restore function up above the return statement and then return the boolean.
function akwQueries_byMembership( $memID ){
switch_to_blog( akw_memSiteID() );
global $wpdb;
$user_id = get_current_user_id();
$prefix = $wpdb->prefix;
$membershipTable = $prefix.'membership_users_table';
$query="SELECT members_id, status
FROM $membershipTable
WHERE members_id=$memID AND user_id=$user_id AND status='active'";
$req_memid=$wpdb->get_row( $query );
restore_current_blog();
return $req_memid !== null;
}
I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...
I have a somewhat unorthodox (i guess) question. I have a function that adds a record to my MYSQL DB, with location lat and lng info. However sometimes that function is not working correctly, causing for the the DB record not to be created. Therefore I would like to create a loop to keep checking if the function created the DB record and if not, do the function again.
Just to be clear; the function I use is a default GEOMyWP function (reference). Sometimes it is not working properly, I guess due to the Google maps API response time.
I have the following in my functions.php and it seems to be working. I really would like to know if this is a proper way to accomplish the above, since I am not sure. Thanks
global $wpdb;
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
if ($myccount <= 0) :
while ($myccount <= 0) :
gmw_pt_update_location( $args ); //The function I would like to check.
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
endwhile;
endif;
Below is the function that i use to import the address, when creating a post for a CPT
function gmw_update_post_type_post_location( $post_id ) {
// Return if it's a post revision
if ( false !== wp_is_post_revision( $post_id ) )
return;
// check autosave //
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
//check if user can edit post
if ( !current_user_can( 'edit_post', $post_id ) )
return;
//Add post Meta
add_post_meta($post_id, 'address', $_POST['address'], false);
//get the address from the custom field "address"
$addressarray = get_post_meta( $post_id, 'address', true );
$address = $addressarray[0];
//$address = $_POST['address'];
//varify that address exists. Otherwise abort the function.
if ( empty( $address ) )
return;
//include the update location file file
include_once( GMW_PT_PATH .'/includes/gmw-pt-update-location.php' );
//make sure the file included and the function exists
if ( !function_exists( 'gmw_pt_update_location' ) )
return;
//Create the array that will pass to the function
$args = array(
'post_id' => $post_id, //Post Id of the post
'address' => $address // the address we pull from the custom field above
);
//Start counting 1
global $wpdb;
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
if ($myccount <= 0) :
while ($myccount <= 0) :
//Add location
gmw_pt_update_location( $args );
//Start counting 2
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
endwhile;
endif;
}
//execute the function whenever post type is being updated
add_action( 'save_post_mpp-gallery', 'gmw_update_post_type_post_location', 13, 1 );
Function that is inserting a record to the db is eventually: gmw_update_location
This function can be found in the GEOMyWP plugin. See this link for some reference: https://github.com/Fitoussi/geo-my-wp/blob/master/includes/gmw-location-functions.php#LC194
I am using Yii2 and ActiveRecord. I have a field called "code" and for each record, it is meant to have a unique value like this: "REC0001", "REC0002", "REC0003" in a sequencial manner.
All works and I can generate a record code as described. However if I refresh my page request fast in a multiple manner (trying to test multiple requests at the same time in a very raw manner hehe), then some of the records end up with the same record code. In other words I found "REC007" a few times.
I generate the code looking at the last code and increase it by one, then I do a while foundFlag == true by checking to see if it already exists in the database.
I am suspecting there is a delay in writing to the database and hence it assumes that it is not there.
Here is a portion of the code:
static function createCode($rec){
if ($rec->code){
return $rec->code;
}
if ($rec->id){ // find it by id if one passed and record exists
$tmpRec = $rec->find()
->where([
'id' => $rec->id,
])
->one();
if ($tmpRec && $tmpRec->code){
return $tmpRec->code;
}
}
$prefix = 'REC';
if (!$prefix){
$prefix = 'REC';
}
$maxDecimals = 12;
$codeLength = $maxDecimals+strlen($prefix);
$query = $rec->find();
$query = $query->where([
'archived' => '0'
]);
// look under an organization if it exists in the model and there is one
if ($rec->hasField('organization_id') && $organization_id){
$query = addQueryWhere($query, [
'organization_id' => $organization_id,
]);
}
$query = addQueryWhere($query, [
'LENGTH(code)' => $codeLength*1,
]);
$query = $query->orderBy('code desc');
$lastRec = $query->one();
$tmpNumber = 0;
if ($lastRec && $lastRec->id){
// check what it returns
$tmpNumber = str_replace($prefix, '', $lastRec->code);
}
$tmpNumber++;
$leftDecimals = $maxDecimals - strlen($tmpNumber.'');
for ($k=0; $k <= $leftDecimals-1 ; $k++){
$tmpNumber = '0'. $tmpNumber;
}
$ret = $prefix . $tmpNumber;
return $ret;
}
public function generateCode($rec){
$foundFlag = true;
$break = 1000; // safe break point - no continuous loop
$cnt = 0;
$code = static::createCode($rec);
while ($foundFlag === true || $cnt < $break){
$tmpRec = $rec->find()
->where([
'code' => $code,
])
->one();
if (!$tmpRec->id){
$foundFlag = false;
break;
}
$time = getCurrentTimestamp();
$code = static::createCode($rec);
$cnt++;
}
$ret = $code;
return $ret;
}
So I simply call: $this->code = $this->generateCode();
Like I said it does work in generating the code, but it creates duplicates when it shouldn't!
Thank you for your assistance.