I have made an "api", I have converted data from my sql table into JSON and that is echoed onto my file "api.php", I have "get.php" and I would like to get specific bits of data from the JSON on get.php. It's not working and just throwing an error however
This is for a contract, I have already tried cURL but it doesn't work
api.php (not included login variables)
$dblink = new mysqli($servername, $username, $password, $dbname);
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
$result = $dblink->query("SELECT * FROM updates LIMIT 3");
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata);
and this is what I see on api.php, the JSON is corrected echod i just can't access it.
[{"id":"1564343527","title":"title","type":"Server","overview":"overview","added":"a:2:{i:0;s:6:\"added1\";i:1;s:6:\"added2\";}","removed":"a:2:{i:0;s:8:\"removed1\";i:1;s:8:\"removed2\";}","changed":"a:1:{i:0;s:0:\"\";}","date":"2019\/07\/28","time":"09:52:07pm"}]
get.php
<?php
$strJsonFileContents = file_get_contents('api.php');
var_dump($strJsonFileContents); // show contents
?>
error (on get.php)
string(610) "connect_errno) { printf("Failed to connect to database"); exit(); } $result = $dblink->query("SELECT * FROM updates LIMIT 3"); $dbdata = array(); while ( $row = $result->fetch_assoc()) { $dbdata[]=$row; } echo json_encode($dbdata); ?> "
Expected result is for it to echo the page (api.php) so i can pick apart the JSON, actual result is an error.
Not sure about the extent of your code, but I think this can be done simply by including api.php in get.php. There is no need to read the contents of api.php to parse the data.
get.php:
<?php
require 'api.php';
// api.php is included so $dbdata is in scope here
var_dump(json_encode($dbdata));
Related
I'm currently working on a project. It's almost done, there's only one big problem. I tested my code all the time with a xamp server on my computer, which worked perfectly fine. the goal is to run it (apache server, mysql database) on my raspberry pi. Now my project is finished, I came figured out the problem why my code doesn't work on my raspberry (at least not as I expected).
I turned on error reporting in PHP and came to this error message:
Notice: Trying to get property of non-object in /var/www/html/test.php on line 41
I use this function for all my SQL queries. Can someone provide a solution so I don't have to rewrite the whole code? Thanks in advance!
PS: this is just a piece of the code (the function where I pull the data out of the database + example of one of my queries)
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****"; // I just dont want to give my sql database password its nothing wrong ;)
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
print_r("ok connection");
function sqlquery ($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //line 41 in my code ==> do a while loop to fetch all data to an array
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
}
$stateLoop = "1";
}
else { // if there are no results
}
}
$sql1 = "SELECT stopTijd FROM gespeeldeTijd WHERE naam = 'thomas' ORDER BY ID DESC LIMIT 1"; // get data with SQL query
sqlquery($sql1,$conn,"stopTijd");
if ( $stateLoop == "1") {
print_r("ok loop");
$date1 = $myArray["0"];
print_r($date1);
$myArray = [];
$stateLoop == "0";
}
}
?>
It pretty much looks like you have some sql error in your query; check if your field names in your database match those on the raspberry.
Seeing through your code it seems like you are pretty new to programming (which is no bad thing, I was once, too). So I made a few more modifications to your code showing you the prettiness of PHP
use "return" in function sqlquery instead of globals
check for errors after executing the code
use only one variable to check if data was loaded
I commented everything I changed
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "test";
// Your function with some modifications
function sqlquery($sql, $conn, $naamtabel) {
$result = $conn->query($sql);
// Check for errors after execution
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
// If we have no data, we simply return an empty array
if($result->num_rows == 0)
return array();
// This is a variable we store the data we processed in
// We will return it at the end of our function
$myArray = null;
// Read all field data and store it $myArray
while($row = $result->fetch_assoc())
$myArray[] = $row[$naamtabel]; // if you use "$naamtabel" here, PHP first needs to interpret the string (= slower)
return $myArray;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Because we use "die" above we don't need an "else"-clause
print_r("ok connection");
$sql = "SELECT `stopTijd` FROM `gespeeldeTijd` WHERE `naam` = 'thomas' ORDER BY `ID` DESC LIMIT 1";
$data = sqlquery($sql, $conn, "stopTijd");
// $data will contain $myArray (see "return $myArray" in function sqlquery)
// Instead checking for $stateLoop being "1" we check if $data contains any values
// If so, we fetched some data
if(sizeof($data) >= 1) {
print_r("ok loop");
$date1 = $data[0]; // No "0", because we are trying to get index 0
print_r($date1);
$data = array(); // Are you sure this is nessecary?
} else {
echo 'No data returned from query!';
}
?>
Note: code tipped on my smartphone -> untested!
If you don't want to adapt the code I wrote, the important part for this question is:
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
Your error Notice: Trying to get property of non-object means "you are trying to get num_rows from $result, but $result is not an object, so it can't contain this property".
So to figure out why $result is not an object, you need to get the error from $conn->query - my code above probably won't fix your error, but it will display you one you can work with (+ it's too long for a comment)
If you have a more detailed error message and you can't solve it on your own, feel free to comment; I will update my answer!
I am trying to record which user has downloaded a file in an SQL database. Every file uploaded has its path displayed as a link on the site, allowing the user to download that file from a folder on the server. I am having trouble figuring out how to record which user has downloaded a file though. How can I query my database that a specific user has clicked a specific link? I have the user id stored as a session variable, so possessing the user id is not a problem. My code to display the downloadable files are as follows:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_website1";
$user_id = $_SESSION[ 'user_id' ];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>" . $row["file"]. "</td><td>" . $row["title"]. "</td><td>" . $row["deadline_claim"]. "</td></tr>";
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='" .$row["file"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
If you want it to be purely PHP, as suggested, just use the task_id of the row in your file table. Here is a basic example, noting I have reorganized some elements to help keep your script cleaner. Ideally you will want to keep the functions on a different page and include them when you want to use them. Keeps your script cleaner and more easily readable.:
# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
{
# Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
# Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
{
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
# I am assuming your task_id values are numeric, so I don't sanitize here
if ($id) {
if(is_numeric($id))
# Append sql
$sql .= " WHERE `task_id` = '{$id}'";
else
# You shouldn't get this exception unless someone is trying to
# Manually put something else here via injection attempt
throw new Exception("Id must be numeric!");
}
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new[] = $row;
}
}
# Send back rows
return (!empty($new))? $new : array();
}
# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
{
if(!empty($_GET['file']) && is_numeric($_GET['file']))
return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;
return false;
}
# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
# Get the tasks, could be based on id or all
$tasks = getTasks($conn, getFileId());
# Save to the database, make sure that you either bind parameters, or
# check that the values are numeric (if they are supposed to be numeric)
# Also check the count here first for the task before inserting. Make an error if not.
# Usually means user is trying to manipulate the request
$conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
# Download file. If you want to obfuscate the file, you would use
# download headers instead:
# http://php.net/manual/en/function.readfile.php
header('Location: '.$tasks[0]['file']);
# Stop execution
exit;
}
# Get all tasks
$tasks = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
# output data of each row
foreach($tasks as $row) {
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Final note, I have not tested this, so be aware of that.
your header for calling script in html
<head>
<script laqnguage="javascript" src="myfunction.js" type="text/javascript"></script>
</head>
then in your while loop in php jump out of php
?>
<form name"myform" method="get" action="<? php echo $row["file"]; ?>">
<input type="button" name="name" Value"<? php echo $row["file"]; ?>" onClick="setinsertAction();" />
</form>
then jump into php again
<?php
now create a file called myfunction.js and put this inside
function setinsertAction() {
document.myform.action = "HERE PUT YOUR PHP FILE THAT WILL DO THE QUERY";
document.myform.submit()'
}
if all goes well it should the retrieve the file for download and executed your php script if the you replace your php file for the query in the .js file if it fails let me know
my php web service is not giving me json result from my database when i run it in web browser or i try to connect to it from my android app. When i test it through postman it gives me back results i json.
Here is my php code:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
showStudent();
}
function showStudent()
{
global $connect;
$query = " Select * FROM demo; ";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("demo"=>$temp_array));
mysqli_close($connect);
}
?>
here is my result from database through postman:
whil in web browser im not getting any of this:
can anybody see any problem with this, im actually not a php developer i tried to wrote this on my own for a project.
Thanks
You are checking for the method of submission first which is POST. while when you hit direct url it work as GET. So for getting data in web change POST to GET.
<?php
if($_SERVER["REQUEST_METHOD"]=="GET"){
include 'connection.php';
showStudent();
}
I'm trying to make an iCalendar file via querying the database, so I don't have to make new iCalendar files with every event created.
<?php
header("Content-type: text/calendar");
$connection = mysqli_connect("localhost", "root", "");
$sql = "SELECT * FROM events WHERE eventID = '{$eventID}'";
$result = mysqli_query($connection, $sql);
$numrows = mysqli_num_rows($result);
// Render iCal file
?>
How to forbid file download if $_GET["eventID"] is not set?
In that case, I want instead of downloading, the visitor to get a blank page for an example.
Stick this at the top:
if (!isset($_GET["eventID"])) {
exit;
}
You should also do something after the SQL query, checking that it has actually returned a result. e.g.
if ($numrows == 0) {
exit;
}
if (!isset($_GET["eventID"])){
echo 'bad';
}else{
// your code here
}
The proper thing to do is the send a 404 Not Found HTTP status code if the URL/entity doesn't exist:
$result = mysqli_query($connection, $sql);
$event = $result->fetch_assoc();
if (!$event) {
header('HTTP/1.0 404 Not Found');
exit;
}
header("Content-type: text/calendar");
echo $event['title'];
..
Here I'm checking whether the event exists in the database. To handle a missing $_GET parameter you could send a 400 Bad Request separately.
Hello friends please help me for following question
How to pass data in JSON and how to get JSON data in php using
following code
eg:
$.getJSON("url",function(data)
{
alert(data);
});
php file:::::
<?php how to get JSON data here? ?>
The below is a sample server side code i.e. php code (you asked for php)
This includes fetching data from sql and encoding it into JSON format and returning it to client.
File content of testAJAX_getJson.php
$con =
mysql_connect("localhost","peter","abc123");
if (!$con) { die('Could not
connect: ' . mysql_error()); }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM
Persons");
while($row =
mysql_fetch_array($result)) {
$data[] = $row; }
echo json_encode($data);