Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 09/25/2021 in all areas

  1. It's the antithesis of progress and learning. We can only tell him stuff that he already knows, which is pointless. If he doesn't know it he won't use it. Therefore, whatever we tell him is a waste of time.
    2 points
  2. Using a DB, I'd do it this way (tables used are from my SQL tutorial). Select a house name and the pupils menu lists pupils from that house. <?php const HOST = 'localhost'; const USERNAME = '????'; const PASSWORD = '????'; const DATABASE = 'jointute'; // default db $db = pdoConnect(); //============================================================================== // HANDLE AJAX CALLS // if (isset($_GET['ajax'])) { if ($_GET['ajax']=='pupilopts') { exit( json_encode(pupilOptions($db, $_GET['hid']))); } exit('INVALID REQUEST'); } //============================================================================== function houseOptions($db) { $opts = "<option value=''>- select house -</option>\n"; $res = $db->query("SELECT houseID , house_name FROM house ORDER BY house_name "); foreach ($res as $r) { $opts .= "<option value='{$r['houseID']}'>{$r['house_name']}</option>\n"; } return $opts; } function pupilOptions($db, $hid) { $opts = []; $res = $db->prepare("SELECT pupilID , CONCAT(lname, ', ', fname) as name FROM pupil WHERE houseID = ? ORDER BY lname, fname "); $res->execute([$hid]); $pups = $res->fetchAll(); $opts = array_column($pups, 'name', 'pupilID'); sort($opts); return $opts; } function pdoConnect($dbname=DATABASE) { $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $db; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Example</title> <meta charset='utf-8'> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> $().ready( function() { $("#houses").change( function() { var hid = $(this).val() $.get( "", // specify processing file on server (in this case it's same file) {"ajax":"pupilopts", "hid":hid}, // data to send in request function(resp) { // handle the response $("#pupils").html("<option value=''> - select pupil -</option"); $.each(resp, function(k, v) { $("#pupils").append($("<option>", {"val":k, "text":v})) }) }, "JSON" // response type ) }) }) </script> <style type='text/css'> body { font-family: calibri, sans-serif; font-size: 12pt; } div { margin: 16px; padding: 8px; border: 1px solid gray; } label { display: inline-block; background-color: black; color: white; width: 120px; padding: 8px; margin: 1px 8px; } </style> </head> <body> <div> <label>House</label> <select id="houses" > <?= houseOptions($db) ?> </select> </div> <div> <label>Pupil</label> <select id="pupils" > <!-- pupil options --> </select> </div> </body> </html>
    2 points
  3. First, let me just opine that there are generally accepted reasons to create stored procedures. Those include 'performance', 'adding business logic', 'doing things that can't easily be done in a single query/ie having procedural logic', 'providing a procedural api that enforces business rules', and in the case of triggers, enforcing complex data integrity, which is often done with triggers, and can't easily or robustly done client-side. What you have to understand about MySQL, is that it doesn't work the same way that Sybase/MS-SQL Server or Oracle work. In those DB's, sprocs are cached in global server memory, so they can be shared by connections. Oracle also has heavy client connection overhead. MySQL does not work that way. Quite probably, a normal query will be faster with MySQL in many circumstances, when compared with a sproc, because you have to understand that MySQL sprocs are not available in a shared memory structure like Oracle. So performance is not one of the advantages of sprocs in MySQL. The sproc memory exists PER Connection! So that should give you pause, from a performance standpoint, because each connection will need memory allocation for sprocs, and conversely, the fact that clientA is calling a sproc, does absolutely nothing for clientB. There has been rumblings that something might be done about this architecture, but as of MySQL 8, as far as I know the per connection sproc cache is still local. So to be absolutely clear, what happens when you create a connection to MySQL, every time you use a sproc, it gets compiled (if it was not already used), and stored in memory. There is not pre-compilation performance boost you get from other databases like Oracle. Furthermore, PHP is a "shared nothing" environment. Depending on how you are running PHP, database connections will be created/destroyed frequently, or upon every execution. The fact that mysql connections are lightweight and performant is one of the reasons it has always been a good partner for PHP data persistence. This was your original concern. Most of us tried to convince you that you already are covered for those concerns by: Disallowing multiple statements in PDO Using bind variables Using InnoDB with allocation of memory to buffer pools, to maximize cache hit of result set data PHP does give you a robust and highly capable language to build your reporting tool, and your code can be safe and will be performant against mysql, and sprocs bring nothing to the table that will make that better for you. I understand that you have felt frustrated in this conversation, but this is a frequent phenomenon in the tech communities I frequent, when someone comes from a point of view that has predetermined a particular approach is the only way to do it. People immediately question whether or not, as the old adage goes, this is a "person with a hammer, who sees everything as a nail." I think this was a valuable thread that contributed to the community, and I appreciate your perseverance and patience in sticking with it, but I also hope you can see that developers who are donating their time to try and help other developers tend to get a bit irritated when they perceive that someone is telling them "just shutup and answer my question", especially when they aren't convinced that the problem to be solved has been articulated clearly. With that said, I hope you will continue to find the forum valuable to you now and in the future.
    2 points
  4. Or avoid the concatenation which is usually the biggest source of error (and the query string needs an "=") echo "<a href='icerik.php?icerik={$goster['icerik_id']}'>{$goster['baslik']}</a>";
    2 points
  5. I was in my fifties when I first came across something called HTML. I knew Basic from from my days with a BBC home microcomputer so I started using Visual Basic to create web pages. Daily, I would log in to the Compuserve Bulletin Board using my dial-up modem to exchange ideas (much like now - plus ca change, plus ca meme). I started to write Java applets to enhance my pages but, no sooner had I started to become reasonably proficient, the world switched to Flash (which has since died a death). Disheartened, I let the Java lapse. One of the biggest mistakes I've made as today's phone apps are essentially Java applets. A year or so later I came across PHP and much prefered its Java/C type syntax to Basic. My preference was cemented when I discovered that rewriting my VB/ASP scripts in PHP gave me a 3x+ speed increase (in one case a 70x increase in performance as VB was crap at handling long string concatenations). Anyway, the moral is "You ain't too old".
    2 points
  6. While PHPStorm is subscription based, it's pretty good in my opinion and for an IDE it has helped my PHP skills a lot. It makes suggestions on how to write the code in a better way that I would never have thought of and makes syntax errors easy to resolve. I am not affiliated with JetBrains as I just like using their developer tools as it simplifies my coding a lot.
    2 points
  7. You might have more success with function toggleResponseArea() { if (document.getElementById("commentResponse").style.display == 'block') { document.getElementById("commentResponse").style.display = 'none'; } else { document.getElementById("commentResponse").style.display = 'block'; } } Or, easier still $("#reply").click( function() { $("#commentResponse").toggle() })
    1 point
  8. Margins are more complicated than simply giving you spacing from the edge some nearby element. Like they'll merge and collapse with other margins. And margins can extend outside what you think the bounding box of the element is. The comment-action's margin does not push it away from the bottom of the parent div because there was nothing to push against. That bottom edge isn't a hard edge. Think of margins as a way of spacing from other unrelated elements while padding is for spacing from other related elements; use a margin with a div + div but use padding with a div > div. Of course it's not actually that simple, but it's a start.
    1 point
  9. You're way overthinking this. Forget positioning. Let the element render where it would normally because that's where you want it. Then simply align its contents right. https://jsfiddle.net/fk9n1pbz/
    1 point
  10. So unfortunately there's three different "roots". Which one someone means depends on context. 1. When it comes to files and directories in Linux, / is the root. Not "home" - that's where your personal files are, and is typically /home/something. 2. When it comes to figuring out where stuff is when you're dealing with PHP code, the "root" means the place where your web server starts holding files. That would be /opt/lampp/htdocs. 3a*. When it comes to URLs and other things you see when you're browsing a website, the root is also / according to what's in your browser's address bar. Not including the http(s) or domain name but the first slash right after. The second and third are closely related: the root of where your web server is hosting files is /opt/lampp/htdocs and that is the same as / in the address bar. Unless you tell your server differently, if you go to http://localhost/MyProject/uploads/whatever.ext then the web server is going to look for the web root (/opt/lampp/htdocs) + the path portion of the URL (/MyProject/uploads/whatever.ext) and try to find a file named /opt/lampp/htdocs/MyProject/uploads/whatever.ext. What ginerjm is talking about is the second one, and whose value you can get in PHP with $_SERVER["DOCUMENT_ROOT"]. You do not set that value yourself. PHP gives it to you for free. If you want to take a file upload and always place it in the root of your web site + /MyProject/uploads/ then you need the DOCUMENT_ROOT plus that path part (and probably plus a file name itself). $fileDestination = $_SERVER["DOCUMENT_ROOT"] . "/MyProject/uploads/" . $fileNameNew; Now here you've got a slight problem: that /MyProject piece. That's not going to be there in the real site, but you have it in your setup. You have two basic choices for how to deal with that: 1. Tell your web server to host files out of MyProject. That requires going into the server configuration and changing some values. There's a right way and a wrong way of doing this, so rather than deal with that, just ignore this option. 2. Put all your MyProject files into the htdocs directory. This is really easy. The downside is that you can't have multiple websites anymore because http://localhost is always going to be what's in /opt/lampp/htdocs and that's always going to be the "MyProject" stuff. Once you've moved the files you can get rid of the "MyProject" stuff in your code and your local site will be one step closer to working like the real site will. $fileDestination = $_SERVER["DOCUMENT_ROOT"] . "/uploads/" . $fileNameNew; * There's a 3b option where you might say "well no, I consider the root of my site to be http://localhost/MyProject". Saying things like that is an easy way to get everybody confused so stick with 1, 2, and 3a.
    1 point
  11. Your script is probably getting stuck here: $dataOut = fgets($f); It's waiting for data from your serial device but the device isn't sending any data so the script just hangs there waiting indefinitely. You'll have to add some debug logging or something to figure out why or if that's actually the case. You could also try implementing non-blocking IO and a timeout.
    1 point
  12. I see that you're using the parseInt function. What does it do?
    1 point
  13. You're asking if someone could create their own website under *.basemaps.cartocdn.com.
    1 point
  14. Yes it was that simple. To keep your function cleaner I'd add the id value as an argument of the function as well function ($id, &$mail, &$rank)
    1 point
  15. You've posted a few pieces of code without any context to how they are used. That makes it really difficult for anyone but you to know what you're talking about. If clickedD.php is where the AJAX request with the dentist's name is sending its data then only clickedD.php has the dentist's name available to use. The AJAX happens after the page loads, so PHP cannot time travel and take the information from it and retroactively change what happened when it was first creating the page. Without knowing more about what you're doing, I would say that you "have to" use clickedD.php and AJAX to modify the page with whatever information you want - information which would have to be returned by clickedD.php itself. But I suspect there's an easier method to do what you want. No way for me to know what it is, but I do believe there is one.
    1 point
  16. 1. The second argument to add_filter() is the name of a function WP should call when it wants to use whatever filter. The name of your function is "new_mail_from_name" and not "alphaequipment". 2. get_option() will want the name of the option it should get. An option name would be like "blogname". You very likely do not have an option named "alphaequipment.com". Have you tried using that add_filter + function code without making any changes to it?
    1 point
  17. I personally don't use bootstrap, but I'm assuming it has grids? Anyways, I use grids and HTML for a two column format. A third column would be easy as well using CSS grids. Here's the two column form using grids: <main class="content"> <div class="container"> <?php foreach ($cms as $record) { ?> <article class="cms"> <img class="article_image" src="<?= htmlspecialchars($record['image_path']) ?>" <?= getimagesize($record['image_path'])[3] ?> alt="article image"> <h2><?= $record['heading'] ?></h2> <span class="author_style">Created by <?= $record['author'] ?> on <time datetime="<?= htmlspecialchars(CMS::styleTime($record['date_added'])) ?>"><?= htmlspecialchars(CMS::styleDate($record['date_added'])) ?></time> </span> <p><?= nl2br($record['content']) ?></p> </article> <?php } ?> </div> </main> Here's a small section of the CSS: /* Approximately the size of a 1248px large display monitor */ @supports (grid-area: auto) { @media screen and (min-width: 78em) { .site { display: grid; grid-template-columns: 1fr minmax(23.4em, 54.6em); grid-template-areas: "header header" "nav nav" "main main" "sidebar sidebar" "footer footer"; justify-content: center; width: 75em; margin: 0 auto; } .masthead { grid-area: header; background-image: url(../images/img-header-001pg.jpg); background-repeat: no-repeat; } .checkStyle { grid-area: main; font-size: 1.2em; } .sidebar { grid-area: sidebar; justify-content: center; } } // End of Screen Size } // End of Last Grid Area Using grids cuts down on the CSS as well as the HTML, plus CSS really should be in a separate file and not inline. I'm assuming it's your CSS, but I'm sure you can have CSS from bootstrap that is an external fire as well that you can change?
    1 point
  18. If someone decides to be funny and set $_GET['page'] to "-42" you don't end up with messed up calculations. Using max, any number <= 0 will get ignored and $page will get set to 1 instead. If you calculate your total page count you should do a min($totalPageCount, $page) as well so that $page doesn't get set to something larger than $totalPageCount.
    1 point
  19. They are local to the function. Pass them or make them global
    1 point
  20. But - do not save it in a table. Have a folder for these and save the filename in the customer's records but save the pdf as its own file.
    1 point
  21. For future reference, rather changing the value of display directly like that, it's easier to just add/remove a class which will apply display: none; Doing it that way, you don't have to worry about whether it should be 'block', 'inline', 'table-cell', 'grid', etc. You just apply display: none; with a class to hide it, then remove the class so display: none; gets removed and it falls back to whatever the previous value was.
    1 point
  22. Instead of changing the display to "block" when you click the button, set it to "display: table-cell;" <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> function showDetails(cnt) { $(".more").css("display", "none"); // hide all var details = "details"+cnt; var x = document.getElementById(details); if (x.style.display === "none") { x.style.display = "table-cell"; // display requested one } else { x.style.display = "none"; } } </script>
    1 point
  23. That line in your onchange function concerns me. If it was generated when PHP was executing. how does it relate to the id of the product the user is clicking in the browser?
    1 point
  24. I am not suggesting you go to a Framework although they are structured the way I mentioned. Check out this free Laracast video series on PHP. It is the only video tutorial I have seen that I would recommend to anyone. It will get you going in the right direction. Watch each one even if you understand it already. The PHP Practitioner https://laracasts.com/series/php-for-beginners
    1 point
  25. This is a common area of confusion. Anything having to do with php and files (include/require/fopen, etc) wants file system paths. (OS Filesystem) Anything having to do with web resources (images, css, javascript) wants a url. Urls only exist in webspace. (Webspace/HTTP 2.0 Serving). As the front controller is now a popular design pattern for web apps and frameworks, you will come to find that it is frequently the case, that the only PHP script that would be under the webroot, would be the front controller script. All requests are thus, routed through the front controller, using a router. All the classes and other php scripts will be in directories that are not visible in any way from webspace. This is far superior in numerous ways, than a system that has entry points from scripts that have been mapped into webspace. I only bring this up because if you think about it for a minute, it should reinforce your understanding that PHP's functions require a filesystem path and not a url. PHP can load scripts in any directory on your file server that the PHP process has operating system level access to. Things that are not related to php code, as mentioned above, that in general are referenced in your html markup, are things in webspace. Each can be accessed via a url. Both webspace/url's and filesystems can have relative paths, so this can lead to confusion. A relative filesystem path is typically relative to the "current working directory" of the process that is running. This can easily get confusing when you are executing scripts that one or 2 levels deep in a hierarchy. For this reason, some technique which establishes the filesystem project root is helpful. That could be the document root, or as is more common these days, a variable or constant established through a bootloader or init script that references either the __FILE__ or __DIR__ magic constants. Using this technique is equivalent to, from a file system perspective, establishing something like the document root for your php code. At that point you can have simple helper functions that can concat project relative paths to it, to always have a fully qualified filesystem path. As an example, here is a simplified version of a directory path you will find using one of a number of the more popular PHP frameworks. var/ ├─ www/ │ ├─ my_website/ │ │ ├─ config/ │ │ │ ├─ init.php │ │ ├─ public/ │ │ │ ├─ css/ │ │ │ │ ├─ style.css │ │ │ ├─ images/ │ │ │ ├─ js/ │ │ │ ├─ index.php │ │ ├─ src/ │ │ │ ├─ pageA.php │ │ │ ├─ pageB.php │ │ ├─ vendor/ In this case, the webroot of the site will be mapped to the filesystem /var/www/my_website/public So the css file in markup can be referenced as: https://www.mywebsite.com/css/style.css. However, in your markup it would be completely safe and reasonable to reference it with the relative path "/css/style.css" What about file system paths for a PHP require of pageA.php? Keep in mind, that only the public directory is visible to webspace. there is no way to reach any file using a url in the src or vendor directories. Let's assume that at some point in the .../public/index.php there is code that is trying to require_once("pageA.php") You could attempt to use relative paths, based on the knowledge of where the public directory exists relative to the src directory, but this can get very convoluted once you have more complicated file system trees. It would be convenient to always use the relative path of the src script. In the case it would be simply "/src/pageA.php". A solution in index.php could be a function that always returns the path to the project directory (my_website). That would work great in index.php as a front controller, because every request goes through it, so if that variable gets initialized it can be safely used in all includes. In your case, you don't have a front controller, so this isn't as helpful. There is however, a common pattern that has been used to do this, and that is to make sure that any executing script (script that can be directly referenced in webspace) requires a config, bootstrap or setup script in the root of your project. This isn't perfect, because the filesystem path to this script will vary depending on the directory structure you have, but at worst you need a relative file system path to it. Let's assume in this example this would be .../config/init.php In init.php you have this variable defined: <?php $PROJECT_ROOT = substr(@realpath(dirname(__FILE__)),0, -1 * strlen('/config')); // The only hardwired fact here, is that the init.php script is in the /config directory. We need to strip that off the path to get back to the root. //If it was further nested from the project root, the '/config' constant would need to be changed accordingly to where it exists. //Keep in mind there would only be one of these files in the project, and typically it might also have other global configuration variables like database credentials. So long as you include the .../config/init.php script, you will be able to use the $PROJECT_ROOT, and append your relative file system paths to it to include or reference other scripts. All you need to know is the location of those scripts relative to your project (my_website). So in index.php, code like this could be used to reliably reference pageA for inclusion, simply knowing that relative to the project, it exists in the src directory. Furthermore pageA.php could reference pageB.php reliably. // In public/index.php require_once("../config/init.php"); // Sometime later, we need pageA.php require_once($PROJECT_ROOT . '/src/pageA.php'); // In pageA.php, pageA.php needs pageB.php require_once($PROJECT_ROOT . '/src/pageB.php'); Since in your case, again you don't have a front controller, you just need to make sure that any scripts that get directly executed by the web server via a url, include the "config/init.php" script in relative fashion. You probably already have a configuration script like this in your project, that everything must include, and if so, that would be a good candidate for adding the $PROJECT_ROOT to. Hope this helps. As most people are now using composer, with component libraries, and class autoloading using PSR-0 or PSR-4 standards with classes and namespaces, this already solves a lot of file inclusion problems for a project, and the more you can move your project towards an MVC pattern, the easier it will be to extend, enhance and test. If you don't understand composer, namespaces, autoloading etc., these would be excellent growth areas for you, allowing you to evolve your project towards something more sophisticated and professional.
    1 point
  26. File paths and URLs are not always the same thing. Look at your browser's address bar right now: does it say? https://forums.phpfreaks.com/var/www/forums.phpfreaks.com/index.php?controller=idontknow&action=something&whateverelse&id=313889&name=altering-percieved-resource-path If your $root is also the root of the website then there's a really easy way to get an absolute path: start with a slash. That's it. / in the URL will correspond to the $root. <link rel="stylesheet" type="text/css" href="/css/actors.css"> <link rel="stylesheet" type="text/css" href="/css/gallery.css">
    1 point
  27. Firstly, I doubt anyone is clicking a link from a first-time poster. Second, what you are doing, updating with parts of a column, is indicative of problems in the database design. What is the structure of those two tables and what does the data look like in the relevant columns?
    1 point
  28. You have a problem with file paths and somehow making one file appear to be in another place is the opposite of a solution. Consider that someday you, or maybe someone else, would look at that code and wonder how the hell it seems to be including the correct file when the file path is clearly wrong. 1. If you need to move the file then that sucks. Move the file and get it over with. IDEs can often help with rename operations, otherwise it's real simple to do a quick global search for "page.php" and update the paths you find; unless you have hundreds of files, that should take only a minute or two. 2. If you do have a lot of references to change then that hints at an underlying problem in how you use files for reusable code. Give it a few minutes of thought to see if maybe there is a better way of arranging your code or whatever so that it's accessible in a way that makes more sense. 3. Don't use relative paths. Use an absolute path based on the DOCUMENT_ROOT, as in include $_SERVER["DOCUMENT_ROOT"] . "/pages/page.php";
    1 point
  29. I have to agree with Requinix that PHPStorm is by far the choice of professional developers. It's an amazing editor in every way, and is the king of many other languages like Java. With that said, for web development in general, Visual Studio Code from Microsoft has really taken the web development world by storm, and with plugins is a very competitive PHP development environment. I do a lot of remote editting, and I still use Eclipse/PDT for many things, but I'm slowly making the transition to using VSC, and were it not that old habits and configurations die hard, I'd probably retire Eclipse and move to VSC 100% of the time.
    1 point
  30. When I first started coding in PHP there was a person on here (I can't remember his name) that helped me out a lot. I was hung up on securing my code and spent all night writing a script that I thought was "secure" then the next day I posted it here. He replied back to me and the first thing he wrote was to throw that script in the trash. He went on to say people who write security code work in teams and test them out before they are introduced to the wild (internet). There is nothing wrong with prepared statement and unless you are a large corporation the speed of prepared statements is fast enough. Prepared statements are as secure as they possibly can be and nothing is 100 percent secure. So I totally disagree on the use of prepared statement.
    1 point
  31. In my experience this really isn't the case, again due to caching. I'm sure you know as well, that the main area of result set optimization is index coverage. One other thing to know about MySQL with InnoDB is that the data is stored as a "clustered index". In other words, the data is stored in primary key order, and whenever you read a row where it was retrieved through the use of the primary key, there is no index read cost, and you get the data for the entire row. This also perhaps helps explain the value of the result set cache, as MySQL can return data from Server memory pages, and will use a number of techniques to optimize the use of cache, rather than reading from disk. There is some overhead in parsing the queries, but it's less of a concern in MySQL than in other db's. I might not have explained this clearly, but again, in MySQL, sprocs are not pre-compiled because someone used one at some point. They get compiled for each connection, when requested. After that, the sproc will be reusable in compiled form, for the life of the connection, but as I stated previously, in a PHP application, your connections will be either frequently closed, or closed on every connection. The details of that, go into how PHP is being run, but in either case, new connections and re-compilation of sprocs will be frequent with MySQL. The more you have, the more memory will be required to store the compiled sprocs, so if you have a lot of sprocs and a lot of connections, that memory could be significant, but if this is an intranet environment where you don't have a hugh query volume or lots of concurrent requests, it's probably not reason for concern either. There is one mechanism that might be of interest in regards to the compilation of sprocs, which is to use a persistent connection: <?php $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array( PDO::ATTR_PERSISTENT => true )); The PDO::ATTR_PERSISTENT => true setting will trigger, again depending on your web server configuration, a connection pool, if for example you are using php-fpm. As frequently as you can find information about it, you will also find people telling you not to use it, as it can cause issues like deadlocks, hung connections that lead to timeouts/500 errors in your application, etc, but again in an Intranet environment it might not be a problem. I have at times in my career made heavy use of sprocs, triggers and views, so I'm not predisposed not to use them, but in my substantial experience with using MySQL, it is rare that I've found they were needed. Typically, when I have used them, it was to insure some sort of programmatic locking/transaction that I wanted to be guaranteed. One example that comes to mind is an implementation of a homegrown sequence object with naming and business rules around the range boundaries of the sequence numbers. It's always good to remember things like triggers and sprocs often will cause serialization and reduce concurrency. The other thing about sprocs, is that you are only moving code around. And in the process of moving code to the db, you are adding complexity to your development environment, as you have to make your changes to the database, rather than in your frontend code, when coding/debugging. You aren't going to have less code.
    1 point
  32. @maviyazilim: This is the best way to handle your problem. Claiming you don't understand this code, so you can't use it, is not acceptable here. Perhaps if this was in some way complicated, you might have an argument, but this is some of the most simple and basic PHP syntax that exists, and has existed in the language since it was created. This is using "Interpolation", which is one of the features that has made PHP great to work with for web development. When using double quotes, PHP will look at the contents of a string for PHP variables, and replace those variables with their values at runtime. This code is elegant, easy to read, and far superior to the alternative of concatenating a bunch of pieces together in most situations. You should try and use it whenever you can. The link is to the PHP Manual. Look for "Complex (curly) Syntax". I will explain this to you with an example. You also need to understand PHP arrays, and in particular the way that PHP arrays can have strings as a key. Simple Interpolation: <?php $testString = 'scary ghost'; echo "She saw a $testString. It was green!" . PHP_EOL; //embed newline with \n echo "She saw a $testString. It was blue!\n"; Outputs: She saw a scary ghost. It was green! She saw a scary ghost. It was blue! Again this is one of the most basic things about PHP you should know! The $testString variable gets interpolated. In the 2nd example I use "\n" for the newline instead of the PHP_EOL constant. Interpolation of array variables is also a fundamental feature of PHP: <?php $fruit = array('apple', 'banana', 'orange', 'grape'); echo "I ate one $fruit[0] for breakfast, and one $fruit[3] for lunch\n"; Outputs: I ate one apple for breakfast, and one orange for lunch Of course PHP arrays can have programmer defined string constants for keys, and this causes a parsing problem for PHP: $name = array('first' => 'George', 'last' => 'Washington'); // Syntax error echo "The first US President was $name['first'] $name['last']\n"; The problem here is that using "$name['first']" confuses PHP, when it sees the "$var['something']" and breaks the PHP string parser. So, PHP Helpfully allows you to put curly brackets around the array, telling php to resolve the value of the array, and then interpolate it as it would with any simple variable. // Interpolating an array with a string constant key $name = array('first' => 'George', 'last' => 'Washington'); // Using complex syntax echo "The first US President was {$name['first']} {$name['last']}\n"; Output: The first US President was George Washington As in Barand's example to you, this is very useful when you are trying to create html markup. This shows concatenation, which is more complicated, and harder to see minor problems you might have, vs using interpolation, where it is very clear what the markup is that you're creating, as well as the places where variables are being injected into the string. In both cases, the output is the same html: $linkData = array('url' =>'http://www.phpfreaks.com', 'name' => 'phpFreaks'); $linkConcatenate = '<a href="' . $linkData['url'] . "'>" . $linkData['name'] . '</a>' . PHP_EOL; $linkInterpolate = "<a href='{$linkData['url']}'>{$linkData['name']}</a>\n"; echo "PHP questions answered at $linkConcatenate <br>\n"; echo "PHP questions answered at $linkInterpolate <br>\n"; Output: PHP questions answered at <a href="http://www.phpfreaks.com'>phpFreaks</a> <br> PHP questions answered at <a href='http://www.phpfreaks.com'>phpFreaks</a> <br> Yet there is more: because this also works with Object variables and methods: class Person { private $name; private $age; private $title; public $summary; public function __construct($name, $title, $age) { $this->name = $name; $this->age = $age; $this->title = $title; $this->summary = $this->__tostring(); } public function __tostring() { return "Name: {$this->name}. Age: {$this->age}. Title: {$this->title}"; } public function getName() { return $this->name; } public function getAge() { return $this->age; } } $bob = new Person('Bob Smith', 'Manager', 31); $sue = new Person('Sue Jones', 'Director', 28); echo "Bob's Summary| {$bob->summary}\n"; echo "Sue's Summary| {$sue->summary}\n"; echo " <table> <tr><th>Employee</th></tr> <tr><td>$bob</td></tr> <tr><td>$sue</td></tr> </table>"; $employees[] = $bob; $employees[] = $sue; echo "\n\n\n"; foreach ($employees as $employee) { echo "{$employee->getName()} is {$employee->getAge()} years old\n"; } Outputs: Bob's Summary| Name: Bob Smith. Age: 31. Title: Manager Sue's Summary| Name: Sue Jones. Age: 28. Title: Director <table> <tr><th>Employee</th></tr> <tr><td>Name: Bob Smith. Age: 31. Title: Manager</td></tr> <tr><td>Name: Sue Jones. Age: 28. Title: Director</td></tr> </table> Bob Smith is 31 years old Sue Jones is 28 years old Interpolation is one of the best things about PHP. I hope you take the time to learn more about how it works. You can play with all the examples I provided here if you would like to experiment: https://3v4l.org/7jUPS
    1 point
  33. Remember, people are not there to see what is actually happening or what you are doing. The solution that you get that works might be something that you don't understand, but a person who helped you who put his or her time in should at least be thanked. At least you acknowledge and thanked that in the last post that you made. I once had someone help me with a PHP script that I didn't understand and even to this day still don't after deciphering it, but it worked and there wasn't another solution out there. So I used it anyways as I spent too much time on the particular part of the script. There are a lot of times I don't understand what something does, but only to have a light-bulb go on in my head months or even years later. Object-oriented programming is something that I could do, but really never understood the meat & potatoes of it until now. It's starting to make a lot of sense now and to me that is what is fun with it comes to coding.
    1 point
  34. You haven't seen code written like that which is perfectly normal, so "you can't use it"? What kind of nonsense is that?
    1 point
  35. Get a decent editor! Four errors found... Unwanted single quote Mispelled and unwanted "</label>" Mispelled and unwanted "</label>" Missing "a" at start of "<a .... "
    1 point
  36. The basics of AJAX are simple. You send a request to be processed on the server and it sends back a response. When responding to an AJAX request, anything output by the server program (stuff that would normally go to the browser screen) is sent back as the response. Here's a simple example (using data from the DB in my tutorial) which accepts a teacher_id, sends it in a request, and recieves back the data for that teacher thne displays it. <?php require 'db_inc.php'; $db = pdoConnect('jointute'); // my cuton connection function - use your connection code //******************** PROCESS AJAX REQUESTS ********************* // // if (isset($_GET['ajax'])) { if ($_GET['ajax']=='teacher') { exit(json_encode(getTeacher($db, $_GET['tid']))); } else { exit('INVALID'); } } // // Functions // function getTeacher($db, $id) { $res = $db->prepare("SELECT t.fname , t.lname , d.deptname as dept FROM teacher t JOIN department d USING (dept_id) WHERE teacherid = ? "); $res->execute([ $_GET['tid'] ]); $row = $res->fetch(); if ($row) { return $row; } else return ['fname'=>'NOT FOUND', 'lname'=>'', 'dept'=>''] ; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Example</title> <meta charset='utf-8'> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript'> $().ready( function() { $("#find").click( function() { var tid = $("#tid").val() $.get( "", // specify processing file on server (in this case it's same file) {"ajax":"teacher", "tid":tid}, // data to send in request function(resp) { // handle the response $.each(resp, function(k,v) { $("#"+k).val(v) }) }, "JSON" // response type ) }) }) </script> <style type='text/css'> body { font-family: calibri, sans-serif; font-size: 12pt; } div { margin: 16px; padding: 8px; border: 1px solid gray; } label { display: inline-block; background-color: black; color: white; width: 120px; padding: 8px; margin: 1px 8px;; } </style> </head> <body> <div> <label>Teacher ID (1-20)</label> <input type='number' id='tid' value='0'> <button id='find'>Find</button> </div> <div> <label>First name</label><input type='text' id='fname' value='' readonly><br> <label>Last name</label><input type='text' id='lname' value='' readonly><br> <label>Department</label><input type='text' id='dept' value='' readonly> </div> </body> </html>
    1 point
  37. Now it returns 10 again function ec($n, array $a, array $b) { return $n * $b[1] - $b[0] * $a[0] * $a[1] ; } echo ec( 4, [1,3], [2,4]); // 10 If you post this topic again you will be banned.
    1 point
  38. When it comes to SQL injection, stored procedures and prepared statements both do the same thing - they separate the data values fron the query statement. The mechanisms are slightly different, however. With prepared statements, placeholders are used instead of the data, and the values are passed at execution time. With stored procedured, the values are passed as input parameters when the procedure is called. Using both is a "belt and braces (sorry, suspenders)" approach. The advantage of a sproc is it is pre-written and stored (clue is in the name) waiting to be called so there is no overhead of sending the query statement - you just send the data. If you use "dynamic sprocs" you throw away this advantage. To me the idea of a "dynamic sproc" is oxymoronic, like military intelligence, internet privacy, common sense.
    1 point
  39. Wife is from Dublin -- have always enjoyed visiting. Brother in law spent a few years in Australia -- sorry we didn't visit them when they were there. Best of luck with the business idea!
    1 point
  40. Despite requests, you refused to show any code that output the query results. On top of that you used "SELECT * " which gives us no information whatsoever about the columns you are selecting. As I told you, I created a test "icerik" table. This had columns "icerik_id" and "name" - which is why I output a column called "name". You need to use your column names, whatever they are.
    1 point
  41. Greetings 🙂 This is a story up again. I think i have heard it before. Earning money, say good bye to all, and moving to the south or Asia (Australia is in oceania). First i moved to Hua Hin in Thailand, got married, divorced, moved to Torrevieja in Spain and then.... now i travel between Norway and Torrevieja while i am planing and opening a new page for making my new history for the future. I do not yet know what those plans are based on, or... i know what they are based on, but i dont know what the plans will be 👍 Soooo, what they will be when a finished result is in front of me. I dont have a clue. I just know that something is growing. I have studied what is applicable today within standards in development and programming. I feel as "lost and helpless" as almost a year ago when I resumed programming and development. It is not easy to get acquainted with the new when you have to learn the old that is basic again. Believe me, I've been trying for almost a year. Old age weighs, and age that is the one who should be so light and bear. I will never be the same 😞 Good luck mate 🙂
    1 point
  42. 😆 Physical printed books are out of date by the time they get published (coughphpsix). Use online resources as much as you can.
    1 point
  43. I don't know. There's no sign of anything boolean. Did you get the same error messages?
    1 point
  44. There's a lot here that can be involved so you'll need to do some learning on your own. The main things to learn about are: the <video> element and the basics about how HTML and CSS work together. Can you create a page that has just the video in it and playable?
    1 point
  45. You will probably need something like this. But will need to work out the actual outline of the Frame to make it look like a TV: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_responsive_iframe_169
    1 point
  46. It's not exactly easy to tell what it is you're describing, but I think the general term you're looking for is "front controller": where most/all code doesn't start off by executing individual .php files but instead everything goes through one file (typically index.php) which then has some amount of logic to determine what code should be running. That process can start with URL rewriting (telling the web server that everything should go through index.php) or simply using specially-crafted URLs (such as query strings like /my_directory/?stuff or PATH_INFOs like /index.php/stuff); the former is the modern approach.
    1 point
  47. These are the results I get (wordlist contains 351,100 records) $t1 = microtime(1); $res = $db->query("SELECT word FROM wordlist WHERE MATCH (word) AGAINST ('sang*' IN BOOLEAN MODE)"); $t2 = microtime(1); printf('Query 1 : %0.4f seconds<br>', $t2 - $t1); $t1 = microtime(1); $res = $db->query("SELECT word FROM wordlist WHERE word LIKE 'sang%'"); $t2 = microtime(1); printf('Query 2 : %0.4f seconds<br>', $t2 - $t1); results (74 words found) Query 1 : 0.0026 seconds Query 2 : 0.0005 seconds
    1 point
  48. doing it like that means that $params is required. The way I did it means that $params can be there or not
    1 point
This leaderboard is set to New York/GMT-04:00
×
×
  • 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.