Migrating from xamp to raspberry pi apache server - php

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!

Related

Get JSON data from a different page PHP

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

Using include/require to connect database [duplicate]

This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 6 years ago.
I have a following code
//dsn.php
//Object Oriented way
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
//check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("could not connect:".$conn->connect_error);
}
//index.php
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
$sql = "sql command";
$result = $conn->query($sql);
//not working
$conn->close();
}
This will display warning and notice that says:
Warning: mysqli::query(): Couldn't fetch mysqli
Notice: Trying to get property of non-object
Warning: mysqli::close(): Couldn't fetch mysqli
However this one works:
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
include $dsn.php
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
How do I use just one include file for DSN and use repeatedly on other functions?
EDIT
sorry I forgot to mention
function a($conn) {}
function b($conn) {}
I passed the variable $conn but it still displays the warning and notice I mentioned above
When you include a file, you can imagine that in the background it is just copy-pasting that code into the current document.
There are 2 problems with your code...
The $conn variable is not in scope inside function a or b.
Even if it was in scope and accessible, you are closing the connection after each query. A better way to do it is to open the connection, run all queries and close the connection when it is no longer needed.
The second piece of code you gave works because it is creating a new variable $conn inside of b(), but this is not ideal as it will create a new database connection every time you execute that function.
Something like this may suit your needs:
include 'dsn.php';
function a($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
function b($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
$aResult = a($conn);
$bResult = b($conn);
$conn->close();
Notice that we are only including 'dsn.php' once, and then passing around that existing connection to the functions that need it.
This is very simple. On page load, the connection file is included which makes $conn the connection object available to the remaining codes. The $conn is used by the functiona() and it is then closed at the end of the function. $conn->close(); destroys the database connection object means, $conn is no more object hence it should not be treated as object. But the Function b() is treatong it as database connection object and resulting into error.
But if you again include the connection file, inside the function b() then $conn becomes available to the function as local object. And works as it should.
Do not close the $conn() on the any function till you are dealing with DB.
function a() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function incDbConnectionFile() {
include 'dsn.php';
}

PHP mysqli insert return error invalid request

I've been having a bit of trouble with my PHP code.
I'm trying to insert a new row in table gebruikers.
I'm using a JSON API to post the data from my C# Android app to the server.
running the code returns an invalid request error.
PHP:
function registerUser($api_data)
{
// connection
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$database = "test";
$mysqli = new mysqli($servername, $username, $password, $database);
//check connection
if(mysqli_connect_errno())
{
API_Response(true, 'connection error');
}
$register_data = json_decode($api_data);
$leerlingnummer = intval($register_data->leerlingnummer); //passed as string, int in database
$wachtwoord = $register_data->wachtwoord; //string
$email = $register_data->email; //string
$result = $mysqli->query("INSERT INTO `gebruikers` (`Leerlingnummer`, `Wachtwoord`, `Email`) VALUES ({$leerlingnummer}, {$wachtwoord}, {$email})");
if ($result == false)
{
API_Response(true, "{$mysqli->error}");
}
else
{
API_Response(false, 'SUCCESS');
}
$mysqli->close();
}
database is looking as follows:
database layout
I've never felt this stupid before, but the error came from the fact that I was still referencing to an older .php file. I was so focussed on the PHP script that I didn't notice this error in my app before.
the quotes advised by Sean and fuso were needed later on though so thanks for that.
Problem solved, sorry for wasting some of your time :/
You should quote your data in the insert query.
... VALUES ('{$email}','{$other}')

Trying to insert data into a database using PHP / Mysqli

I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method

php mongo Uncaught exception 'MongoDuplicateKeyException' E11000

I am trying to migrate data from mysql to mongo. It adds one record fine to mongo but then on the second record I am getting
Fatal error: Uncaught exception 'MongoDuplicateKeyException' with message 'localhost:27017: E11000 duplicate key error index: app.hospitals.$_id_ dup key: { : ObjectId('558365d7423467484bd63af3') }'
Not sure what I am doing wrong
here is my code
<?php
//echo phpinfo();
$host = "localhost";
$user = "root";
$password = "root";
$database = "database";
// Create connection
$conn = new mysqli($host, $user, $password, $database);
$connection = new MongoClient();
$db = $connection->database;
$collection = $db->hospitals;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM hospitals";
if($result = $conn->query($sql)){
$i=0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$value){
$collection->insert($row);
unset($collection->_id);
}
if($i > 3) die;
$i++;
}
}
$conn->close();
?>
using
$collection->save($row);
instead of insert solved the issue. Not sure why though.
Had the same problem, I believe it's a problem with the PHP mongodb driver that it is not generating a new id inside the loop.
The weird part that the first time I called the script it inserted all the documents then the exception popped in the end, then when I dropped the database and called the script again, it only inserted one document before giving the exception.
Anyway I solved after reading this answer by explicitly assigning new id.
In your case, add this before the insert:
$row['_id'] = new MongoId();

Categories