I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school
Related
I have this json file that I need to make a cron job for and receive SMS notification when data changes http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json
I need to find out if some server is on stock, so I found this code:
<?php
$cellphone = '15551234567';
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
$a = $tmp ['availability'];
$data = array();
foreach ($a as $item) {
if (!in_array($item ['reference'], $a_track)) {
continue;
}
foreach ($item ['zones'] as $zone) {
if ($zone ['availability'] == 'unavailable') {
continue;
}
$data [$item ['reference']] .= $zone ['zone'];
}
}
foreach ($data as $item => $availability) {
$message = "SYS STOCK: $item: $availability";
mail('my#email', 'OMG BUY THIS NOW!', $message);
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy& from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
$discard = file_get_contents($url);
}
The problem is that when I trigger it I receive SMS no matter if server is on stock or not and the SMSs keep coming with false positives. I also got this message :
]# /usr/bin/php /home/sys.php
PHP Notice: Undefined index: 143sys12 in /home/sys.php on line 22
I changed your code around a bit and moved the sending of the message in a function to be called when the reference is found.
Take a look:
<?php
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
foreach ($tmp['availability'] as $item) {
if (in_array($item['reference'],$a_track)) sendMeAnEmail($item);
}
function sendMeAnEmail($item){
$cellphone = '15551234567';
$message = "SYS STOCK: ". $item["reference"] . PHP_EOL;
$gotStock = 0;
foreach ($item["zones"] as $zone)
if ($zone["availability"] != "unavailable" and $zone['availability'] != 'unknown' ) {
$message .= "Available in the " . $zone["zone"]. " zone, with the " . $zone["availability"] . " status." ;
$gotStock++;
}
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy&from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
if ($gotStock > 0) {
print $message . PHP_EOL; // to check
mail('my#email', 'OMG BUY THIS NOW!', $message);
$discard = file_get_contents($url);
print "Got stock, sent mail and SMS" . PHP_EOL;
}
}
How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called
JSON_decode
I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?
Here is the data located:
http://csgo.nssgaming.com/api.php
The current script:
<?php
require_once ('simple_html_dom.php');
$html = #file_get_html('http://csgolounge.com/');
$output = array();
if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));
// Source: http://php.net/manual/en/function.strip-tags.php#86964
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE)
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
else
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
} elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
$additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;
$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;
foreach($match->find('.teamtext') as $key => $team) {
$output[$id]["teams"][$key] = array(
"name" => $team->find('b')[0]->plaintext,
"percent" => $team->find('i')[0]->plaintext
);
if(#$team->parent()->find('img')[0])
$result = array("status" => "won", "team" => $key);
}
if($additional)
$result = $additional;
if(isset($result))
$output[$id]["result"] = $result;
}
echo json_encode($output);
Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.
Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.