-
Posts
6,060 -
Joined
-
Last visited
-
Days Won
153
Everything posted by gizmola
-
Moving some PHP to the backend without a button press or anything
gizmola replied to JoshEir's topic in PHP Coding Help
I think the point you are making, is that there is no holistic cross language debugging tool, but then again that is the nature of web development. There are a lot of different languages and ways you can connect things, which require different debugging tools. In recent years most of my projects have been done with either Symfony or Laravel, and they both offer a debugging toolbar that tries to bridge the gap somewhat, but at the end of the day, I find there are a number of different tools and techniques you need for debugging. The same is probably true of any networked system, where there are a variety of services that are connected in a non-trivial way. From a front end standpoint, the more complicated the javascript, the more you need to use the developer tools. More often than not, I'm looking at the network tab and looking at the request/response data. I'm typically only using the javascript debugger when I have something specific that I know is broken in a particular way. If I'm not sure exactly where thing are going wrong, then I'll step through the code by placing a breakpoint at an early/well known point. At the end of the day, once code is running in the browser, it is no longer something you can debug from the serverside. -
Had no choice but to begin learning, so Hello!
gizmola replied to dannypritchett01's topic in Introductions
PHP is a very different language from the one you learned many years ago. Any code you might have written is entirely obsolete, and probably you are running a PHP version that long ago was end of life. Candidly, PHP wasn't looking pretty viable, but in the last decade it has been steadily improved to once again be one of the best languages for web development. It has an excellent dependency manager: Composer. This enabled the creation of a truly impressive array of component libraries, many of which have great code coverage and unit tests, insuring quality and stability. It has two state of the art Dependency Injection frameworks: Symfony and Laravel, and there are others that are capable. There are several ORM's for relational database development supporting both the Data Mapper pattern or Active Record. The language has been enhanced to support many of the constructs and type of coding available in other languages, and performance has been improved in a variety of ways, so that large commercial websites are comfortable using it. It's once again a great time to be a PHP developer, but it's also a time to update your application and your knowledge. I would highly recommend learning either Symfony 5.2 or Laravel, by porting your application to them. In the process you will update your skills and at the same time, have a website that is clean, secure, maintainable and with your code concentrated on functionality rather than the basic MVC code most websites utilize. -
Moving some PHP to the backend without a button press or anything
gizmola replied to JoshEir's topic in PHP Coding Help
Javascript debugging is done in the browser using the built-in developer tools. People typically use chrome. The exception would be if you have a node application or javascript front end application built on vue or react etc. but in that case you are going to have the front end code separate from the back end code, and be implementing a REST api or something similar on your backend, which is basically what you would want to do for any ajax calls. If you have lots of mixed PHP/HTML scripts you can still debug those with the PHP debugger, but it's really not a great way to develop clean maintainable code. Most pro developers use PHPStorm. It's not free obviously, but it's the premier solution. It has so many options it can actually be pretty daunting, but it also provides the best navigation through a complicated code base of any IDE. As for free options, I have also used phpeclipse, which is built on top of eclipse. It's not terrible, as Zend for a time had a commercial product based on it, but Zend no longer exists as a company. Lately I'm using Visual Studio Code, but I haven't made a lot of efforts to get it setup for PHP. It's really where a lot of the web development community has migrated, and the support and velocity of enhancements is very high. -
It looks to me like you have some sort of sync issue with your environment, because there is no reference to a key of 'title' in the script you posted. There could be all sorts of reasons depending on how you are testing or revising your code. This could also be because you have a cached version of your code. Did you try to restart your apache/php? If that doesn't fix the issue, I'm not sure what to tell you, as the code you provided does not include 'title', but does include 'titel' in a number of places. If you changed the spelling of 'title' to 'titel' recently that would also suggest a caching issue. If you are interested in where this type of caching might exist in a development environment, reference OPCache. OPCache is a performance enhancement that caches source code in memory to vastly improve runtime production. It might be installed in your xampp. In a development scenario, it is probably advisable to disable it just to remove the possibility it might interfere with your development cycle. Again this is just an educated guess based on what you provided.
-
You also have to realize that there are no longer any versions of PHP that will work with unaltered 10 year old code. You most likely will need to update your system to work with a current supported version of PHP.
-
There isn't really a "php database". PHP can talk to many different types of databases through client libraries. So... I can not guarantee this is going to work, but it's worth looking into. The primary goal here is to keep you within PHP which you know, which should make writing the code you need within your comfort zone. You need an MQTT Broker that your ESP32 device will be publishing to. This needs to be some sort of network connected device that can run your MQTT broker, as well as your SQL database + storage for your data. You will also be running an MQTT client job that will be subscribed to the broker and will take data and add it to the SQL database in (near) realtime Here is an async server package called Swole that is added to PHP via an extension. You would need to use PECL to add it to your PHP installation which will live on the aforementioned server With Swole you run a php based MQTT broker/server. Here's simple code that shows how you would do it: https://www.swoole.co.uk/docs/modules/swoole-mqtt-server You write a client who subscribes to your MQTT Topic for the data you are charting, and transforms that data. Again there is a php library for this, and there may be others if you do some googling, packagist searches etc: https://github.com/php-mqtt/client Your client will receive the data and add it to your SQL database each time a relevant message is received with data you want to store Now theoretically, you can cut out this client piece by adding code to your Swole based MQTT broker. As messages are published to the topic, you should be able to process the data and add it directly to the the sql database, so like anything there are multiple different ways to do this with strengths and weaknesses for each. If the server code can do it directly, clearly that's simpler and better.
-
Another way of doing this that uses some array functions would be: $countries = array_intersect_key($countries, array_fill_keys(array('US','CA'),0));
-
Highly unlikely. Performance tuning isn't something that is typically fixed with a couple lines of code, and typically requires various forms of expert level profiling and sysadmin/devops skills.
-
Yes, well we would need to actually see your code if you want help.
-
Good luck with your studies.
-
I missed the subtlety in your question. Barand has a good solution.
-
Here is a simple example, turning the date strings into DateTimes and then using format to output the date. You will need to read the manual page Strider64 provided to reference all the different ways you can specify output. There are also a number of predefined constants you can use. <?php $dates = array('2005-05-21', '2006-11-01', '2006-11-02', '2020-09-28', '2020-09-29', '2020-09-30', '2020-10-01'); foreach ($dates as $date) { $dt = DateTime::createFromFormat('Y-m-d', $date); echo $dt->format('r'); echo PHP_EOL; echo $dt->format('\i\t \i\s \t\h\e jS \d\a\y.'); echo PHP_EOL; echo $dt->format(DateTimeInterface::ATOM); echo PHP_EOL; echo PHP_EOL; } Your dates all need to be valid, or you may get some odd results. It is possible to check as to whether or not a date was invalid, which is documented on the manual page for Datetime::createFromFormat(), if that is a possibility you need to handle.
-
Can't Detect isset() for text box (only 1 box)
gizmola replied to jahicki's topic in PHP Coding Help
So you have 2 items you can work on. The first was brought up by benanamen, which is really a syntax issue. You are not referencing arrays correctly: // Use this if (isset($_POST['itemName']) { // Not this if (isset($_POST{'itemName'}) { That is not the source of your current problem however. Your current problem is that whatever javascript you have that you assume is making your form valid, is not valid, so your text field is not being passed when the form is posted. Another good debugging tool is to use something like chrome dev tools, and look at the network tab when you submit the form. You can then see the contents of the post variables as they are sent when you submit the form. In conclusion, right now your problem is your html/javascript code and has nothing to do with PHP. The code is working as you intended, as $_POST['itemName'] is not set/does not exist. -
Can't Detect isset() for text box (only 1 box)
gizmola replied to jahicki's topic in PHP Coding Help
Add a debugging statement at the top of your script of var_dump($_POST) and verify your assumptions. -
I will try and come back and take a look at your code, but I wanted to say that using PDO is great. I would say that the staff is universally in favor of using PDO, so no worries about learning mysqli.
-
Transactions are another one. I don't really disagree with what you wrote, and in fact I linked to information that agrees with you. The problem with anything concrete is that we don't know if jodunno is using PDO or MySqli.
-
Actually, I think that Barand just made a small mistake, which is certainly very unusual for him The unique constraint should be: UNIQUE KEY `unq_page_link` (`user_id`, `page_link`), That will enforce uniqueness on a user/link basis, which is what I assume you are going for. This is a better solution in that you are using the db to enforce your integrity rule rather than relying on the front end code to do it for you. With that said, code around database queries needs to be written in a way that you catch and deal with database errors appropriately. Typically that is done with a try..catch block. I can't give you specifics without knowing in advance what db api you are using (mysqli vs pdo) . Here's an example out of the "(The only proper) PDO tutorial" which is highly recommended reading for anyone learning the PDO api: try { $pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data); } catch (PDOException $e) { $existingkey = "Integrity constraint violation: 1062 Duplicate entry"; if (strpos($e->getMessage(), $existingkey) !== FALSE) { // Take some action if there is a key constraint violation, i.e. duplicate name } else { throw $e; } } Assuming you are using PDO this could be adjusted to fit your problem as it is essentially the same issue you would face in dealing with the unique constraint violation to prevent a user from adding the same link multiple times. If you are using mysqli, then you should certainly read this. A general discussion of php error handling strategies is good to read. The important thing to note about this, is that you don't want to generalize error handling to try .. catch blocks around all your queries. This is a specific issue, having to do with something you expect to happen frequently. Lots of other database exceptions can happen, and you want to have a generalized exception handling solution for those.
-
The html generated along with the css you used, would allow people to help you diagnose what is or isn't working. Also, you would still need tables, or alternatively convert to flexbox or css grid
-
Please provide an example of the array you are expecting to generate.
-
Let's look at your method: public function countVehicles (){ $this->db->query("SELECT COUNT(id) FROM vehicles WHERE id = :id"); // Where is the :id parameter? You do not pass it into the method nor do you pass it to the query $counter = $this->db->rowCount(); // This, should it work, will always return 1. Not what you want! return $counter; } You do not want to do a rowcount on that query, because it will always be 1. Select count(id) is going to always return one row. Even if there is 1 row counted or a million, or zero. The reason the query was suggested is that it will always have a value. With that said, you would need to fetch the row to access the value, not count the number of rows in the result set. Personally, in order to have a simple column name to use, I will alias the result of a count() query like the one suggested. Here is how I would do it: "SELECT COUNT(*) as count_of FROM vehicles" Then if you have fetched this result into a variable in some way, you can expect to access the value via something like $row['count_of']. With that said, your query by id, assuming that id is the primary key of the vehicles table, will always count at most one row, because the primary key must be unique. There are compound keys that could complicate this, but I don't see anything you are doing that suggests you have a table with a compound key. Are you just trying to get this to work, so that you can do what you *really* want to do? I'm going to assume you actually want the count of all vehicles as you did initially. If things were working as they should, your original code should have worked. Something is not working in your database model/class. Unfortunately, I can render no further aid, because I would need to know more about what "MVC" you are using. MVC is a design pattern, not an implementation, and has been implemented in various ways by nearly every popular PHP framework, with a few exceptions. What framework are you using, or is this something you have built yourself from scratch? What is the source of the database class?
-
One other option available to you would be to use HTML 5 local storage. This allows you to have the client save its data locally. Since you would be well served to update your html from 4.01 to 5 anyways, it would be a great time to experiment with LocalStorage. The javascript API is incredibly simple: localStorage.setItem('myCat', 'Tom'); const cat = localStorage.getItem('myCat'); localStorage.removeItem('myCat'); localStorage.clear(); //Clear all items Ajax is the answer. When you have a cascading group of interconnected dropdowns, you want to convert your code to make ajax calls. On the serverside it's pretty easy -- you just concentrate on the data. So let's take zipcode to city/state as an example. User is prompted for a zipcode, and you then lookup the city/state for that zipcode in your database and return those. The client parses the city/state and updates those values in the user's form. Lots of things have changed in the javascript world since you first implemented your app. You want to move to the modern way of doing ajax calls, which is to use Fetch with promises. The two go hand in hand, in that fetch was designed to use promises. About this, I will just say that the hard part of ajax is what happens when there are errors. People often concentrate on the "happy path" where everything works, and ignore the issues with the asynchronous web. Fetch and promises help you write a more robust app with simpler code. Here's a nice tutorial link, although there are many available if you need more help learning them. For example, if video tutorials work for you, you can find many on youtube by searching for "javascript fetch". One important fundamental is to return all your data from your php scripts in json format. That makes it easier to integrate the results into your clientside code.
-
There's a few different ideas in play. In the olden days, if you wanted to maintain a channel of communication between a (web) client and your server you could use polling. This was essentially some javascript running in the client on a timer that would make a request to your server every so often. The problem with this is that as the number of users goes up, so does the number of requests purely to poll the server for new messages. The next evolutionary step was Long Polling. The idea with Long Polling was, that the client would open an ajax connection to the server (with HTTP these are TCP socket connections) and hold it open listening for a response. The server only responds with data if there is a notification. At that point the client closes the connection and immediately opens a new one. This was a good work around for systems where notifications are desired but are relatively infrequent. With PHP it also has some significant overhead in traditional Apache/Mod_php environments, as a child process will be forked/allocated to each running PHP script. This can tie up a lot of children with large allocations of memory, simply waiting on open ajax connections. The next innovation was Websockets. The idea of websockets was to create a specification that does not work within HTTP, but instead is intentionally designed for standalone persistent client/server communication. This has become a well adopted technology at this point, as libraries and servers exist in javascript and all serverside languages. The big advantage of websockets was that it was client agnostic in that you could build a serverside solution that will work for any type of client you might have. So if your serverside app is basically a REST api used by mobile clients, you will probably choose websockets. There are also numerous PaaS vendors out there like Pusher, who offload the serverside overhead of Websocket communication and operate as proxies for websocket communications. Your client code can talk to Pusher who manages the socket connection to the clients, and you then write a serverside script that connects to Pusher and handles messages and sends responses to clients as needed. Even if you run your own Websocket server, you will implement a similar architecture. The latest innovation is the Web Push Protocol built right into various web browsers. This was meant to address the lack of OS level notifications that exist in the mobile OS's which mobile app's can use to subscribe a user to serverside information. Websites have long desired a way to re-engage or update users without their having to visit the site again. Email has been the traditional method for that, but now browsers are allowing subscription opt-ins for a website, which you can use to send notifications to users. Of course the main issue is that these notifications are specific to a browser AND the user must have the browser open to receive them. With that said, sites have rushed to implement the technology, and as in the case of Websockets, scores of PaaS vendors have emerged to act as middlemen in implementing proxies. There is an awful lot of setup and configuration involved with Web Push implementation. A great way to understand and perhaps implement your own web push notifications would be to use a component library like web-push-php which has documentation and references you can use to learn what you will need.
- 6 replies
-
- notifications
- php
-
(and 1 more)
Tagged with:
-
You don't need the value of oak to increment it within the database. "UPDATE users SET oak = oak + 1" With MySQL you do need to be careful with this type of update, if the original value of the oak column is NULL. See this article on the problem. Make sure that an uninitialized row is 0. The obvious problem that jumps out is that this query will update ALL rows in the users table. I think this is probably one of the things Barand noticed. One would expect that you would be updating the row for a particular user. If this is just for development purposes right now, then one would expect something like: "UPDATE users SET oak = oak + 1 WHERE id = 1" This assumes the users table has a primary key column named id, perhaps with auto_increment, and as a user logs into the system this page would use a session variable to set the specific user row to update.
-
Laravel Error : Trying to get property 'data' of non-object
gizmola replied to a topic in Frameworks
You already have what? php artisan serve starts up the development server on a port. You are accessing the port. When you say it "doesn't work" you would need to be a lot more specific about what you already have installed and configured.