Connecting with a mysql - mysql

We are trying to interface between a MySQL database and Google API using ajax and php (on line 3 "phpsqlajax_dbinfo.php" dedfines the database info). We want to create a marker with the lat/long from Google API, but we get the fatal error on "add(Child)"
Actual error message : "Call to a member function addChild() on a non-object"
How can we get the db to register and store the info?
<?php
require_once("phpsqlajax_dbinfo.php");
$xml = ("mapPointInfo.xml") ;
$newLatLng = $_POST['latlng']; //new markers LatLng
$newLatLng = substr($newLatLng, 1, -1); //removes first and last characters of
newLatLng which are ( and )
list($newLat, $newLng) = explode(",", $newLatLng);
//$newLng = substr($newLng, 1, 0);
$locName = $_POST['geoNameMarker']; //geocoded or simple incremented site name
$markerComment = $_POST['createMarker']; //comment entered by user
$userName = $_POST['user']; //acquire username from session
$voteValue = "likes"; //acquire vote value if any
date_default_timezone_set('America/New_York');
$timeStamp = date("m/d/Y G:i"); //get timestamp
year:month:date:hour:minutes:seconds (example: 11:6:31:14:31:42)
if($markerComment == null || $markerComment == '' || $markerComment == ' '){
$markerComment = ' ';
}
$markerComment = htmlentities($markerComment, ENT_QUOTES);
$locName = htmlentities($locName, ENT_QUOTES);
$marker = $xml->addChild('marker');
$marker->addAttribute('lat', $newLat);
$marker->addAttribute('lng', $newLng);
$marker->addAttribute('name', $locName);
$marker->addAttribute('type', 'user-sug');
$comment = $marker->addChild('comment', $markerComment); //add information to
latest/last marker
$comment->addAttribute('user', $userName);
$comment->addAttribute('vote', 'likes');
$comment->addAttribute('time', $timeStamp);
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
header ('http://www.wmuhotspotmap.org/');
exit();
?>

The fatal error? You get a fatal error. What was it? I'm guessing it has something to do with the fact that $xml is a string, but you're for some reason doing $xml->addChild() as if it were an object with functions.

Related

gravity forms validate field entry values against mysql table value

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

how to use searchmailbox() to search emails by passing date in the criteria of this method?

This is my function and in this line of code * $mailIds = $mailbox->searchMailBox(); * i'm facing problem .. i want to search latest email but if i write anything in this method i'm facing the syntax problem or the blank page. please anyone can help me in solving this problem?
public function actionCreate1()
{
$imapConnection = new ImapConnection();
$imapConnection->imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$imapConnection->imapLogin = 'example#gmail.com';
$imapConnection->imapPassword = 'password';
$imapConnection->serverEncoding = 'encoding'; // utf-8 default.
$imapConnection->attachmentsDir = '/';
$imapConnection->decodeMimeStr = true;
$mailbox = new Mailbox($imapConnection);
$mailbox->readMailParts = false;
$mailIds = $mailbox->searchMailBox();
foreach($mailIds as $mailId)
{
// Returns Mail contents
$mail = $mailbox->getMail($mailId);
// Read mail parts (plain body, html body and attachments
$mailObject = $mailbox->getMailParts($mail);
// Array with IncomingMail objects
echo '<pre>';
print_r($mailObject);
// Returns mail attachements if any or else empty array
$attachments = $mailObject->getAttachments();
foreach($attachments as $attachment){
echo ' Attachment:' . $attachment->name . PHP_EOL;
// Delete attachment file
unlink($attachment->filePath);
}
}}

Yii2 - Save data in database without repeating the same page w/ the same ip address

I already saved the data i needed in my database, I need to save only one URL on each IP address or user id but it keeps on saving every time I reloaded the page, so I need to get the URL and IP address but only once every page, then after 30 mins w/ the same IP address will be save when visiting the same page again.
Here's my code:
$ip = $_SERVER['REMOTE_ADDR']?:
($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
$page_view = new Pageview();
$user_view = User::find()->where(['id' => Yii::$app->user->id])->one();
$timedate = date('Y-m-d h:i:s');
$id = Yii::$app->request->url;
$view_count = Pageview::find()
->where(['user_ip'=> $ip])
->andWhere(['user_id'=> $user_view])
->andWhere(['page'=> $id])
->andWhere(['>=', 'date_time', date('Y-m-d h:i:s', strtotime('-30 minutes'))])
->count();
if($view_count == 0){
if(!Yii::$app->user->isGuest){
$page_view->user_id = $user_view['id'];
$page_view->user_ip = $ip;
$page_view->date_time = $timedate;
$page_view->page = $id;
$page_view->save(false);
}else{
$page_view->user_id = 0;
$page_view->user_ip = $ip;
$page_view->date_time = $timedate;
$page_view->page = $id;
$page_view->save(false);
}
}

youtube video info json object gives error

I am working on youtube api
and I want to get youtube video information using youtube video info JSON object
and I am using a code as given below but when I try to run this code it is showing error as "Video Is not cipher not needed to decode"
please help me to solve it out also tell me where is the problem in code
<?php
// Video with cipher signature
$video_id = "zDrNLZ1uJ2w";
// get_video_info url formation
// although for cipher signature we have to get the details from the video's webapge not from get_video_info object
$info_url = "http://www.youtube.com/get_video_info?el=detailpage&asv=3&video_id=".$video_id;
// youtube webpage url formation
$yt_url = 'http://www.youtube.com/watch?v='.$video_id.'&gl=US&persist_gl=1&hl=en&persist_hl=1';;
// get the contents from the url
$raw_data = file_get_contents($info_url);
// parse the data received and save it as an array
$output = array();
parse_str($raw_data,$output);
// check the status of the get_video_info object
if($output['status']=='ok'){
// check for the cipher signature
$cipher = (isset($output['use_cipher_signature']) && $output['use_cipher_signature']=='True') ? true : false;
// If cipher is true then we have to decode it
if($cipher == true){
// if cipher is true then we have to change the plan and get the details from the video's youtube wbe page
$yt_html = file_get_contents($yt_url);
// parse for the script containing the configuration
preg_match('/ytplayer.config = {(.*?)};/',$yt_html,$match);
$yt_object = #json_decode('{'.$match[1].'}') ;
/// check if we are able to parse data
if(!is_object($yt_object)){
echo 'Sorry! Unable to parse Data';
}else{
// parse available formats
$formats = $yt_object->args->url_encoded_fmt_stream_map;
// get the player id from assets section
$player_id = strbtwn($yt_object->assets->js,'html5player-','.js');
$player_id = explode("/", $player_id);
$player_id = $player_id[0];
echo 'Player ID: '.$player_id.'<br /><hr />';
// get the algo dictionary
// first check if the file exists
if(file_exists('./algo.json'))
$algos = json_decode(file_get_contents('algo.json'),true);
else{
// API call to fetch the algo dictionary
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
// saving the algo dictonary in local env for easy access
// Note: Developers should save the dictionary in their local env.
// Only make the API call for the new player ids which is not present in the algo dictionary.
// Repeated violation will results in IP ban.
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
}
/// check if the algo exist for the given player id
if(!array_key_exists($player_id, $algos)){
// if the algo dictionary is old then fetch a new one
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
$algo = $algos[$player_id][1];
}else{
$algo = $algos[$player_id][1];
}
echo 'Algo Used: '.$algo.'<br /><hr />';
// download links formation
$dlinks = array();
$links = explode(',',$formats);
echo 'Download links <br /><br />';
foreach ($links as $link) {
parse_str($link,$linkarr);
// parse link array one by one and decrypt the signature
$dlinks[$linkarr['itag']] = $linkarr['url'] . "&signature=" . decrypt($linkarr['s'],$algo);
echo $linkarr['itag'].'<br />';
echo $dlinks[$linkarr['itag']].'<br /><br />';
}
echo '<hr />';
}
}else{
echo 'Video Is not cipher not needed to decode';
}
}else{
echo 'Unable to get Video Info';
}
// string helper function
function strbtwn($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
// signature decoding
// parse the python string operation into php string operation
function decrypt($sig, $algo){
$funcarr = explode(' + ', $algo);
$decrypt = '';
foreach($funcarr as $singfunc){
$singfunc = substr($singfunc,2,-1);
$operators = explode(':', $singfunc);
if (sizeof($operators) == 1) {
$decrypt .= $sig[$operators[0]];
}
if (sizeof($operators) == 2) {
if($operators[0] == ''){
$decrypt .= substr($sig, 0 ,$operators[1]);
}
if($operators[1] == ''){
$decrypt .= substr($sig, $operators[0]);
}
if($operators[0] >= 0 && $operators[1] >= 0){
$decrypt .= substr($sig, $operators[0], $operators[1] - $operators[0]);
}
}
if (sizeof($operators) == 3) {
if($operators[0] == '' && $operators[1] == ''){
$decrypt .= strrev($sig);
}
if($operators[0] >=0 && $operators[1] == '' && $operators[0] != ''){
$decrypt .= strrev(substr($sig, 0, $operators[0] + 1));
}
if($operators[0] >=0 && $operators[1] >= 0 && $operators[0] != '' && $operators[1] != ''){
$decrypt .= strrev(substr($sig, $operators[1] + 1, $operators[0] - $operators[1]));
}
}
}
return $decrypt;
}
?>
According to your code $cipher is being set to false because 'use_cipher_signature' is not found in the $raw_data from file_get_contents($info_url).

Excel Not Saved as Numeric Format (MySQL to Excel)

I have a script that allows me to convert a database from MySQL to Excel .xls format, It was a success,
here is the code
<?php
// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!
// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
$cdate = date("Y-m-d");
$dbhost = "localhost";
$dbuser = "-";
$dbpass = "-";
$dbname = "-";
$dbtable = "-";
$filename = "C:\xxx";
// END CHANGING STUFF
// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got
// them from some where else but hey it works so I am not going to question it
// just reuse
// This one makes the beginning of the xls file
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// This one makes the end of the xls file
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." ";
$qr = mysql_query( $q ) or die( mysql_error() );
//start the object
ob_start();
// start the file
xlsBOF();
// these will be used for keeping things in order.
$col = 0;
$row = 0;
// This tells us that we are on the first row
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
// Ok we are on the first row
// lets make some headers of sorts
if( $first )
{
// di comment karena ini ngasih label tabelnya, sepertinya nggak butuh
//foreach( $qrow as $k => $v )
//{
// // take the key and make label
// // make it uppper case and replace _ with ' '
// xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
// $col++;
//}
// prepare for the first real data row
$col = 0;
$row = 0;//$row++; // nyoba
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
//write the contents of the object to a file
file_put_contents($filename, ob_get_clean());
?>
this code produced a .xls file. I used Matlab to read my .xls file through readxls function, but it didn't recognize the value inside the .xls file as a numeric data, so my script on matlab couldn't make a matrix from reading my xls file. I had to convert it manually inside excel, there were some pop-ups near the value that offers me to convert it into numbers
If your goal is to take data from MySQL and put it in Matlab it might be easier to directly connect to MySQL from Matlab rather than sending the data through the xls format.
http://www.mathworks.com/help/database/ug/database.fetch.html