AngularJS .get Method Causing Internal Error 500 - php

I've got a working version of the code on my local machine using xampp but when I uploaded it to my Raspberry Pi it seems to go haywire.
Basically I've got an angularjs script calling a file called dbConn.php which is in the same directory and works on a local machine but doesn't when uploaded to a Pi.
function raspberryController($scope, $http, $timeout) {
var poll = function() {
$timeout(function() {
try{
$http.get("dbConn.php")
.success(function(response) {$scope.names = response;})
.error(function(data, status, header, config) {
console.log(alert, status, header, config);
});
} catch (e) {
console.log("Got an error!",e);
throw e;
// rethrow to not marked as handled
}
poll();
}, 1000);
}
poll();
}
dbConn.php
<?php
//$db = new SQLite3('system/modules/test.db');
header("Access-Control-Allow-Origin: *");
try{
$dbh = new PDO('sqlite:system/test.db') or die("cannot open db");
} catch(Exception $e) {
echo $e->getMessage();
}
$query = 'SELECT * FROM connected;';
$results = $dbh->query($query);
$outp = '[';
foreach($dbh->query($query) as $row){
if ($outp != "[") {
$outp .= ",";
}
$outp .= ' { "ID":"' . $row[0] .'",';
$outp .= '"IP":"' . $row[1] .'",';
$outp .= '"CONNECTED":"' . $row[2] .'",';
$outp .= '"LEASE_TIME":"' .$row[3] .'" } ';
}
$outp .= ']';
echo($outp);
?>

You have:
try { $dbh = new PDO('sqlite:system/test.db') or die("cannot open db"); } catch(Exception $e) { echo $e->getMessage(); }
You're trying to call the query() function on the $dbh object outside of the try.
Here's a link to variable scoping in PHP: http://php.net/manual/en/language.variables.scope.php
To solve your problem either have an empty $dbh variable outside the try block and then initialise it within the try eg:
$dbh = null;
try {
$dbh = new PDO('sqlite:system/test.db') or die('cannot open db');
} catch (Exception $e) {
//some code to handle it in here
exit(); //to stop anything else from executing
}
$result = $dbh->query();
The other way to solve the problem would be to put the rest of your code in the try/catch block you've created for the initialisation of the $dbh variable.
try {
$dbh = new PDO('sqlite:system/test.db') or die('cannot open db');
$query = 'SELECT * FROM connected;';
$results = $dbh->query($query);
$outp = '[';
foreach($results as $row){
if ($outp != "[") {
$outp .= ",";
}
$outp .= ' { "ID":"' . $row[0] .'",';
$outp .= '"IP":"' . $row[1] .'",';
$outp .= '"CONNECTED":"' . $row[2] .'",';
$outp .= '"LEASE_TIME":"' .$row[3] .'" } ';
}
$outp .= ']';
echo $outp;
} catch (Exception $e) {
echo $e->getMessage();
}
You'd be better off abstracting DB logic into a separate class and using it like a Singleton or a static class as detailed in this other post: Best practices for a PDO class?.
Oh and for future reference, the easiest way to find out what's going wrong if you're met with a unhelpful err 500 is to use tail -f /var/log/apache2/error.log from your terminal if you're using a Debian distro such as Raspbian.

Related

Php code to get json data from mysql database

Iam trying to create a JSON object out of my SQL data in PHP. How to do that?
This is my approach, which does not work so far.
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros = "[";
while ($result = $query->fetch()) {
if ($registros != "[") {
$registros .= ",";
}
$registros .= '{"id": "' . $result["id"] . '",';
$registros .= '"name": "' . $result["name"] . '"}';
$registros .= '"salary": "' . $result["salary"] . '"}';
$registros .= "]";
echo $registros;
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>`
Why dont you try the json_encode() for this ? Why you try for unnecessary while loop.
$query = $conn->prepare('SELECT id, name, salary from afreen');
Then try the json_encode() to get the Data in Json format.
Sources - http://php.net/json_encode
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
header('Content-Type: text/html; charset=utf-8');
$dns = "mysql:host=localhost;dbname=afreen";
$user = "root";
$pass = "";
try {
$conn = new PDO($dns, $user, $pass);
if (!$conn) {
echo "Not connected";
}
$query = $conn->prepare('SELECT id, name, salary from afreen');
$query->execute();
$registros= [];
while ($result = $query->fetch()) {
array_push($registros,array(
'id' =>$result["id"],
'title' =>$result["name"],
'salary' =>$result["salary"]
));
$output = json_encode(array("product"=>$registros));
print_r($output);
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>

PHP FetchAll() Not returning rows

I was wondering if somebody could help shed some light as to why this PHP code is not entering into the for loop? In MySQL the query returns the appropriate rows that I need but in this PHP file it fails to return anything into the array, thus not executing the foreach loop.
CODE
<?php
try {
$sql = 'SELECT FirstName,LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN employee USING(EmployeeID) ';
$sql .= 'JOIN contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I even have the program echo the SQL query and I copy that into MySQL and it still works. Could it be a simple syntax error or is it the table joins that im performing?
Also im certain that the program is contacting the database correctly because I have other similar PHP files working properly like this one:
<?php
try {
$sql = 'SELECT department.Name FROM adventureworks.department';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo '<ul>';
foreach ($stmt->fetchAll() as $depts) {
echo "<li>" . $depts["Name"] . " -> (" .
"<a href='deptEmps.php?deptID=" . $depts['deptID']
. "'>Employees </a>)" . "</li>\n";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
The problem with the PHP script was that I was not specifying which tables to select from. This was harder than it should have been since the syntax above returned data in MySQL which was the database I was accessing, The correct PHP script that is working can be found below:
Working PHP:
<?php
try {
$sql = 'SELECT contact.FirstName,contact.LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN adventureworks.employee USING(EmployeeID) ';
$sql .= 'JOIN adventureworks.contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I was wrong that the tables would have been assumed through the JOIN in PHP as they are in MySQL.

how to call the function once at a time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm working on my PHP script to call the function once at a time when I click the link on my site.
When I click the link on my site to connect to the get-listing.php script, it will call to both function of tvguidecom and skyuk at the same time which it will output one of those webpage.
I think the problem are on this line:
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
Here is the full code:
<?php
$errmsg_arr = array();
$errflag = false;
$link;
include ('simple_html_dom.php');
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'mydbname');
define('DB_PASSWORD', 'mydbpassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
function tvguidecom($row)
{
include ('tvguide.get-listing.php');
}
function tvguide2($row)
{
include ('skyuk.php');
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = "";
$id = "";
if(isset($_GET['channels']))
{
$channels = $_GET['channels'];
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row);
skyuk($row);
}
mysql_close();
exit;
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '">http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . '</a><br><br>';
//echo "<p id='links'>";
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=' . $row["channels"] . "&id=" . $row["id"] . "'>http://example.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'>test</a></p>';
//echo '<a id="link1" href="http://example.com/get-listing.php?channels=';
echo '<a id="streams" href="' . $row['streams'] . '">Stream 1</a><br><br>';
}
}
}
?>
I want to call either of function once at a time when I click the link on my site. Example: I want to call tvguidecom function to see if it will output the data in my get-listing script or else move on to the next function and call the skyuk function.
Can you please show me an example of how I can call the function once at a time when I click the link on my site?
The best thing you can do is having your functions returning a boolean so you can check if you should continue the process.
I guess the function tvguidecom looks like:
function tvguidecom() {
// do something without return value
}
Add a return value in it:
function tvguidecom() {
// do something
return $status;
}
So in your code you can test for the return value
while ($row = mysql_fetch_array($result1))
{
if (tvguidecom($row)) {
skyuk($row);
}
}
Note: on a different topic, you shouldn't use anymore mysql extension because it is deprecated. You should use instead mysqli or pdo.
TL;DR
while ($row = mysql_fetch_array($result1))
{
// this ensures that `tvguidecom()` does its stuff, and `skyuk()`
// waits for results returned by the function.
skyuk(tvguidecom($row));
}
function tvguidecom($row) {
// do stuffs, returns original input $row;
return $row;
}
** Another approach, callbacks.**
while ($row = mysql_fetch_array($result1))
{
tvguidecom($row, callback);
}
and fn:
tvguidecom(a, callback) {
// dostuffs and when complete
callback( result );
}
** syntax may be incorrect, refer to link supplied. Hope this helps.

Angular crashing while there is a "Enter" in json file

So basically i have json file made from SLQ database by PHP script
Geting angular to read json and binds to scope
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://kserwach.nazwa.pl/extremerun/data.php")
.success(function (response) {$scope.names = response.records;});
});
You can look at json file by simply enterning this link
[http://kserwach.nazwa.pl/extremerun/data.php][1]
My problem is that, while i put any "new line" in SQL angular crashes. How can i make angular to not crash while someone press "enter button" while writing new desc? Or else how to make json file to replace this "enter" with some html tag, and then how to make angular to read this html tag?
This is how i read mySQL data
<?php
$user='user_name';
$password='password';
$dbname='db_name';
$host='host';
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname.';',$user,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>"; die();
}
$stmt = $db-> query('SELECT name,description,surname,photo FROM mates');
$temp = 0;
$outp = "";
foreach($stmt as $row)
{
if($temp == 0) {
$outp .= '{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
$temp = 1;
} else {
$outp .= ',{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
}
}
$outp ='{"records":['.$outp.']}';
echo($outp);
?>
And then, sorry for my bad english. Just not primary, or even secondary language.

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

Categories