r/PHPhelp • • Oct 28 '21

Solved Help with JSON_DECODE

8 Upvotes

Hello together,

I am no professional developer but try to learn more in this field.

At the moment I try to convert a JSON result to a table, sadly I am stuck on the result from JSON_DECODE.

stdClass Object ( [data] => Array ( [0] => stdClass Object ( [type] => transaction [attributes] => stdClass Object ( [amount] => 10.00 [recipient] => [time] => stdClass Object ( [date_iso8601] => 2021-10-28T14:43:57+02:00 [unix] => 1635425037 ) (...) [1] => (...)

If I understand correctly, I can get the [type] = "transaction" over "$data->data", but how do I get for example the "amount"?
This confuses me, because there are class objects in class objects and I was not able to find a solution in the internet oder forums.

Thankful for every help and suggestion!


r/PHPhelp • • Oct 09 '21

Solved Php array values are repeating

8 Upvotes

Hi Guys,

I am using postman to see the response of my php code and the first value of my array is repeating itself --- not sure why please have a look into my code:

<?php

include 'connection.php';
$con = mysqli_connect($servername,$username,$password,$database);

$allStories = "SELECT * FROM stories ORDER BY rand()";
$loadStories = mysqli_query($con,$allStories);

if($loadStories->num_rows > 0){
while($row[] = $loadStories->fetch_assoc()){
$item = $row;
$json = json_encode($item);
echo $json;
#print_r($json);
}
}
else{
echo json_encode('Content not loaded...');
mysqli_error($con);
exit();
}
mysqli_close($con);
 
?>

POSTMAN RESPONSE::

[{"sid":"1","story_title":"First Story","story_body":"<p>This is a sample story body text
	<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
		help","upload_date":"2021-10-03"}][{"sid":"1","story_title":"First Story","story_body":"<p>This is a sample
		story body text
		<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
			help","upload_date":"2021-10-03"},{"sid":"2","story_title":"Second Story","story_body":"<p>This is a second
			story body text.
			<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
				help","upload_date":"2021-10-03"}]

Please help me resolve this issue

I only have 2 sample data in mysql database


r/PHPhelp • • Sep 24 '21

Solved How do I prepare the script for a site with high attendance/use?

8 Upvotes

I am applying for my first internship/job and I got three tasks to do. One of them is writing a PHP script and using OpenWeather API to get the current weather in my hometown. Now after that it says, refresh the data with ajax every 10 seconds (I think I know how to do that) and it also says: Prepare the script for a site with big attendance/use.

I don't understand that part, what does that mean, and how do I do that? Thanks in advance.


r/PHPhelp • • Sep 22 '21

Looking for serious answers: what are some real examples of reasons people don't like PHP? I've been learning PHP for 2 years now and i cant figure out the general dislike towards it. What are some actual examples of reasons people don't like PHP?

8 Upvotes

r/PHPhelp • • Aug 09 '21

Solved Question regarding unit testing

8 Upvotes

Hi all,

So lately I've been trying to get into unit testing my code.
I think I'm ready to go and implement it, been following some pretty nice video's about it as well, however..

I'm kinda struggling to know what to test.

So the company I work for has framework that's being used to mainly power a CMS. It contains a lot of functionalities regarded to websites (create a new page, post a new blog, etc).

I can find some use cases for unit testing on specific application, but I'm kinda lost when it's for our main product..

Let's say, for example, I'd like to test our page related functionalities.
We have validation methods in place to assure that all properties are correctly filled.
I could write a test to see if the validation succeeds, but then I'd also like to create a test to see when it fails.
But, failing could be to lots of reasons!
Should I create a test for every possible reason?

Most guides and blogs related to unit testing don't do this, but I'd like to be able to have faith and trust in the test results.

I think it will also reduce bugs, but just having a test pass right now won't give me any assurance that everything is actually okay, since there are so many other possible ways to let the validation fail.

Does anyone have some experience with this, or could you share some knowledge on what to test? :)

Thanks in advance, much appreciated :)


r/PHPhelp • • Jul 08 '21

What is a subsystem in PHP?

8 Upvotes

I've been learning about OOP and design patterns in PHP, and hear this subsystem word used when describing facades, for example.

A facade provides a simple interface for a complex subsystem.

Source

It later goes on to say...

The Complex Subsystem consists of dozens of various objects. To make them all do something meaningful, you have to dive deep into the subsystem’s implementation details, such as initializing objects in the correct order and supplying them with data in the proper format.

Subsystem classes aren’t aware of the facade’s existence. They operate within the system and work with each other directly.

But I'm not really sure if I understand what a subsystem is.

Can someone ELI5, perhaps?

Thanks.


r/PHPhelp • • Jun 28 '21

Solved Do you ALWAYS have use prepare statements and bind parameters?

8 Upvotes

Apologies in advance if my lingo isn't quite correct. I'm learning.

I understand that binding variables to a query with prepare statements prevents sql injection. I'm talking about mysqli_prepare, mysqli_stmt_bind_param, and mysqli_stmt_execute. But, do you ALWAYS have to do it?

For example, I'm creating a filter for results that show a list of upcoming events. Users can (but don't have to) select checkboxes to narrow down results by category, date range, city, and hosting organization. Iv'e set this up as a form that a user then submits. There is no text-based input anywhere. It's all thought checkboxes, drop-downs, or date range pickers. Do I have to use prepare statements in this case? Would it be possible for someone to use sql injection in this case? I guess I don't know very much about sql injection and how it's done to be able to prevent it.

As a heads up, I'm using procedural php. I wish I had started with OOP, but at this point, I've rewritten so many things, I'm just going to let that be and use OOP in my next project.


r/PHPhelp • • May 18 '21

Is this php site I made unsafe?

8 Upvotes

I'm new to php and some concepts confuse me, so please be patient with me.

I finished a little php site and found a flaw. Well, I'm not sure if it is one.

I secured everything to prevent sql injections and XSS but this one thing... I don't know if that really is a problem.

I made a contact manager where all the contacts from a database are listed in a table with an edit and a delete button. pic

If I click delete, the contact gets deleted in the database. So far so good.

The way that I implemented is that when I click the delete icon, I call "index.php?id=4".

When index.php is loaded and id is set, the delete function gets called to remove the entry with the matching id. pic

But nothing prevents me from just changing the id in the adressline, hit enter and if a contact matches that id it gets deleted without actually clicking the corresponding delete icon.

Is this considered unsafe/bad?

If so, what can I do different?


r/PHPhelp • • Apr 19 '21

Solved PDO query differences

8 Upvotes

what's the difference between:

$sql = "SELECT * FROM credentials WHERE userID != $userID section = $sectionID";
$stmt = $mysqli->prepare($sql);
$stmt->execute();

this:

$sql = "SELECT * FROM credentials WHERE userID != ? section = ? ";
$stmt = $mysqli->prepare($sql);
$stmt->execute([$userID , $section]);

and this:

$sql = "SELECT * FROM credentials WHERE userID != :userid section = :section ";
$stmt = $mysqli->prepare($sql);
$stmt->execute(
    array(
      ':userid' => $userID,
      ':section' => $section,
    )
  );

is there some kind of speed or security differences?
what's the industry standard when it comes to these?


r/PHPhelp • • Mar 13 '21

Only load a class if condition is true.

8 Upvotes

Thanks for reading. I have a PHP class that represents a product in an Ecommerce system.

The class has lots of properties like price, title, description etc.

In a search module I get a list of IDs and do a for each like this:

foreach($ids as $id) { $products[] = new Product($id); }

In the Product class constructor I check if the id matches that of an actual product in the DB and I return false if it does not.

The problem is that this just returns an empty object with null properties.

So my question is, how do I return false from a constructor and prevent the loading of the class?


r/PHPhelp • • Feb 01 '21

Solved Cant understand how data is passed to an object

8 Upvotes

Hey,

So I got this code where there is an object like this:

class ProductData extends Data
{
}

The `Data` class is also empty and extends a third party lib - https://github.com/dflydev/dflydev-dot-access-data

When this class is instantiated, it's done like so:

new ProductData($productConfig);

And when I dump this object, it somehow gets data from the products config created in a self service dashboard and I have no idea how is this done.

I know this question has a lot of holes in it and might be hard to understand but I didn't know how to better explain myself. Hoping someone might know what this is all about.

#edit - I don't think I can explain myself well enough for someone to be able to help me. Changing to flait to "solved". Thanks to everyone who tried!


r/PHPhelp • • Jan 17 '21

Make sure you spell things right in you PDO DSN connection string...

8 Upvotes

Ok, just sharing, maybe for some to learn from, maybe for someone to laugh at my stupid mistake...

$aptDB = new PDO( 'mysql:dname=assessments;host=localhost', 'user', 'password' );

See the problem? A simple typo... IDE doesn't flag it, and the connection is still made.

However anything trying to use the database fails, though something like SELECT (3) works. Something is up with it picking wrong database. I tripple check the name of it...

Then I finally noticed, dname instead of dbname, so even though the connection is made it doesn't seem to care or error/report that it found an unknown parameter in the DSN.

Closing IDE, opening a beer... Good night all. :)

PS. yes normally I use a custom database class to handle connections/queries. this was just a quick down and dirty script to parse some data really fast... so much for fast with the 5 minute stupidity delay LOL


r/PHPhelp • • Dec 21 '20

How to list all dependencies explicitely required by us via composer?

8 Upvotes

Imagine a project with this composer.json

require: {
php: ">=5.6.4",
arcanedev/log-viewer: "~4.0",
arcanedev/no-captcha: "~3.0",
barryvdh/laravel-dompdf: "^0.8.0",
ckeditor/ckeditor: "4.*",
cmgmyr/messenger: "~2.0",
consoletvs/charts: "4.*",
creativeorange/gravatar: "~1.0",
davejamesmiller/laravel-breadcrumbs: "^3.0",
hieu-le/active: "~2.0",
intervention/image: "^2.3",
khill/lavacharts: "3.0.*",
laravel/framework: "5.3.*",
laravel/socialite: "^2.0",
laravelcollective/html: "5.3.*",
unisharp/laravel-ckeditor: "^4.6",
yajra/laravel-datatables-oracle: "~6.0"
},

Is it possible to list those 16 dependencies via composer itself (without loading it with via text editor)?

I tried `composer show` and `composer status`. Seems that it shows ALL the dependencies: explicitely installed by me and implicely required by the libraries. I'm only interested in the former.


r/PHPhelp • • Dec 17 '20

Solved Hey got a problem with a Undefined array key even though the code works, can s1 help me pls

8 Upvotes

my website shows me that even tough it collects all the data from the database

it fills the table with the information i need but above the table its says undefinded array key

can s1 pls help me with that problem? sorry for my english and thanks ahead

Warning: Undefined array key "ReviewDate" in D:\XAMPP1\htdocs\sample\index.php on line 228
Warning: Undefined array key "Comment" in D:\XAMPP1\htdocs\sample\index.php on line 229
Warning: Undefined array key "Title" in D:\XAMPP1\htdocs\sample\index.php on line 230 

// this is my code for the table on my index.php site
        
        require_once("methoden.php");

        $recent_reviews = latestreviews();    

<?php
            foreach($recent_reviews as $review)
            {

                $Datum = $review["ReviewDate"];
                $Kommentar = $review["Comment"];
                $Name = $review["Title"];

                unset($review);

                echo "<tr>";
                echo "<td>$Datum</td>";
                echo "<td>$Name</td>";
                echo "<td>$Kommentar</td>";
                echo "</tr>";
            }
                
?>

// this is the code for the function on method.php

function latestreviews()
{

    $db = new DataBase();
    
    $db -> connect();
    
    $sql =  "SELECT artworks.ArtWorkId, reviews.ReviewDate, reviews.Comment,     	         artworks.Title From artworks INNER JOIN reviews ON artworks.ArtworkId = reviews.ArtworkId Order By reviewDate DESC LIMIT 2";
   
    $statement = $db ->prepareStatement($sql);
    $statement -> execute(); 
    

    $reviews[] = array();

    while($review = $statement->fetch() )
    {
        $Datum = $review["ReviewDate"];
        $Kommentar = $review["Comment"];
        $Name = $review["Title"];

        $reviews[] = array ("ReviewDate" => $Datum, "Comment" => $Kommentar, 
                               "Title" => $Name);
    }

    $db->close();
    
    return $reviews;
}

r/PHPhelp • • Oct 30 '20

Do you plan or draw out a structure of your app before you start?

8 Upvotes

If so what methods are possible for doing this? I'm creating a user signup, signin, team join, team create flow but I want to draw out my actions, repositories, classes, methods before I start coding, are there known methods of doing this? How do you go about this?


r/PHPhelp • • Sep 25 '20

Can you suggest alternatives to the learning site Udemy.com?

8 Upvotes

I am looking to take some online classes and learn more PHP and start learning Laravel. I used to like Udemy.com because they are really inexpensive. Can you think of other options that are also inexpensive?


r/PHPhelp • • Sep 10 '20

Anyone with experience converting a webpage to PDF? Looking at TCPDF, jsPDF, html2canvas, pdfMake, etc but no luck. Could use some help here. Thx!

8 Upvotes

Long story short I've got a page a client is wanting in PDF form. It's a calendar view with lots of specific customization on it and I only need the view without any of the buttons, etc. on the page (running PHP back end).

Ideally, I could use one of these JS plugins to just export a section of the page and be done. Creating a new backend script to parse out what I need from the original view will just create more maintenance I'm afraid. I guess I could also use AJAX to grab my tables and send to a PHP script for something like TCPDF to generate it.

I posted over to stackoverflow for help but no answer yet, pdfmake is jacking up the view and way too zommed in. Also appears pretty fuzzy. Basically grabbing the specific tables I need then sending to htmlcanvas/pdfMake but not rendering well. jsPDF also have me extremely fuzzy and odd aspect ratio issues.

Anyone have guidance on this, can't decide the best route. Really want to avoid reinventing the script generating the page just for pdf output.


r/PHPhelp • • Aug 18 '20

Good PHP starting points for a Team?

8 Upvotes

I have a team that is to switch from Python/Django to a PHP based CMS. Since there is zero PHP knowledge in the team at the moment I wonder about how to built up some knowledge.

Can you give me some hints? Are there some learning resources that are generally seen as good starting points? Are there blogs/forums/communities/movements one should be aware about?


r/PHPhelp • • Aug 14 '20

Getting data from PHPMyAdmin (beginner question)

8 Upvotes

I've not touched PHP in 15 years or so (and the last time I was a beginner at best) so I'm a bit rusty.

My problem is I have a database (called table1) with a table in that has two data rows and when I try to select the info from the db to a PHP-page it successfully establishes the collection but doesn't seem to pull any data from the db.

I've got some server space through one.com where I have a database.

My issue is that I don't understand why it doesn't process my SQL. I've uploaded the super basic page (as a .txt) where I try this in hope that someone can identify where I go wrong. Username, password etc are changed (connection is successful so the issue doesn't seem to be there).

https://1drv.ms/t/s!AhzkfwJlWNPrhbIKlzv6JoRrXoGQ0w

I've got my page one a server hosted by one.com using PHP 7.4 and PHPMyAdmin if that information is important.


r/PHPhelp • • Aug 08 '20

What is the best way to generate pdf from dynamic HTML?

8 Upvotes

We're on a shared hosting that supports PHP only, We're using wordpress. We want to let users fill a form and then give them the option to download their results as a pdf. The pdf should be available in English and Arabic and it should have a header containing a logo and a URL. I'm trying to capture the results <div> section from the browser then download what's inside it.

  1. I tried html2pdfJS, the pdf wasn't rendering when I tried adding a header

  2. I tried JsPDF, I wasn't able to make page break work, it splits the page in half vertically.

  3. I tried using Dompdf, turns out, it only accepts HTML, my results page contains PHP, so I have to capture the page somehow then send it back. Don't know how to do that, seems too much of a hassle.

Is there a better approach to do that task?


r/PHPhelp • • Jun 29 '20

Question: How does Reddit create a new page for every post created?

8 Upvotes

Sorry if this is a stupid question, but I was wondering each Reddit post created is its separate page. Like how after writing a post, when another user clicks on the post, the user is directed to another page.

Thank you!

Edit: Is there a specific process for this? And if so, what is it called?


r/PHPhelp • • May 04 '20

What is this syntax? Creating a function with what looks like a ternary operator....

8 Upvotes

This is the code the developer sent in:

function extract_task_data(array $row) : array {
    $assignee =  explode(", ", $row['assignee']);
    // more lines of code
}

It is the first line, the creation of the function. What syntax allows a colon and the raw token "array" before the braces? What is it doing?


r/PHPhelp • • Apr 27 '20

Looking to hire PHP help - convert php mail () to send with SMTP?

8 Upvotes

Would like to hire someone to convert a php mail () contact form to send out using SMTP over TLS instead. It's an odler form built into an application we've deployed so we need to update existing form rather than replace it fullys new forms don't load in the old version of the browser.


r/PHPhelp • • Apr 25 '20

Where/how to learn more about PHP in detail?

8 Upvotes

I've been doing PHP for sometime now (1 year professionally) but I just seem to know the language and how to get work done. I want to learn more about the language itself. Not really the C implementation or the source code but more like how the PHP files I write are interpreted, what component takes care of that, principles, etc. More like the architectural details.

As an added info, I'm doing Laravel at work.