-
Posts
5,954 -
Joined
-
Last visited
-
Days Won
145
Everything posted by gizmola
-
It seems to me that mac_gyver has identified the key problem you have, which is that it appears you exhaust all the available players qualified for role 7 before arriving at role 7. This is equivalent to saying you have an open position for "chief surgeon" and only 4 candidates available, and you find that all 4 candidates already took other positions. What can you do if you have no qualified applicants? There is nothing to do -- the job sits open until you have more qualified applicants. If you want to insure that you place someone, you could, if a group has no person in the role, continue on to check the next group, and to keep doing that until either you filled the role Or you again have gotten to the end of the users_roles array. This will fill the role with the top available applicant in the following group(s) if possible.
-
^^^^^^^^^^^^^^^^^^^^^^^^^ What he said!! Regex for html parsing and extraction is the wrong tool for the job
-
What exactly are you having troubles with? Database design? Data structures? Coding? Some specific examples would help.
-
The important takeaway here is that you shot yourself in the foot with not knowing basic PHP syntax. Since you are using PDO, the manual is pretty clear I think that you are passing public PDOStatement::bindValue(string|int $param, mixed $value, int $type = PDO::PARAM_STR): bool @Phi11W did a great job explaining that '[]' is acceptable array syntax, which is why it let you get away with it, but the thing you also missed is that the 3rd parameter needs to match the TYPE of the actual data you are passing. In your case, you were passing the SQLITE3_TEXT constant, indicating that the parameter you are trying to bind is a string. Right there, that should be the indicator to you to think that -- is this thing I'm passing as a value a string? At the point you removed the array brackets, you were just passing a string variable, and this explains your success. With that said, and also just reiterating Phi11W's earlier point, the id shouldn't be a string. Its only purpose is to guarantee uniqueness. I don't know if this a tutorial you are following, but the way keys are generated via SQL Data Definition Language (DDL) varies by database engine. SQLite has a feature where it will automagically generate a key for you, known as the ROWID. If you declare the first column to be an integer, it essentially creates a mapping where you can use this name as an alias for the rowid. Example: CREATE TABLE test(id INTEGER PRIMARY KEY ASC, foo, bar); At this point, for the test table, id would be an alias for the internal SQLite rowid. When you insert, you can either omit id entirely, or pass NULL/'' as a value. This will cause SQLite to generate the unique rowid for you. You then immediately follow up the insert with a call to: $newId = $db->lastInsertId(); This assumes that you actually need the id at that point in order to create some related row linked by this id (ie. you are going to use it as a foreign key, or to look up the row you just added).
-
Yes there is a way to do this, but it involves a solid foundational understanding of relational database design concepts and how to write code. It would be a significant amount of work for a professional programmer. An alternative to reinventing the wheel from scratch would be to use a php based CMS like Drupal or Bolt These projects start you out with a lot of functionality and systems that already have templating, much of which can be tweaked without programming. They also have "taxonomies" which are extensible. You can utilize existing templates to learn how templating works, and how to customize them without already being an advanced developer. Not to sound pessimistic here, but creating a blog database is not difficult at all, for something simple, but you still need to know what you are doing. With that said, even though it might be fairly simple to do so, providing you a custom CMS database structure and instructions on how to create different templates against it is the topic of many an article, book and online course. If you have a better idea of what approach you might take, people can provide you better advice.
-
Reading and copying from the book the joy of php
gizmola replied to Markus1954's topic in PHP Coding Help
It could not have been made any clearer than it was in my reply to you. Take time to carefully read and study the replies, especially when people spend the time to give you code snippets and corrections. -
Welcome to the community. Looks like you have already learned a lot of compsci and programming at a very young age. PHP has 2 great frameworks: Laravel & Symfony. If you haven't already, you might enjoy creating some projects in one or the other or both.
-
Reading and copying from the book the joy of php
gizmola replied to Markus1954's topic in PHP Coding Help
Please use the code tag button in the future. I edited your post to add it for for your code snippet. It's the <> button. The condition in PHP must be inside parens. This is what ginerjm was telling you. Yours: if($mysqli->query("CREATE DATABASE Cars")=== TRUE{ echo ("<p>DATABASE Cars created</p>"); The logical operator '===' has the 2 things you are comparing. These must be enclosed in parens. if (logical evaluation) { //true code } ...etc. Should be: if ($mysqli->query("CREATE DATABASE Cars") === TRUE) { echo ("<p>DATABASE Cars created</p>"); Putting a space before/after logical evaluation constructs like if while etc., will help you see these types of mistakes easier. PHP removes the whitespace, so anything you do to make your code more readable is fine. -
To really help you I think we need a better understanding of the basics of your problem. Do I understand this correctly that you have a table of persons. I could argue that this application would benefit from some form of the party model, but for simplicity, as Barand did, let's assume there is a table of persons, and a table of helpers. What does the "persons" table look like? Is there a row for each person who will receive help along with a birthday or age? Conversely, the helpers are individuals and not organizations or some mix of both? Their commitments are to "help" a particular number of "persons" and this help for some reason has to be typed by gender AND age? Is there no option for an organization to help either/or? So as a "helper" I have to go through this convoluted UI and indicate: I will help "3 females of the age of 2", "1 male the age of 7" etc? What is the nature of "help". Is this providing items/clothing/toys? Why is the age important. Do age ranges come into play, and if so how, or why not?
-
As for whether you should set POST variables to null vs '', an argument could be made that they have similar strengths and weaknesses. I would suggest always setting empty form variables initially to '' rather than null for 2 reasons. From the browser point of view everything coming from a POST method is in string format. It is up to you to synchronize your form code with the datatypes you received. That's a different topic, but suffice it to say that loose typing and ease of conversion between types is one of the features of working with PHP, so long as you are consistent. This issue exists when using null and comparing to a variable that doesn't even exist. <?php $foo = ''; $bar = null; echo $foo === $baz ? "=" : "!="; echo PHP_EOL; echo $bar === $baz ? "=" : "!="; //output // != // = In PHP 8, they changed things, so this now produces a warning, but in prior versions, trying to use a variable that was never declared just produces a notice. This is where it gets muddy with PHP, in that a variable set = null is equivalent to a variable that doesn't even exist. In general null exists to support the concept of "no value". There is no intrinsic value to setting a variable you intend to use as a number = null vs. '' other than that with '' it's internally typed initially as a string. Perhaps a more important comment to you is that, having lots of variables floating around isn't great. Typically it is better if you have some sort of object or at least an array that supports your form handling. It's also pretty far from DRY when you are writing the same statement 10x because you are processing a form with 10 elements. I would start down this path, using an array, with a name like $postData or $formData. Look at the benefit of something like this: function getPostData($fields) { $postData = []; foreach ($fields as $field) { $postData[$field] = $_POST[$field] ?? ''; } return $postData; } $fields = ['name', 'description', 'email_address']; $postData = getPostData($fields); It's a lot easier to build upon or expand this concept, then to write code with a bunch of independently named variables. Using an array will provide you many benefits. Classes can do even more for you, and if you look at frameworks you will find they always wrap the underlying HTTP request/response mechanics for you using classes.
-
You can use the empty function now to kill 2 birds with one stone. if (!empty($_POST['var1']) { // Make some use of $_POST['var1'] } There is also the "null coalescing" syntax (php >= 7) you can use for assignments like this: $user = $_POST['user'] ?? 'Guest'; // This is equivalent to $user = isset($_POST['user']) ? $_POST['user'] : 'Guest';
-
To be absolutely clear: The Apache HTTP server that is commonly used in the AMP,LAMP, MAMP,WAMP stack, is not java based, does not integrate or use any java components, and is not at risk. This is a common enough misconception, in regards to Apache vs the Apache Software Foundation. The Apache webserver is one of the oldest Free Open Source web servers. For the record it is written in c. The original core contributors to the Apache HTTPD server, went on to create the Apache Software Foundation(ASF), which was incorporated as a non-profit to support the continued development of FOSS software. The ASF also authored their own License, that is comparable and competes with the GPL and MIT licenses often used for FOSS. Over the years, the ASF has sponsored and brought many different types of software under their umbrella. These projects benefit from funding and support services provided to them by the ASF. At present there are something like 180+ individual software projects under the ASF umbrella. Here is a list by programming language. Apache is a big player in the Java development space, with many important tools and java based projects under their umbrella. Log4j is just one of these projects, but it is often integrated into other java based software and systems via their java logging project. Here's one quote to help understand the potential scope of the problem: Anyone running an Enterprise or Java based system is a potential target, but there are also many pieces of java based software that are used by companies for the services they provide. For example, note the mention above of "Solr" which is a popular full text indexing engine that many sites who aren't otherwise java based, may use. Apache also provides the Lucene engine, which is also Java based. Basically if you are running any sort of java based software server, there is a good chance that the log4j vulnerability is a concern. For any company with sysadmin/devops/developers with a degree of competency, the log4j exploit vector can be quickly and easily closed using several techniques that vary by log4j version and environment. The problem is that there are many packages of java based software like Lucene & Solr, that the users may not realize are java based. They may come with a packaged JRE, or be running via an independently installed JVM. The actual exploit requires crafted input that gets logged containing instructions which trigger java JNDI to download and run remote code. So it's a "remote code exploit". If a server with a vulnerable installation or version of log4j doesn't have some sort of publically available listener, there isn't a vector for exploitation. For example, depending on the integration, your Solr or Lucene engine might not be at risk. It could depend on how or what you are indexing, and where the data being indexed comes from. Many people are running java based editors like Eclipse or Netbeans, or any of the Jetbrains editors, in particular the very popular PHPStorm. What does Jetbrains have to say about this? https://blog.jetbrains.com/blog/2021/12/13/log4j-vulnerability-and-jetbrains-products-and-services/ I hope this helps clarify some things for people.
-
I am not a fan of these setups, as they install a bunch of software and server processes on your workstation. They were a nice solution back in the day, but now you can use virtualization with virtualbox/vagrant or use docker. With a machine with the resources you listed, that is plenty of horsepower to run lamp in containers. Some advantages to doing this: You don't have installations of the AMP stack running under windows You don't have to deal with upgrades/maintenance of them Nobody runs the AMP stack in production on anything other than Linux these days, so you are developing closer to/or exactly on the target OS you will deploy to You can easily run containers that let you simulate more complicated environments (for example, multiple PHP servers behind a load balancer) that would be very difficult to set up under AMP without hacking the hell out of the setup, which defeats the purpose. You can easily run different versions of the stack under vagrant/PHP. If I want to test the lastest version of PHP against some code, that is trivial with Docker. There is a learning curve to everything, but I would advise anyone to invest in learning how to use Docker, as it's the tool that most teams are using to develop and often to deploy.
-
In the future, please use the <> button to insert code. I fixed it for you this time. You stated your timer was every 10 seconds, but your example shows it's 5 You should note that if you test it with something longer like 30000, after the initial render, the links don't work, so it's not a timing issue I don't know how many rows you are sending but it seems pretty inefficient to blow out the entire list every 5 seconds. The main issue I see is that you are only setting the click handler when the page loads. Once you reload the page, the reloaded li's won't have click handlers attached. So the simplest fix is to move the code that sets the click handlers inside the setInterval code. With that said, the update might perform faster if you just write your click handler function, and then have your button markup include the onclick="clickHandlerFunction()". This way the DOM doesn't have to process adding the click handler for every refresh.
-
With no code to look at, there is nothing anyone can do to help you. A page where you are updating the contents every 10 seconds, and in the process blocking any interactivity, doesn't seem like a very good design to me. At very least, you should be checking to see if an update is even needed or relevant.
-
Maximum execution time with php-fpm and Apache
gizmola replied to NotionCommotion's topic in PHP Coding Help
The old school way of running php with apache was to use the mod_php apache module, which makes php a part of apache. So that was certainly different. You can think of php-fpm as a "php server" process. Using it with apache or nginx or any other http proxy means that php-fpm is running separately and being communicated with from the http server via fastcgi. Fastcgi is a specification that evolved from the original cgi spec, that was the earliest way a web server could be configured to send data to and from an external program. php-fpm is a php server that implements fastcgi, so it can be used with any http server or proxy that also supports fastcgi. One of the obvious things to notice is that the effective user running the php script can be different than the user that the apache process is running as. It also has some efficiency when compared to mod_php, for reasons I won't go into, but that I did examine in a blog post I made. One big problem with mod_php is that the apache child processes tend to grow and absorb memory when serving php, and this pool of child processes has to be used for every request, so even if apache is handling a request to return an image or css file, or other static content, the apache child process might be 500mb in terms of memory usage, because previously it had been used to run a php script. This is a big reason that nginx became popular, as it was always intended to be a high performance proxy, and always used fastcgi. With that said, when php-fpm runs a php process it still does so using the php configuration. It does have its own settings to manage fastcgi, so in that way it's got another group of settings that you have to configure, and areas where the communication between apache and php-fpm can have issues, so in that way it's more complicated. -
Yes, the CN name needs to match the hostname. You will have to add an entry on the PHP server that resolves to the IP. So make the CN something like mysqlserver1.dummydomain.internal, where dummydomain is whatever you want it to be. On the server running php make an /etc/hosts entry for that domain that resolves to the mysqlserver IP. Then when you connect, use the mysqlserver1.dummydomain.internal hostname. If you are using a version of php >= 7.1, an alternative solution that might work is to pass MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT in the flags parameter for mysqli_real_connect. Theoretically that gets you around the problem, and may be what is happening with the mysql CLI on whatever other machine you are testing with.
-
Is the server "remote"? When you did your "command line mysql" verification, did you do that on the server or from your workstation? A "decode" of the files generated by the mysql_ssl_rsa_setup: ca.pem - the "certificate authority" public key for the self-signed certs that were generated. (You will want this file on your client) client-key.pem - the "client" private key they generated. (You will want this file on your client) client-cert.pem - the "client" certificate that was generated which goes along with the client-key. These are the files you would need available to your client. Ideally you want to make copies of those files in a directory (not under the web root) of the server running your php application, with read only permissions, but still readable by the user that the php process is running as. You need to pass an actual or relative path to the files, when you make mysqli_ssl_set initialization. mysqli_ssl_set($con,"/path/to/client-key.pem","/path/to/client-cert.pem","/path/to/ca.pem",NULL, NULL);
-
You have hit a bug: https://bugs.php.net/bug.php?id=81145 The bug has been fixed, but apparently it's not been merged into a production release yet. For now you can try this workaround. Replace your copy() with the copyByChunk() function, and see if it solves your issue. Increasing the buffer size will probably help if the performance hit is substantial, but fair warning -- test this function out before you use it. I did no real testing of it. function copyByChunk($srcFile, $dstFile) { # Use 1mb chunks $bufferSizeBytes = 1048576; $bytes = 0; $src = fopen($srcFile, "rb"); $dst = fopen($dstFile, "w"); while (!feof($src)) { $bytes += fwrite($dst, fread($src, $bufferSizeBytes)); } fclose($src); fclose($dst); // return bytes written return $bytes; }
-
We need more information: What OS are you running on? Is this a CLI program or something happening via webserver integration? What version of PHP are you using? Copying from where to where? Is this from one directory to another on the same server? From one server to another? From a local directory to an NFS mounted one? A snippet of the code that actually does the copying would be helpful Possibly you hit a limitation rectified in a more recent version of PHP. Most likely there are several alternatives you can use to get around the problem.
-
Catching All HTTP Requests to Apache and Storing Them in DB
gizmola replied to mongoose00318's topic in PHP Coding Help
First off, I understand what you are looking for, and it is in no way unusual to want to have instrumentation and information about what is happening. There are many products out there, first and foremost Google Analytics. There are also log "mining/reporting" systems available. Awstats is one of them, but it's pretty old and I haven't used it in a long time. I'm not sure how functional and up to date it is. Here's a partial Google list of "alternatives to Awstats": Dynatrace. LogicMonitor. New Relic One. Datadog. Sumo Logic. Graylog. LogDNA. Apache log4j. Of these I've used New Relic, and Sumo Logic in the recent past, so it just goes to show you the many commercial and non-commercial offerings in this space. One thing you sometimes need to do, to get the level of information you want, is to modify the web server log format, and sometimes to inject additional variables into the logs. Things like session id's and cookies can be added to the logs to help establish things that can't be surmised otherwise. The details of doing this are an aspect of system administration that depend on your specific webserver and hosting environment. One specific example, would be the IP address of the request. If your server has a load balancer in front of it, the IP address of all requests will be the load balancer, and not the actual client IP, so that is an example of where you need to customize the logs in order to see what is actually going on. There are many many products and companies out there that offer logging infrastructure. One I've used in the past, not just for webservers, but for analysis of an entire cluster is Splunk. With that said, Splunk is a pricey commercial option. One FOSS stack that has a lot of mindshare and users is the ELK Stack, which consists of a setup of Elastic Search, Logstash and Kibana. Each piece of that stack solves a particular part of the problem that companies with sometimes large and complicated infrastructures face in getting server side analytics. You can do some reading about it here: https://logz.io/learn/complete-guide-elk-stack/ This might be the type of server based analytics system you want, and is modern, scalable and far more functional than a simple log parser/web reports system like AWStats. Most companies use multiple different options, as each tends to have a strength and a weakness. Google Analytics has a lot of features, but of course, it depends on the client running its javascript, and thus isn't ever going to show you requests that were still processed but didn't load javascript. If there are errors or bugs in the javascript on the page, this might cause GA not to log correctly or at all. Still you want to configure and start using GA with your site, and you will find it already gives you a lot of the functionality you want, without you having to do anything within your infrastructure. In my experience companies often use a variety of different tools. Sometimes, just looking at web logs is not enough, or doesn't really help you understand something, and you need logs of multiple different services. You might need to look at graphs of webserver(s) and your database for example, to see that a problem your system was having was related to database load at a particular time, which was in turn related to some slow queries that were running tying up the database resources for a long period of time. Resources on the server itself, like available memory, amount of swap being used, and cpu load, might show you that your server is overloaded or low on disk space. There are different types of logging and monitoring you can setup, that can often provide valuable insights into issues you will never find just looking at web logs. -
This is a great point from @ginerjm Mixing "presentation" and "logic" is the best way to have hard to maintain code. PHP is intrinsically a templating product, in that you can put partial html scripts and include them easily. There are also numerous excellent and easy to integrate template systems. If you can separate the database/model related code from all the other code that is really just html, it will be easier to see how to approach things in a simple and maintainable way. The concept is certainly related to KISS and to breaking larger blocks of complicated interdependent code down into discreet functions that do one thing in a predictable way. From a database standpoint, your comment that "it creates a duplicate entry in my database if the value was already checked" also tells you that you are not using features of the database engine that will provide you data integrity. You can use constraints/indexes, as well as "UPSERTS" to help manage this. I would provide further examples, but I have no idea from your code snippets what your database looks like.
-
Thanks for letting me know your outcome. This is what we are here for, but it's still nice to know that we helped.
-
how do i create a template page for multiple items
gizmola replied to RaiN3772's topic in PHP Coding Help
OR........... perhaps you just make a page call item.php, and you pass the id as a url parameter, query the data you need and present it. You can also use rewrites to make it look like a static url like /item/3. That used to be a benefit for SEO, but at this point search engines don't penalized you for having url parameters like item.php?id=3. -
Well yes, it violates relational database design rules, which are referred to as the rules of normalization or normal forms. This is in violation of the most basic rule, meaning your table can not be in 1st normal form, by doing what you are trying to do. See this article. Your instinct to put multiple values (categories) in a single column/row combination, tells you that you are going down the wrong path. Furthermore, if your table has category1, category2, category3 etc, then that is a repeating group which is also incorrect. There are many issues here: You can't add a new category position without changing the table structure & all associated queries Queries are ugly and inefficient because you will need to index every category column and have a query that has code like "if category1 = 3 or category2 = 3 or category3 =3" etc. What is the right structure? You need to understand the relationship between the entities (thing, category). Start with the relationship from "thing". What have you told us? "A thing can have many categories". So the relationship of thing -> category is "one thing to many categories". Now look at the relationship from category to thing. What do we know? "One category can define many things." So the relationship from category -> thing is "one category to many things". This tells you that the relationship between thing and category is actually Many to Many. Think about it for a minute, using simple examples. Thing1 (category1, category2, category5) category5 (thing1, thing20, thing1000) Currently you don't have a table for category. You need to make one. category -------- id smallint unsigned primary key AUTO_INCREMENT category varchar(80) This table should be loaded with all your 1-n categories. Create a table to resolve the many to many relationship between thing and category. Typically people name a table like this "thing_category". It only requires 2 values: thing_category -------------- thing_id category_id You can give this table its own unique primary autoincrement key if you want or define the primary key to be thing_id,category_id. It is important either way, that you have a key that guarantees uniqueness for a thing_id,category_id value. Hopefully can now see how you would use this table. If I want to set thing1 to have categories 3,7 and 9, then I only need to insert rows into thing_category of (1, 3), (1, 7), (1,9). To get the categories back out, you join the tables together. Your queries are simple when you need to query for a particular category -- just inner join thing to thing_category and specify WHERE category_id = 7, or whatever you need. If you want a few categories, the query can be WHERE category_id IN (3,7) etc. This also makes your system configurable and data driven, as new categories can be added to the category table at any time, and you can start to make use of them without having to change code, since nothing will be hard wired in.