PHP script called from within AngularJS service does not work - php

I've made a simple PHP script to update a mysql database. When I run this script as a standalone script, it works as expected. However when I call this script from within an AngularJS Service it does not do the job.
This is my script:
<?php
include('../connection/connection.php');
$data = json_decode(file_get_contents("php://input"));
date_default_timezone_set('CET');
$cursist_id = $data->cursist_id;
$id_ggv = $data->id_ggv;
$cursist_id = intval($cursist_id+1);
$id_ggv = intval($id_ggv+1);
try {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = " UPDATE crskrt_ggv
SET cursist_id = '$cursist_id'
WHERE id_ggv ='$id_ggv' ";
$db->exec($q);
//echo json_encode($id);
}
catch(PDOException $e)
{
echo $q . '</br>' . $e->getMessage();
}
echo "cursist_id: ". $cursist_id;
echo "id_ggv: " . $id_ggv;
echo $q;
When I check the network tab in the developers console, I can see that the right variables are returned. However, the database is not updated.
Anyone have any idea?

Related

PDO and query troubleshoot - basic

I am converting an old php 5.6 code to 7.2 and learning how to use PDO.
I have reached a point where I got stuck and would like to learn from the community.
I created a test file structure:
db.php:
<?php
try {
$conn = new PDO($initlocation, $username, $pwdata);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "worked"; // THIS WORKS ON THE SCREEN
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
test.php:
<?php
include("db.php");
$user_query='SELECT * FROM `users` WHERE `email`="user1.a#gmail.com"';
echo $user_query; // I GET THE QUERY PRINTED ON THE SCREEN
echo is_object($conn); // THIS IS 1 WHICH IS GOD
echo "<br>";
echo is_object($res); // THIS IS 1 WHICH IS ODD
try{
$res = $conn->query($user_query);
}
catch (Exception $e){
echo "Query failed: " . $e->getMessage(); // NOTHING
}
echo "<br>";
echo is_object($res); // NOTHING
$data_exists = $res->fetch();
if ($data_exists==1) echo "yes"; // NOTHING
?>
I have left the testing method in the code as well and I am keen to find a better solution to find out why the query does not show anything.
The aim would be to find the email address in the DB and give me some feedback about it. Thank you in advance all the comments I will only learn form them.
Additional info:
When I run the SQL query in the DB directly it does give me the record that has the same email.
Try the following and use prepared statements like protection from SQL injections.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

iTunes Search API: Update Notification

i'm using iTunes API Search and Advanced Custom Field WordPress plugin so the wp author can add a mac app id to a custom field and the implanted iTunes Search API above will add all the other information of app automatically in the wp post. and when app information updated my wp post will have the updated info like last verion number app size and ...
but the problem is my own wrote review and guide of any verion of any app inside my website and it need to be updated manually.
for example i have added a post for version 3.7.1 of "Things 3" mac app using method above to my WordPress and i have reviewed this version with my own description and hand-wrote in the post.
now i need to get notified when ever this app gets a new version or update so i can update my review and add some text for new version inside the post as well.
is there any way or method you guys can think of, so i can get notified when ever an app i have reviewed in my site gets an update ?
i really appreciate any way or taught !
Thanks.
There is no native API to do what you're asking.
However, with a little coding I believe you could use the RSS feed of the application to then create something to notify you on a change.
See Example for the App HomeScan
https://itunes.apple.com/lookup?id=1380025232
ID= YOURAPPID
I believe this should give you some general direction to do what you need.
This is a reply to our comment history in the other answer.
#erfanMHD, there are a number of ways to really do this. You don't have to do it in javascript. This isn't really something someone can give you an easy code snippet for since it requires a few additional things and is generally frowned upon in StackOverflow.
You'll need somewhere to store the localVersion of the application of the review you last wrote. In the example I wrote below I used a simple MySQL database to hold the local version. You'll also need to figure out how you want to display the data. I know you can add stuff to the wordpress dashboard but this isn't something we can show you how to do via StackOverflow.
However, below is a very simple (JUST FOR REFERENCE) purposes only on how one could achieve what you're trying to do. However this is just an example to guide you along the process.
For this demo, you'll need a MySQL database with a DBName of test and and a record created called application_version with 3 rows. ID, Name, Version.
<?php
$servername = "localhost"; // Your MySQL Server
$username = "root"; // Your MySQL Username
$password = "password"; // Your MySQL Password
$dbname = "test"; // The name of your MySQL database
$id = "904280696"; // The ID of the applicaiton you're wanting to check
function search($searchTerm){
// Construct our API / web services lookup URL.
$url = 'https://itunes.apple.com/lookup?id=' . urlencode($searchTerm);
// Use file_get_contents to get the contents of the URL.
$result = file_get_contents($url);
// If results are returned.
if($result !== false){
// Decode the JSON result into an associative array and return.
return json_decode($result, true);
}
// If we reach here, something went wrong.
return false;
}
function updateVersion($id, $name, $version) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Save the Version information
$sql = "UPDATE application_version SET name='" . $name . "', version='" . $version . "' WHERE id='" . $id . "'";
echo $sql;
echo "<br>";
// Run the Insert into MySQL
if ($conn->query($sql) === TRUE) {
// Print On Success
echo "Record Updated Successfully";
echo "<br>";
} else {
// We dun goofed
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
function getLocalVersion($id) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM application_version WHERE ID = " . $GLOBALS['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Found Application ID Entry in database";
echo "<br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Version</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["version"]."</td></tr>";
$GLOBALS['storedVersion'] = $row["version"];
}
echo "</table>";
echo "<br>";
} else {
echo "No Application ID Entry found in database";
echo "<br>";
}
$conn->close();
}
// Search for your requested ID
$searchResults = search($GLOBALS['id']);
$currentVersion = '0.0.0';
$storedVersion = '0.0.0';
$appName = 'null';
// Loop through the results.
foreach($searchResults['results'] as $result){
// Pass the current version to variable
$currentVersion = $result['version'];
$appName = $result['trackName'];
// Get the current version or what ever else information you need
echo 'Current Version: ' . $currentVersion;
echo "<br>";
echo "<br>";
}
// Get Local Version from database
getLocalVersion($id);
if ($currentVersion > $storedVersion) {
echo "You have an old version friend";
echo "<br>";
// Write what you want it to do here
updateVersion($id, $appName, $currentVersion);
} else {
echo "You're all up to date";
echo "<br>";
// Write what you don't want it to do here
}
?>
Again, this is just quick and dirty. You'd want to do a lot of additional checks and balances. One I see right off the bat would be in the check for inserting.

Using .php to write data to database

Can someone point the fault in this code? I'm unable to update data to the database. We are sending a text message to the server, and this file here decodes and sets it in the database. But this case over here is not working for some reason. I checked and tried to troubleshoot, but couldn't find a problem.
case 23:
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = $machine_press/20;
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`=".$UnixTime.",`machine_press`=".$machine_press.",`machine_pct_full`=".$machine_pct_full.",`machine_cycles_return`=".$machine_cycles_return.",`machine_cycles_total`=".$machine_cycles_total." WHERE `machine_serial`='$MachSerial'";
// Performs the $sql query on the server to update the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ($SeqNum,$UnixTime,'$siteDID','$MachSerial',$machine_press,$machine_cycles_total,$machine_cycles_return,$machine_pct_full)";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
break;
More information is required to help you out with your issue.
First, to display errors, edit the index.php file in your Codeigniter
project, update where it says
define('ENVIRONMENT', 'production');
to
define('ENVIRONMENT', 'development');
Then you'll see exactly what the problem is. That way you can provide the information needed to help you.
I just saw that you are inserting strings when not wrapping them in apostrophe '. So you queries should be:
$sql = "UPDATE `machines` SET `machine_last_run`='".$UnixTime."',`machine_press`='".$machine_press."',`machine_pct_full`='".$machine_pct_full."',`machine_cycles_return`='".$machine_cycles_return."',`machine_cycles_total`='".$machine_cycles_total."' WHERE `machine_serial`='$MachSerial'";
and
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . " VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
For any type of unknown problems I can recommend turning on PHP and SQL errors and use a tool called postman that i use to test my apis. You can mimic requests with any method, headers and parameters and send an "sms" just like your provider or whatever does to your API. You can then see the errors your application throws.
EDIT
I tested your script using a fixed version with ' and db.
$Message = "value1:value2:value3";
$MachSerial = "someSerial";
$SeqNum = "someSeqNo";
$siteDID = "someDID";
$pdo = new PDO('mysql:host=someHost;dbname=someDb', 'someUser', 'somePass');
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = (int)$machine_press/20; // <----- Note the casting to int. Else a warning is thrown.
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`='$UnixTime',`machine_press`='$machine_press',`machine_pct_full`='$machine_pct_full',`machine_cycles_return`='$machine_cycles_return',`machine_cycles_total`='$machine_cycles_total' WHERE `machine_serial`='$MachSerial'";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
It totally works. Got every cycle inserted and machines updated. Before i fixed it by adding wrapping ' i got plenty of errors.
Alright so this is the solution:
i replaced the line:
$Message = preg_replace("/\s+/","%20", $Message);
with:
$Message = preg_replace("/\s+/","", $Message);
This removes all blank spaces in my text message and makes it a single string before breaking and assigning it to different tables in the database.
I understand this wasnt really a problem with the script and no one around would have known the actual problem before answering. and thats why i am posting the solution just to update the team involved here.

Run PHP script in same directory as wordpress, but without it

Let's say I've got a PHP script called import.php (code at the bottom) which is stored in the same directory (root) as my wordpress website. My issue is when I would like to run that script by typing: www.mydomain.com/import.php of course it launches wordpress with 404 ERROR.
How can I run this script somehow outside wordpress environment / exclude it from wordpress?
My script is dedicated to database update (via real cron), that's why i dont want to use wordpress for that.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$mysql_host = 'localhost';
$mysql_username = '';
$mysql_password = '';
$mysql_database = '';
$db = new PDO('mysql:dbname='.$mysql_database.';host='.$mysql_host,$mysql_username,$mysql_password);
// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
function truncate_db()
{
global $db;
$sql_query_1 = "
TRUNCATE TABLE `WIZYTY`;
TRUNCATE TABLE `ANIMALS`;
TRUNCATE TABLE `DOCTORS`;
TRUNCATE TABLE `CUSTOMER`
";
try {
$stmt = $db->prepare($sql_query_1);
$stmt->execute();
echo "Truncate action - OK";
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
}
function import_db()
{
global $db;
try
{
$sql_query_2 = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/*.sql")));
$qr = $db->exec($sql_query_2);
echo "Import action - OK";
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
truncate_db();
echo '<br />';
import_db();
$db = null;
?>
You should add something like this on
.htaccess
<FilesMatch "^import\.php$">
Allow from all
</FilesMatch>
Anyway, you shouldn't have it on the root folder, check wordpress for better solutions
Wordpress Event Scheduler
https://codex.wordpress.org/Function_Reference/wp_schedule_event
And here you have a great example
https://tommcfarlin.com/wordpress-cron-jobs/

Is read() necessary before write() with SSH via PHPSecLib?

I have written a small script that issues a series of commands via write() to a linux machine, with a 5 second sleep() between each one. The exact same commands work when entered manually but despite being connected successfully, do not seem to work when used from a PHP script.
As this is the case, I am curious if using read() is absolutely necessary prior to issuing a write() command?
<?php
include('Net/SSH2.php');
$serverhostname = "IP_HERE";
$ssh_username = "root";
$ssh_password = "PASS_HERE";
// Establish new SSH2 Connection
$connection = new Net_SSH2($serverhostname, 22);
if($connection->login($ssh_username, $ssh_password))
{
echo "LOGGED IN! </br>";
sleep(5);
$result = $connection->write('en PASS_HERE\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('configure terminal\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('interface ve 110\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('port-name Test_Brett\r\n');
echo "RESULT: " . $result . " </br>";
}
else
{
echo "SSH Connection Failed. Check that the remote host is online and accepting connections!";
}
?>
UPDATE
$result = $connection->write('en PASS_HERE\n');
$result = $connection->write('configure terminal\n');
$result = $connection->write('interface ve 110\n');
$result = $connection->write('port-name Test_Brett\n');
$connection->setTimeout(5);
echo $connection->read();
I just did this:
$connection->write("ls -la\n");
$connection->write("pwd\n");
$connection->setTimeout(5);
echo $connection->read();
And it seemed to perform the commands just fine without a read() between the two write()'s. But it could be that a read() has to be done, even if just once, at the end.
What I'd do if I were you is, instead of doing sleep(5) do $connection->setTimeout(5); $connection->read();. You can throw away the return value of read(). If you knew what to expect back you could just do $connection->read('pattern'), which would be faster, but if you don't, I'd do the $connection->setTimeout(5); route just to be on the safe side.

Categories