Jump to content

gizmola

Administrators
  • Posts

    5,945
  • Joined

  • Last visited

  • Days Won

    145

Everything posted by gizmola

  1. Initializing without php7. $_SESSION['cartid'] = isset($_SESSION['cartid']) ? $_SESSION['cartid'] : 0; $_POST['cartitem'] = isset($_POST['cartitem']) ? $_POST['cartitem'] : 0; $_POST['quantity']) = isset($_POST['quantity']) ? $_POST['quantity']) : 0; $_SESSION['lockedcard'] = isset($_SESSION['lockedcard']) ? $_SESSION['lockedcard'] : 0; $_SESSION['lockedpaypal'] = isset($_SESSION['lockedpaypal']) ? $_SESSION['lockedpaypal'] : 0; // Now you can omit any isset() calls, and concentrate on the if/else conditions of the variables.
  2. We never established what version of PHP you are using? Perhaps these few fundamentals will help you understand: PHP has arrays. An array is like a toolbox that has compartments. With PHP these compartments can be named ie the 'cartitem' in $_POST['cartitem']. You are using these arrays: $_POST which is the contents of a form that has been submitted, and $_SESSION which is a special array that stores variables on the server associated with a client/web browser. If you try and access a named array element (example: $_POST['cartitem']) and that array element has not been set with a value, PHP will generate an error. This is why you are checking first with isset(). isset let's you code around the possibility a variable will not be set. In your code, despite the fact that you think the session variables would have previously been set, obviously there are times when they aren't. For example, if I open a browser and go directly to your post page, the session variables won't be set. Personally speaking, big chains of and/or combinations are ugly and hard to maintain. Current best practices are to do early return when possible on individual problems, but in order to understand how to implement that we would need to see more than the if condition. What is done/not done given success or failure? This explains why Barand's code is so much cleaner and simpler, as it uses an operator '??" called the "null coalescing" operator, that helps make this whole isset chaining of code obsolete, as it makes it simple to assign optionally assigned or passed variables a default value. It was added in PHP7 however, so if you are on a version prior to 7, then it would explain why it would not work. With that said, I would rewrite things so that ALL the required variables are set to known values if they fail isset.
  3. Check the value of userid. Is it not a varchar? WHERE a.oracleid = '$userid' If you write code this way, you are using variable interpolation which opens your code up to SQL Injection. That is why I showed you the parameter passing method, which uses prepared statements and bound variables. You would not need the single quotes if you used the parameter, as it will determine the datatype from the type of the variable being passed.
  4. Right, I see the issue. You have to determine the most recent outer array you've added which is going to be numerically indexed. Try this: $json[count($json)-1]['__children'][] = array( A less hacky way would be to have a counter for the outer array loop that you increment anytime you add a new element. Because numeric arrays are zero based, the first element is going to be $json[0], then $json[1] etc.
  5. Most likely you simply need to pass the oracleid into the query as a parameter. Assuming this is PDO... $stmt = $conn->prepare("SELECT s.oracleid , s.staffname , date_format(date, '%W %d/%m/%Y') as absent FROM staff s CROSS JOIN date d LEFT JOIN attendance_records a ON s.oracleid = a.oracleid AND d.date = DATE(a.clockingindate) WHERE a.oracleid = ? ORDER BY s.oracleid, d.date "); $stmt->execute(array($oracleid)); $result = $stmt->fetchAll();
  6. Use parameters in your mysqli code. DO NOT interpolate or you will be creating code that is open to SQL injection. $query = "INSERT INTO a_rankings_select (grade ,position) VALUES (?, ?)"; // $con would be the mysqli connection resource $stmt = mysqli_prepare($con, $query); //2nd param is a string of character(s) describing type of param. In your case these are strings, so 'ss' mysqli_stmt_bind_param($stmt, 'ss', $grade, $position); if (mysqli_stmt_execute ($stmt) { // Insert succeeded } else { echo 'Error: Grade ranking insert failed. Check input/or database status'; } If you spit out the contents of mysql_error, just be aware you could be leaking database connection information which attackers would love to have. Better to log that data, and provide your own customized error message as I illustrated here.
  7. As to your generalized question, yes you should use prepared statements for all DML. The issue is that you don't understand PHP classes adequately so you are missing out on some essential stuff and writing code that can't run. For example: $this->insertNewEntry->$stmt->execute(); You are trying to access a class method 'insertNewEntry' as if it was an instance variable. It's not. If you had a fluent design you might be able to do that, but I'm not going to get into that at present. You should move the $stmt->execute call into the insertNewEntry() method where it belongs, and then your method call would simple be: $this->insertNewEntry($planned_workout_id, $exercise_id, $set_id, $weight, $reps); Correspondingly, insertNewEntry has no parameter list, so there's no way for it to get access to all the variables it needs. Those parameters need to be added to the method definition. An even bigger issue with the same method is this: $stmt = $this->$connect()->prepare( Again you have a number of mistakes. This is trying to run some unknown method name stored in a non-existant $connect variable. What you actually want is: $stmt = $this->connect()->prepare( This has a good chance to work, however, it's going to be pretty wasteful if you are constantly making new database connections for every query. You would be better off, having a class variable that stores the connection, and then simply using that in all of your DML oriented methods. I don't think that inheritance is a great way of doing this as all your parent db class does is make a database connection with hardwired parameters. There is no big win there. Having a db connection class is fine, but you would be better off designing it to accept the database credentials from a configuration file. Your saveWorkout class would be better off using dependency injection instead, and having connection class instance injected into the class at construction. I've recommended this series by Fabien Potencier who is the founder of the Symfony project many times over the years. It talks about the Dependency injection design pattern and explains what it is and why it's a good way to design your classes. Read it here: http://fabien.potencier.org/what-is-dependency-injection.html More likely what I would see you moving towards is an implementation of ActiveRecord which is a model/orm design pattern used by many MVC frameworks including Ruby on Rails, and in PHP frameworks like CakePHP and the very popular and modern Laravel framework. Your base class would then generalize select, save, update, delete methods, and you would have a derived model class for every table you deal with. I would expect that you would have a class named 'workoutLog' that would mimic the structure of your workout_log table, with attributes that get/set all the individual properties that match your database. You can then have generalized code in the model base class that understands how to construct the SQL needed based on the model. Typically you have getters and setters for each column, but these can also be generalized in the base class using PHP's magic methods __get, __set and __call. See https://www.php.net/manual/en/language.oop5.magic.php This would allow you to quickly develop a base class that didn't require each derived model class to have all the properties enumerated for the your tables, if you wanted to avoid that. If you only have a handfull of tables, it might be easier just to author each model class so that it matches the structure of database table. Browse the Laravel Eloquent documentation to get an idea how this type of thing should be structured: https://laravel.com/docs/5.8/eloquent, and look at some of the examples to see the type of code that you write to do database manipulation with an ActiveRecord style implementation. I realize this is a lot of material and suggestions, but then again, you could start with Symfony or Laravel and not reinvent the wheel as you are doing currently.
  8. With older symfony apps there is the concept of environments. Symfony used to come with a seperate controller for 3 environments (prod [production], dev [development] and test [unit tests]). So I would expect that you are configured as production, which means that your app is running the app_prod.php front controller. This will be setup to operate in the same way that apache will often be configured to run by default an index.php file if you access a webspace path directly as in http://www.somesite.test/. With Mautic, things have been configured to run the app_dev.php frontcontroller for every application request. The other thing you have to understand is that symfony generates lots of code, which is what actually gets run. This involves twig templates, doctrine models, routes and lots more stuff. Symfony comes with a console app that has various command that let you generate this code, however, it may be that the apache user doesn't have effective read perms on the files the OS user generated. So my simple fix would be to do this: -have script delete the entire app/cache/* contents recursively, which your bash command list does. Prior to doing this you might want to explore the contents of that dir. You will have a directory for any environments that ran, which I would expect ideally would only be a prod directory. As you can see in the logs you showed, the runtime is trying to access some doctrine orm model proxies that couldn't be opened. Assuming this is the issue, once you delete the directory, open the Mautic app. This will cause all the code generation to kick in and all these files and directories will be owned by the effective web user. That user does need the ability to read/write/execute in the app/cache directory. It might take a few seconds for all the code generation to occur as you are essentially "warming the cache" manually, but once the files are generated they won't be generated again and everything should run at full speed. You could also add your own web function that would clear the cache from the web app, but if the web app is in a situation where it doesn't actually own the directory and/or files in question, there is no way for that user to fix anything once it's broken, and only the account that owns the files will be able to delete/chmod/chown them (or via root or sudo). Assuming you deleted the app/cache/prod user, and ran the Mautuc app, you shouldn't encounter any problems. Not knowing what came with Mautic, it could be that there are scripts being run on some schedule that undo the issue you will be fixing, but removing the app/cache/prod directory should fix the problem.
  9. Hello Vikas, The positioning would be controlled by the layout, html markup and css. It would be helpful for you to share the actual plugin you are using, as there are many covid-19 plugins that have popped up. Without seeing the markup, people would just be guessing. In general you want to understand css positioning. Here's a fantastic introduction video that should help you understand this better, and perhaps solve the problem yourself:
  10. Basically you need your initial array to have an associated array key named '__children'. So where you have this: $json[][] = array( It needs to be this instead: $json['__children'][] = array( As for "Ajax" what everyone is using now is fetch. Depending on your javascript knowledge, this is because fetch works with promises which are easier to deal with syntactically than to do similar things functionally. With that said, if you already have a lot of jquery, then you can use the jquery.ajax. Here's a nice fetch tutorial that introduces you to the basics: https://phpenthusiast.com/blog/javascript-fetch-api-tutorial If you need more just google for fetch. There are literally hundreds of tutorials and howto's you can find, as well as video courseware you can find on youtube that covers the topic.
  11. As far as I can tell, it looks like the right approach to me. Query data into an array, doing whatever transforms you need pass data to javascript as json using json_encode You might consider using ajax but again I'm not clear on the presentation/client application. That would allow you to better separate the front end from the back end, as well as leading to filtration/refresh etc. At that point your individual scripts just (optionally) accept some parameters and deliver the data in json format. This is how most phone apps work, implementing RESTful api's, as well as apps where the UI is using a javascript framework like Angular, React or Vue for the UI while still using PHP for the serverside functionality.
  12. Hey Dilbert, This video walks you through pretty much everything you would need. Since Atom came from github it has intrinsic github support. This video pretty much covers everything you need to know from setup to workflow within the atom ui:
  13. Hi Tony, Is this a symfony app? Are you getting incorrect ownership due to running command line as an OS user? My first suggestion is to stop doing that, as it's guaranteed to mess up your ownership in this type of scenario. I'm not seeing why you need ssh whatsoever. A bash or php script would do the job. Look at the various exec and related commands. I would have to question why you don't simply cron your bash script and run it every 5 minutes. Much simpler and less invasive. Write the script, put it in /usr/local/sbin or /usr/local/bin. sudo su - {appropriate user to run script}. crontab -e. Add an entry to run at the periodicity you desire. I don't know that you want to blindly delete the app/cache dir contents every 5 minutes if you don't have to. Bash is a relatively full programming language where you can do standard if-then-else logic. With that said, you can also write a command line php script and invoke it in a cron exactly as you would a bash script. Or you can call the php command line scripts from bash. None of these ideas require ssh, and I don't really see what you need to run this remotely for if you have it running under cron automatically for you. If you are convinced you need remote execution, you could exec a script from a php page, but of course that will run as the OS user, and if you need sudo to correct some problems, you certainly wouldn't expect the apache user to have either a shell or su or sudo. A sysadmin/Devops person would turn to Anisible or Puppet for on demand controlled execution and administration of a cluster of servers, vpc's or what have you, but Ansible could work for you as well. Of course it might not be possible for you to install these tools in a shared hosting situation.
  14. Please consider using json for all transfer between your javascript and php. It is the de facto standard way of doing this, and the main way anyone does REST/AJAX etc. these days. With json_decode and json_encode, you can naturally and easily convert between json objects and arrays and php objects and/or arrays.
  15. You are using Template Lite? Seems like very little updating of that package, no github repo, and a copyright of the original author. From what I can see, the purpose of Template Lite was to be a drop in replacement for smarty. Smarty compiles the templates into PHP scripts, so Template Lite must do the same. If the original code is not a smarty template, I don't know why Template Lite would be part of the problem or the solution. It was created simply to be a drop in for Smarty, which in its day was a popular php template package, but has been bypassed by newer template engines like twig and laravel blade.
  16. I don't know whether you care or not about People with names like "Martin St. Louis" but obviously your code will not work correctly in that case. Of course you also can't tell if it's someone with a name like 'Sue Ann Smith'. Your code is biased towards Sue Ann Smith, but gets Martin St. Louis wrong. Without a separation of first name and lastname, there is no way to really do it reliably. With that said, you can boil this down to a one liner that doesn't use arrays. I'm fairly sure that your code would throw a runtime error if there was a single name in the string, but didn't test it. This could/should be coded around, which I do with a ternary. There is a lot of extra trimming I do, which could be avoided if the original string was simply trimmed prior to using this one liner, but I provided something that works with a variety of extraneous spaces, per the examples. Here's a one liner as a function for the purposes of illustration, that you might consider: $tests = array('Bob Jones', 'Sue Ann Smith', 'Martin St. Louis', 'Prince', ' Adam West', ' Fred R. Murray ', ' Skipper Van Dammage'); foreach ($tests as $test) { echo makeName($test) . PHP_EOL; } function makeName($name) { return false !== strpos(trim($name), ' ') ? preg_replace('/\s\s+/', ' ', rtrim(substr(trim($name), 0, strrpos(trim($name), ' ')))) . ' ' . substr(strrchr(rtrim($name), ' '), 1, 1) : trim($name); } Returns: Bob J Sue Ann S Martin St. L Prince Adam W Fred R. M Skipper Van D
  17. Hi Phi11w! I agree strongly that a model class for player would be a great addition. If you look closely at what was requested, you might notice that JIm R has implemented linking based on the user name, so it's not quite as simple as making a name out of first/last, although you would improve the part of the code that utilizes the firstname,lastname in links. I can tell that we both would probably agree that adopting some sort of MVC is a best practice, and you illustrate a very easy way to start doing that without full scale adoption of Symfony, Laravel or some other framework.
  18. The answer to that is to use "templating". PHP is designed as a template language but most people use a template component library like smarty or twig. I would highly recommend twig. Either way you seperate your presentation from your logic. It's been a long time since I used Smarty, but with twig, you have the ability to use blocks and partials, so you can have a partial block that you include whenever you want a particular block of html+ data. This would solve your complaint in regards to reuse of markup. So how could you make this all work just with PHP? You make a small include file that looks like this: <a href="/tag/<?php formatPlayerTag($nameFirst, $nameLast); ?>"><?= $nameFirst ?> <?= $nameLast ?></a>; You might name this script using a convention like '_player_name_href.php'; In your main script where you have your output, and the link is meant to appear you just include it: // Read all data into an array using whatever database routines you are using $players = some_fetch_all(); foreach ($players as $player) { $nameFirst = $player['nameFirst']; $nameLast = $player['nameLast']; include('_player_name_href.php'); } This will create your list of links, where the creation of a tag is in a single function (you would want to have in a library script you include) AND your html snippet is in a single place so that if you change it you'll change it in the one place. You've done relatively modern functional programming, and you've kept separation of concerns, started to unmix logic and presentation so that you aren't producing spaghetti code. Just to tie a bow on this discussion, let's say you don't want to try your hand at making your own templating as I illustrated. You can stay with the functional programming approach, by simply creating a 2nd function that outputs your markup. This addresses several of your complaints without making a gobbledy gook function that mixes the 2. Again you will use your original formatPlayerTag function, but you'll pass the data to a 2nd presentation function. Here's how you would do it: function formatPlayerTag($nameFirst, $nameLast) { return strtolower($nameFirst) . '-' . strtolower($nameLast); } function getPlayerNameWithTag($nameFirst, $nameLast) { return '<div><a href="/tag/' . formatPlayerTag($nameFirst, $nameLast) . '">' . $nameFirst . ' ' . $nameLast . '</a>'; } Now to use this: echo getPlayerNameWithTag($row['nameFirst'], $row['nameLast']); You stick both of those routines into a library script you make, and include it in any scripts where you need to create the links, and you have a standard format, with 2 simple functions you would need to alter (should that be required). The more that you can have functions which do a single thing and return a result, the more robust and testable your application will be.
  19. Hey Jim! First a tip. You will be better off if you attempt to adopt PHP Standard coding conventions. I will suggest this link: https://symfony.com/doc/current/contributing/code/standards.html Most of these standards are in PSR-1 and PSR-12, which were ratified and adopted as community standards. The main one you ran afoul of with this plan is the name of your function. Don't use underscores. Instead use "camel case" for naming. Since you are constructing a standard player name tag, a good name for this function might be "formatPlayerTag" or "makePlayerTag" or "getPlayerTag". Often with databases, there are "getters" that will start with the word "get", so in this case you might not want to use get, but something that better indicates that you are making a standardized string of some sort from other data. Another thing you want to avoid is mixing markup with data. I know it seems like an easy way to go right now, but I would advise against spitting out the html in this function -- only have it output the text portion. Another thing you don't want to do here is have a function that does an "echo". Functions should take parameters, make computations and return a result, exactly as math functions do. My suggestion: function formatPlayerTag($nameFirst, $nameLast) { return strtolower($nameFirst) . '-' . strtolower($nameLast); } #used in the while echo '<div><a href="/tag/' . formatPlayerTag($nameFirst, $nameLast) . '">' . $nameFirst . ' ' . $nameLast . '</a>';
  20. For these types of questions, you have to do some research, reading the manual page, and any associated comments. In most cases, I would opt for a validation filter unless I knew I had some edge cases I absolutely had to support. In the case of email, you need to do a couple of things per the manual: So you want to review RFC 822 (if you care enough) to see what RFC 822 specifies in regards to valid email addresses. There are a good number of interesting notes you probably want to read, and possibly test out.
  21. By far the best php editor! Should probably clarify that the company is JetBrains. Here's a link to the PhpStorm version. Started out as a Java IDE (IntelliJ Idea), and it's essentially the same base editor across the line, but I'd still recommend that you buy the Php specific version. There's a 30 day trial you can use to check it out. Has a huge number of plugins and configuration options available, so you can configure your code style, apply rules from various codesniffers and standards. As for a free editor, I'd go with Eclipse PDT.
  22. I would go with either Authy or Google Authenticator. There are popular component libraries for each: Google Authenticator: https://packagist.org/packages/phpgangsta/googleauthenticator Authy (I know you saw this already): https://packagist.org/packages/authy/php
  23. Why don't you var_dump or print_var the contents of $data to debug this. An obvious concern is that you do not urlencode() $data[0]. $url= "http://localhost/home/crud-link.php?target=". urlencode($data[0]); We need more information than "but the link doesn't work." What exactly does that mean? Probably not related, but the form is user input, and your mysqli queries should be using mysqli_prepare with a bound parameter.
  24. Try building it out. There's next to no complexity on the PHP/server side. There is some complexity on the client-side if you are not experienced with javascript, and in particular ES6 javascript syntax. With that said, any modern UI is going to have a good amount of javascript in it, so it's the price of having a functional modern web user interface. JSON is something you need to be comfortable with as it's by far the most popular format for REST api data formatting. As I said in my response, take it step by step: Write the php script Test it out using a browser or a tool like Postman. Validate your json response Make a client page with a button that calls your PHP script via Ajax and updates a link Add the Polling At each step along the way, you will have learned something valuable, and figured out how to test and debug without having to put everything together perfectly on your first try. If you are out of your depth in regards to javascript, you are not alone, but you have something you can study up on. FreeCodeCamp is an amazing organization that provides totally free top notch educational content. Here's a complete course on Javascript for beginners!
  25. @SaranacLake Your summary is great. Requinix makes some good points. While MySQL does conflate the terms Key and Index in DDL as alternative ways to achieve the same physical thing, there really is no relational concept of a "key". Only a "Primary Key" or "Foreign Key". The other thing about MySQL we have covered previously, is the importance of the InnoDB engine for providing referential integrity, and ACID. It also does row level locking whereas MyISAM only has table locking, albeit very fast table locking. What this means is that your DDL that defines a table might be something like this: CREATE TABLE IF NOT EXISTS checklists ( todo_id INT AUTO_INCREMENT, task_id INT, todo VARCHAR(255) NOT NULL, is_completed BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (todo_id , task_id), FOREIGN KEY (task_id) REFERENCES tasks (task_id) ON UPDATE RESTRICT ON DELETE CASCADE ) engine=MyISAM; This DDL will run without issue, regardless of the existence or lack thereof, of a tasks table. For a long time, MySQL defaulted to the MyISAM engine, so even without the engine statement, it would run, discarding the foreign key constraint that would be created or checked for validity with the InnoDB engine. You can see the available engines and the default by issuing: SHOW ENGINES\G or SHOW ENGINES
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.