Jump to content

gizmola

Administrators
  • Posts

    5,959
  • Joined

  • Last visited

  • Days Won

    146

Everything posted by gizmola

  1. Clearly you are floundering and unsure how to proceed. That is easy enough to see from the code you posted. The way to attack this (and to program in general) is to break things into smaller pieces. Those pieces are functions and/or methods. There is no way for anyone to help you at this point without writing the code for you. Start thinking about how to break your problem into smaller pieces. Those individual pieces can be turned into functions, which you can test individually. This is one of the reasons that people write unit tests with phpunit. The other problem with your code, is that you have no separation between the logic, html markup and organization of data. This problem of disorganization is so common, that the Model-View-Controller (MVC) pattern became widely adopted in order to solve it. One way you could start to see where you need functions or methods, would be to take the markup you have and mock up all the final data. Another issue with what you are asking for, is that it presupposes a lot of javascript. You essentially are presenting an input table, where you have a lot of cells, corresponding with your poorly designed database table, and you are asking how an html/javascript UI can be created to allow update of that. There isn't one answer to this, so again, people aren't going to just write you up a bunch of code. Personally, I refuse to work on questions where the underlying relational database structure is fundamentally incorrect, and yours falls into that category. Your revenuetarget table with it's 12 month columns is an example of a repeating group. Rather than having one row per year, you should have a table that has a "month" column, just as you have "year" column, and there should be a row for each month.
  2. No, it is telling you the exact opposite. Redirection was considered first, which explains why greetings.txt is not an argument counted or sent to the program (echo). @Kicken provided a really great explanation.
  3. Far better ways of learning PHP: https://phptherightway.com/ Learning PDO (Relational Database API) https://phpdelusions.net/pdo If you are a visual learner, who likes streaming video courseware:
  4. This begs the question of how well you understand binary/octal/hex and bitmasks. These are all fairly valuable computers science fundamentals, as they are certainly useful to understand not just for unix file and directory permissions, but for things like networking and in particular subnet masks. This also overlaps with boolean operators and bitwise operators, as well as floating point representation. It's also good to understand the way data is represented internally thorough defined datatypes used by persistence engines and relational databases. One command that is not commonly discussed is the stat command. Try using it on files and directories to get a summary of information and meta information about a file or directory. >stat ssl File: ‘ssl’ Size: 4096 Blocks: 8 IO Block: 4096 directory Device: ca01h/51713d Inode: 920958 Links: 2 Access: (0775/drwxrwxr-x) Uid: ( 500/ec2-user) Gid: ( 500/ec2-user) Access: 2023-05-20 20:23:29.770828847 +0000 Modify: 2023-05-20 20:50:30.995642112 +0000 Change: 2023-05-20 20:50:30.995642112 +0000 Birth: - If you are already confident in your knowledge of these fundamentals, the obvious answer, provided by requinix is that these commands use octal values for historic reasons, but are typically not as user friendly as the alternative versions that employ constants. For example, even though I fully understand the octal values, and the position of those values in these bitmasks, it's just easier to think about the matrix of user/group/other and Special,eXecute,Read,Write. Thus it's much easier in my opinion, to just think about what you want to set or search for with something like s=u (special bit = user, aka suid) than what the positional octal value of a bitmask are, even though you should be able to derive them yourself, as requinix showed.
  5. Simple subquery article: https://www.guru99.com/sub-queries.html A subquery is exactly what the name describes: An inner (sub) query that is run, with a result that is then used by an outer query. It is not complicated. In order for it to be used in a "WHERE column =" the subquery must return at most 1 value. If it can return multiple rows/values, then you need to use "where column IN" or possibly NOT IN. My 1st tip: a subquery can't possibly work as a subquery, if it doesn't run by itself in standalone fashion. You want to investigate, whether or not you can use a HAVING clause without a GROUP BY.
  6. Your code seems to be entirely variable driven dynamic sql, based on user input. What could possibly go wrong? 🤐 Add logging routines that log the actual SQL statements AND parameters to a file. I'm sure if this continues to happen, in short order you will see what is being done. Seeing these routines themselves, it's easy to see that anyone can essentially update any table they want, if they can get the variables to these routines set to be what they want. You haven't provided any of the UI code or table structure(s) information for context, so there's not much more we can do to help, when we don't have any idea what those things are or how these routines are called.
  7. Yes, and as others have already stated, you need 3 things: Client javascript to run the countdown UI A publish/subscribe feature A persistent bi-directional socket connection between client and server HTTP 1.x protocol, by itself is not designed for persistent connections. When a client sends an HTTP Get request to a server, the server responds with content (usually the HTML of the web page) and the connection to the server is closed. HTTP is not bi-directional nor persistent. In an application like this, you need some way around the way HTTP 1 was designed to work. This is why multiple people have suggested that an application like this should use websockets. Websockets is an alternative protocol designed for persistence. Since Websocket protocol was developed, HTTP 2.x was released, which overlaps to a degree with websockets. The problem with websocket protocol, is that, while it is relatively simple and has both client javascript support, as well as PHP support, from the serverside, you need to run the websocket server in addition to your web server, which adds a degree of complication that can be difficult for someone without a lot of system administration experience to retrofit. The main options for building a PHP based websocket server are: ReactPHP Ratchet Swoole I'd suggest you take a look at these, and perhaps experiment with some of the examples provided. In terms of publish/subscribe, your control client will publish the sync/start/stop/pause, and the other clients subscribe to these events. I will say that this is a non-trivial application, with a lot of design elements to think about.
  8. ginerjm: everyone starts somewhere. A student learning to code is only going to provide code representative of where they are at a particular point in time. This is likely for an introductory class, and not a bootcamp or professional certification.
  9. Beyond the specific advice that was already presented, the design of your shopping cart is completely wrong. Do not use IP address for identity! IP addresses are not a proxy for a single user, and have no intrinsic association with a browser session. Things you must understand better to see why this is: How does NAT work? IP4 vs IP6 VPN's As a simple example, what do you suppose might happen with your cart, when a user opens up your site in chrome, and on the same computer opens it up with safari? What if they open a 2nd tab to your cart? PHP has sessions, which are purpose built to correlate a web user in your PHP serverside code. You should not be using an IP address to identify an otherwise anonymous user. You should be using a PHP session (which uses a cookie) possibly in combination with an additional cookie for "remember me" type functionality.
  10. One other thing that can be a bit confusing is that WSL2 is not really "version 2" of WSL. You can choose to use WSL or WSL2, and as a matter of fact, can have both of them installed at the same time. That's non-intuitive, given the way most software works. If you are having issues getting WSL2 to work, you might consider just using WSL.
  11. If you are looking for -- exactly, a line that starts ... then has something you want to match, followed exactly by the end of a line, then you may want to use those anchors. Regex is integrated into a lot of different languages and subsystems, for a number of different purposes. For example, it might be that your use case is to find, within a bunch of lines of text, a particular pattern like a phone number or a url. Another use case, might be entirely different, as in the case of a password which must meet certain criteria. In the case of a password, you would want an exact match, including the start and end anchors, whereas, if you're looking for a phone number or a url within a bunch of other text (perhaps in a forum like this one) then you certainly would not want the match to only be made including the start and end line anchors. In some subsystems (apache mod_rewrite for example) the context of the data available to be evaluated with regex, already assumes start and end anchors, and actually trying to apply them won't work, so that might lead to some confusion, when rewrites don't work the way you expect.
  12. Unless the "style" of the original programmer is to be inefficient, there is simply no comparison. The code you are using is extremely inefficient, as is most loops with an outer query that then drives an inner query. You are doing a query for every category. That is slow and adds unnecessary strain on the database server. Barand provided you the way an experienced developer would handle it: one query using a join, so that you get one result set with all the data you need to display. At the end of the day, it's your system, but you aren't maintaining anything for updates -- you've changed the original code and if they provide you an update, the change you just made will disappear, and you will need to figure out how to make it again, which is fairly standard with any customization that modifies the original code provided.
  13. Limit is relative to the ordered result set, so you don't need to try and manipulate the result from a row count. ORDER BY salary LIMIT 0,1 //would be the lowest salary ORDER BY salary LIMIT 3,1 // would be the 4th lowest ORDER BY salary DESC LIMIT 0,1 //would be the highest The other thing to be aware of in a question like this, is -- are they trying to find the 4th lowest salary irrespective of employee, because there could be multiple employees wih the same salary. The question might require you to use a GROUP BY to eliminate duplicates, and can become more complicated from there, if for example, there are 3 employees who are tied for the actual 4th lowest salary. Your current queries do not actually find the 4th lowest (whichever), but find the 4th row in the result set. Depending on the requirements of the question, your initial answer (aside from the unnecessary attempt to make an offset relative to the count of rows) might be factually incorrect.
  14. Bash is a shell that can provide you an interactive environment to run commands, but it also supports scripting and programming features, so the context within which you are using it is important. Since many people find good reasons to automate tasks with scripts, the way that environment variables or command line arguments are processed is important. The example commands you started with, are meant to illustrate the fact that a bash shell has environment variables associated with it. When you make a new bash shell from within a previous one, the default behavior is that you inherit environment variables from the parent shell, but otherwise, environment variables you add via export are local to the shell you have created. Run these commands in a bash shell to see how this works. export SHELL_NAME=one echo $SHELL_NAME bash echo $SHELL_NAME export SHELL_NAME=two echo $SHELL_NAME exit echo $SHELL_NAME In the particular commands you presented, the 1st command shows you the value of 3 built in environment variables. The 2nd command is "env" which is a command that then runs the command you specify (in this case bash) with specific environment variables set or unset depending on what cli options you provided (-i in this case) or otherwise specified. Because there are no environment variables specified with "env -i", you can see that there are no values for the $HOME and $USER environment variables, when bash is run by the env command. Normally bash would inherit the parent shell environment variables as I illustrated above. This variation of the command should further illustrate why the env command might be used to run a command with specific environment variables set. env -i HOME=$HOME bash -c 'echo $SHELL $HOME $USER' In all cases, bash -c is needed so that you can make bash execute the quoted commands as if you had typed them interactively. You should take a look at the bash command man page to see what arguments it will accept. It should be obvious that if you simply tried to add additional programs with arguments on the command line, those same lines would not work the way you intend them to.
  15. Step back from "what works" and think about the fundamental ideas. A query returns a result set that can have 0 .. n rows. If your original query did not group by, what would the result set have? Because you have join from order to order_details, and the relationship is such that each order can have one-to-many order_details, you can end up with multiple rows for an order. It's clear from the original question, that the desired result is to have one row per order This is where GROUP BY comes in. Whatever column(s) you group by, will create exactly one row. The evaluation of the grouping is left to right, by which I mean that you can group by multiple values, but the grouping starts with the first column, and each subsequent column in your group by, is evaluated only after the first/preceding grouping is done. For the question you started with, you don't need additional grouping other than orderid. You should be able to determine this, because the aggregation being done (SUM in this case) is being done on the order_detail price/quantity values. The error you started with, is based on trying to order by emp_name, which is entirely different grouping. At the point that you GROUP the original result set by the names of the employees, you no longer are guaranteed to have one row for every order. If an employee named "Bob" created 10 orders, there would again be one row for "Bob". From the database standpoint, orderId is nonsensical. Which of the 10 possible orderId values that were reduced to a single row, should be displayed with Bob's group? This is no different than if you were to GROUP By order_id, and try to include order_detailID. It wouldn't make sense for the database to try and pick one order_detailID out of the set of related rows, so the database returns an error. As Kicken pointed out, ANSI standard SQL has certain rules associated with it, but MySQL (and other relational databases which provide modality and configuration) will sometimes allow things that a particular standard doesn't. MySQL, for example, has a mode that allowed you to specify in your select list, columns that weren't specified in the group by, or in aggregation functions. The manual talks about the way this works, and the specific default mode that drives how mysql group by works. In your query, it is the c.contactname value that mysql is allowing you to select even though that column is not part of the group by with However, if you consider what I previously wrote about grouping, you would be able to get the same result by adding that column to the group by: GROUP BY orderid, c.contactname, empname
  16. Barand already did that. He changed the code as required, to make it work. Did you try it to see if it worked?
  17. Everything I'm going to say, is based on the default behavior of php sessions. Session behavior can be altered by changing php configuration variables or in most cases, overriding the runtime variables in your script prior to doing anything else. You need to verify what these settings are for your specific installation. Sessions, by default are simply files stored on the server, that contain the contents of the $_SESSION array in serialized form. These variables are serialized/deserialized during the runtime of a php script. The way the server associates a session file on the server with a user, is via a cookie. The default name for that cookie is PHPSESSID The full list of runtime session configuration variables is here. So let us look at the code you provided: if (isset($_COOKIE['session_id'])) session_id($_COOKIE['session_id']); session_start(); if(!isset($_COOKIE['session_id'])) setcookie('session_id', session_id(), 0, '/', '.yourdomainname.example'); So a few things to point out about this code: It exists to change the name of the cookie from 'PHPSESSID' to 'session_id'. That's a lot of wonky code to do something that has official session specific functions to accomodate. This code is attempting to go around the built in cookie session handling, and is likely the source of your issues. My advice is to use the session specific functions instead. session_name('session_id'); session_set_cookie_params(0, '/', '.yourdomain.example'); session_start();
  18. @ginerjm makes a good point here. Omit the ending tag in all your scripts, unless you are going in and out of php mode. Even if you are doing that, you still never need a php end tag "?>" at the bottom of your script. Having one can lead to hard to debug errors, particularly when you are include/require scripts which you did in your code with your "settings.php" script.
  19. Hello Sanjay. Just to be clear, the way this and other forums work, is that people ask questions, and other members are free to read those threads and participate with responses and advice if they would like to. A good way to start is to use the Activity menu/My Activity Streams/Unread Content and browse the threads to see if there is anything of interest to you.
  20. No, log file deletion is not going to bring down Wordpress. Logs are logs, and intrinsically disposable. Most get "rotated" aka archived and deleted on a rotating schedule. A required config file getting deleted might also crash the server, but it doesn't sound like that's the problem. What's possible is that what got deleted were MySQL or MariaDB log files, so now the server is crashed. You stated you think the database is fine, but I question that assumption. The assumption could easily be verified using the cli mysql client, or perhaps a phpMyAdmin setup or something similar if the control panel has that, or it's installed somewhere on the server. It's possible that an expert MySQL dba could find a way to get a MySQL server running again, after something so catastrophic as the deletion of required InnoDB logs, but more than likely you will need to reinstall mysql, and recreate the database(s) from mysql backups/dumps. There are different ways to configure the InnoDB server, so there's not one cut and dried prescription for how one might approach a problem like this. If there's no backup, well then --- it's very likely there's no "recovery" option. In general "recovery" is facilitated by database log files, and is designed to recover from issues that happen outside the log files. These are more accurately referred to as "transaction logs" and should the server crash, these logs are used to rebuild the database and recover it to the most recent transactions, which usually happens automagically when the mysql server is restarted. You're just asking us to guess, but that's a reasonable one for you given the limited information available to us.
  21. Just to be clear, you implemented the fix for the bug that cyberRobot provided? if( $admin == 1 ){ So at this point your entire question has changed! Now you are always going to index.php rather than admin_index.php? A few general comments, and things I noticed: The correct valid form of the location header is: header("Location: index.php"); Notice "Location" not 'location' and the space between the colon and the url. MDN is a good place to verify these types of things: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location These small details often aren't a problem, until they are, and something doesn't work right, and you can't figure out why. In general, you are at the point, where you need to verify your assumptions one step at a time, with debugging output, using var_dump(), die("something...), or something like what @cyberRobot provided in your last message. The other option is to get xdebug working, so you can step through your code. Setting it up can be difficult for some people, depending on your development environment and IDE being used, but it is often a tremendous aid to developers who are learning. If you want to let us know what your development environment is (os, php setup, code editor etc) we might be able to locate some resources or tutorials to help you with the setup. This code appears to be wrong: $_SESSION['$username'] = $row; $_SESSION['user'] = $username; First you have $username, which is an odd key, and makes me wonder what you are trying to do there. It also looks like these assignments are mixed up. I would assume what you really want is: $_SESSION['username'] = $username; $_SESSION['user'] = $row; Last but not least, I would strongly urge you to start looking at how to employ functions, to make your code more manageable and DRY. Look at how many places you are doing a header location! Consider this simple function: function redirect($url): void { header("Location: $url"); exit; } You might notice that whenever you redirect using the location header, you can not trust the browser to perform the redirect, so you should always exit() so that no additional code will be run. Putting it in a function, helps insure you don't forget. With this function, your code would become: if (isset($_POST['login'])) { extract($_POST); $query = "SELECT * FROM users WHERE `username` = '$username' AND password ='$password'"; $result = mysqli_query($con,$query); $num_row = mysqli_num_rows($result); if( $num_row > 0){ $row = mysqli_fetch_assoc($result); $id = $row['id']; $_SESSION['user'] = $row; $_SESSION['username'] = $username; $admin = $row['admin']; if( $admin = 1 ){ redirect("index_admin.php"); } else { redirect("location:index.php"); } } else { redirect("login.php?msg=error"); } This is more of a best practice recommendation, but when you have code like this, that has a functional flow that ends/exits/returns, it is best practice not to employ nested if then else blocks when you can avoid them. Your code can be rewritten this way: if (isset($_POST['login'])) { extract($_POST); $query = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` ='$password'"; $result = mysqli_query($con,$query); $num_row = mysqli_num_rows($result); if ($num_row < 1) { redirect("login.php?msg=error"); } $row = mysqli_fetch_assoc($result); $id = $row['id']; $_SESSION['user'] = $row; $_SESSION['username'] = $username; $admin = $row['admin']; if ($admin = 1) { redirect("index_admin.php"); } redirect("location:index.php");
  22. You have this code: $query = "SELECT t.transactioncode AS tCode, c.transactioncode AS cCode FROM tsc AS t LEFT JOIN Candidates AS c USING (transactioncode) WHERE transactioncode = ?" $stmt = $conn->prepare($query)->execute([$tcode]); $result = $stmt->fetch(); Look at the 3rd line here. Your code assumes that $stmt is a valid result set that you can use to fetch results. The problem is that if your query fails, $stmt will not be a result set, and you will not be able to fetch with it. This is what is happening. You need to figure out what is wrong with the executed query, but also as @ginerjm showed you, you also should not have code that assumes a query worked to generate a valid result, as your current code does. You should check that $stmt is true/valid first.
  23. Great advice. And there is also a built in debugger, where you can set breakpoints in your javascript code, and step through line by line to see how variables change (or not). You use the sources tab for that.
  24. It is pretty hard know what to tell you, as there are a lot of potential variables regarding the type of mac you are using and the OS version. If one of your primary uses of your mac is java development, then I wouldn't recommend homebrew. I would suggest that you install either the openjdk or oracle version of the sdk. This article covers installation of the current version of OS/X (Ventura) https://wolfpaulus.com/tomcat/
  25. Need more information other than "something is wrong". What exactly is not working the way you expect? Do you get any errors? Some obvious things that jump out are: await fetch('http://localhost:80/api/login.php' Just use a relative url here: await fetch('/api/login.php' This header does not make sense for development. header('Access-Control-Allow-Origin: http://localhost:3000'); Start with something permissive and determine later if you can lock it down. header('Access-Control-Allow-Origin: *'); Why are you posting the data as json? JSON is great for javascript, but has no value for PHP. I would recommend just making a standard post structure. Then you can dispense with having to json_decode it and you can use the $_POST superglobals. $email = isset($_POST['email']) ? isset($_POST['email']) : ''; $password = isset($_POST['password']) ? isset($_POST['password']) : ''; At any rate, when you return json, you need to set the Content-type if ($_SERVER['REQUEST_METHOD'] === 'POST') { header("Content-Type: application/json"); Last but not least, remove any PHP end tags. End tags are never a good idea, and only should be used in a script where you need to mix html and PHP together. You should never end a script with a php end tag. See PSR-12 for this and other coding standard recommendations.
×
×
  • 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.