Jump to content


Popular Content

Showing content with the highest reputation since 03/04/2013 in all areas

  1. 3 points
    A few notes about text bounding boxes which, I hope, will help in precise placement of your text. Suppose I have the text string "The lazy fox" which I want to display using 150pt Vivaldi . My image is 4896 x 3672 and I want the text placed at the bottom right but 250 pixels from the edges of the image. $box = imagettfbbox(150,0,'c:/windows/fonts/vivaldii.ttf','The lazy fox'); gives this array of coordinates of the four corners $box = Array ( [0] => 23 [1] => 55 [2] => 871 [3] => 55 [4] => 871 [5] => -140 [6] => 23 [7] => -140 ) You may wonder why it can't just give a rectangle from (0,0) to (width, height) to make sizing simple, but there is extra information to be extracted from the array Text width = (871 - 23) = 848 Text height = 55 - (-140) = 195 The baseline will be 140px from the top The text is offset 23 px to the right. My text, therefore, will be in a rectangle 848 x 195 positioned 250 px from right and bottom edges. The top left x coord of the rectangle will be (4896 - 250 - 848) = 3798 and top left y coord will be (3672 - 250 - 195) = 3227. However, to land the text precisely into this area we position it on the baseline and at the required x offset, ie (3798 - 23 , 3227 + 140) = (3775, 3367). I use a simple custom function to assist with this process function metrics($font, $fsize, $str) { $box = imagettfbbox($fsize, 0, $font, $str); $ht = abs($box[5] - $box[1]); $wd = abs($box[4] - $box[0]); $base = -$box[5]; $tx = -$box[0]; return [ 'width' => $wd, 'height' => $ht, 'ascent' => $base, 'offsetx' => $tx ]; } $box = metrics ('c:/windows/fonts/vivaldii.ttf', 150, 'The lazy fox'); $box = Array ( [width] => 848 [height] => 195 [ascent] => 140 [offsetx] => -23 )
  2. 3 points
    Don't use $GLOBALS. Forget it exists. There is never a good reason to use it. Pretend you never saw it.
  3. 3 points
    +----------------+ +----------------+ | Make sure to |---+ +------->| (e.g. Courier) | +----------------+ | | +----------------+ | | | | +----------+ | | +->| use a |---+ | | +----------------+ +----------+ | | +------->| and use spaces | | | +----------------+ | +----------------+ | | +--->| monospace font |-----+ | +----------------+ | +----------+ | | not tabs |<----------+ +----------+ | +--------------------------------------------------------------------------+ | V +---------------+ | It also helps | +---------------+ | | | +-------------------+ +-------------------+ +------------------------>| if you sometimes |---------------------->| switch between | +-------------------+ +-------------------+ | | +-----------------+-----------------+ | | | | +-------------------+ +-------------------+ | overtype | | insert | +-------------------+ +-------------------+ | | | | | +----------+ | +----------=>| modes |<----------+ +----------+
  4. 3 points
    The code in each switch is identical so all it achieves is to ensure the calculation uses only the defined list of diameter options. Just use an array of the valid values to verify the values. You can use the same array to generate the option list <?php $diam_vals = [2,3,4,6,8,10,12,14,16,18,20,22,24,26]; $results = ''; if ($_SERVER['REQUEST_METHOD']=='POST') { $x = $_POST['x'] ?? 0; $y = $_POST['y'] ?? 0; $diametre = $_POST['diametre'] ?? 0; if ($x > 0 && $y > 0 && in_array($diametre, $diam_vals)) { $rayon = $diametre * 38.1; $dc = $x/2; $ad = ($y/2)-$rayon; $ac = sqrt(pow($ad,2) + pow($dc,2)); $ec = sqrt(pow($ac,2) - pow($rayon,2)); $LongueurBayonette = $ec*2; $alpha = asin($dc/$ac); $alpha = $alpha*180/M_PI; $beta = acos($rayon/$ac); $beta = $beta*180/M_PI; $angle = 180-$alpha-$beta; $results .= "X = " . $x . "mm" . "<br/>"; $results .= "Y = " . $y . "mm" . "<br/>"; $results .= "Longueur = " . number_format($LongueurBayonette,1) . " mm" . "<br/>"; $results .= "&beta; = " . number_format($angle,1) . "°" . "<br/>"; $results .= "Rayon = " . $rayon . " mm" . "<br/>"; $results .= "&phi; = " . $diametre . '"' . "<br/>"; } else { $results = 'Inputs are not valid'; } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Simplified Example</title> </head> <body> <form method="post" action=""> <fieldset> X: <input type="text" name="x" value="" /> <br/> Y: <input type="text" name="y" value="" /> <br/> Diametre: <select name="diametre"> <option value="0"> </option> <?php foreach ($diam_vals as $d) { echo "<option value='$d'>$d</option>\n" ; } ?> </select> <input type="submit" value = "Calculer" /> </fieldset> </form> <br> <?=$results?> Just curious - do you have a diagram of how those values relate to one another. It metions "rayon" and "bayonnette" so my guess is that it is some kind of laser rifle with attached bayonet (but I could be wrong) 😊
  5. 3 points
    I have to agree - do a single query to get the events for the month. I would set up a calendar array of the days in the month (structure: $calendar[wk][wkday][events] ) Loop through the query results and drop the events into their respective week/day slots Loop throught the array to output the calendar DATA TABLE: event +----+----------+---------------------+ | id | name | date_time | +----+----------+---------------------+ | 1 | Event 1 | 2018-11-01 15:00:00 | | 2 | Event 2 | 2018-11-02 12:00:00 | | 3 | Event 3 | 2018-11-11 14:00:00 | | 4 | Event 4 | 2018-11-14 11:00:00 | | 5 | Event 5 | 2018-11-15 14:00:00 | | 6 | Event 6 | 2018-11-16 15:00:00 | | 7 | Event 7 | 2018-11-19 15:00:00 | | 8 | Event 8 | 2018-11-20 16:00:00 | | 9 | Event 9 | 2018-11-23 14:00:00 | | 10 | Event 10 | 2018-11-30 10:00:00 | | 11 | Event 3A | 2018-11-11 16:00:00 | +----+----------+---------------------+ CODE <?php include('db_inc.php'); $db = pdoConnect("test"); // connect to "test" database $curmonth = date('F Y'); // // set up the date range required // $dt1 = new DateTime("first day of this month"); $dt2 = clone $dt1; $dt2->add(new DateInterval('P1M')); $dint = new DateInterval('P1D'); $dper = new DatePeriod($dt1, $dint, $dt2); // // create an array calendar[wk][wkday][events] to store events then output // $calendar = []; foreach ($dper as $d) { $wk = $d->format("W"); $calendar[$wk] = array_fill_keys(range(0,6), []); } // // get the event data for current month // $stmt = $db->query("SELECT id , DATE_FORMAT(date_time, '%D') as day , WEEK(date_time, 1) as wkno , WEEKDAY(date_time) as wkday , DATE_FORMAT(date_time, '%k:%i') as time , name FROM event WHERE YEAR(date_time) = YEAR(CURDATE()) AND MONTH(date_time) = MONTH(CURDATE()) ORDER BY wkno, wkday, time "); // // loop through results and drop events into the array // foreach ($stmt as $ev) { $calendar[$ev['wkno']][$ev['wkday']][] = [ 'day' => $ev['day'], 'time' => $ev['time'], 'name' => $ev['name'] ]; } // // output the array // $tdata = ''; foreach ($calendar as $wk => $wdata) { $tdata .= '<tr>'; foreach ($wdata as $dno => $events) { $cls = $dno > 4 ? "class='we'":""; $tdata .= "<td $cls>"; foreach ($events as $ev) { $tdata .= "{$ev['day']} {$ev['time']} {$ev['name']}<br>"; } $tdata .= "</td>\n"; } $tdata .= "</tr>\n"; } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)"> <meta name="creation-date" content="11/06/2018"> <title>Sample Calendar</title> <style> table { border-collapse: collapse; font-family: verdana, sans-serif; font-size: 10pt; } th { background-color: #369; color: white; padding: 5px; width: 14%; } th.we { background-color: #358; } td { background-color: #FFE; padding: 5px; } td.we { background-color: #FFC; } </style> </head> <body> <h3>Calendar <?=$curmonth?></h3> <table border='1'> <thead> <tr><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th class='we'>Sat</th><th class='we'>Sun</th></tr> </thead> <tbody> <?=$tdata?> </tbody> </table> </body> </html> OUTPUT
  6. 3 points
    I can't imagine a scenario where the gobbledy-gook of a system you apparently are trying to create would be justified, or possible within your demonstrated engineering capabilities. You are talking about trying to create a system that requires a user to only use one workstation and browser to access your system. I don't know what your system would be doing, but it better be providing literally life saving services, because short of that, nobody is going to put up with the restrictions you have in mind. They are anti-user, and when you make things difficult for users, they stop using your system, or never even stay long enough to pass the entry point. It is damn difficult to get anyone to sign up to use legitimately valuable services, which is why you see so many systems that integrate with facebook, google and twitter, so that you can create your account and trust authentication from those systems to allow access. Furthermore some of your plans reflect an apparent lack of understanding of Internet basics like NAT. In your system, if we were to follow along with your plans, for a large company with perhaps 1000 employees at a particular site, you plan to only allow 1 employee there to use your system. Ditto universities, or even an average household: "Hey there roommate, I just made an account at this site, you should too!" "WTF, the system says I'm banned!" Since you are focused on investigating a client IP, I will say this about IP addresses -- they are reliable at least to the degree that they reflect the tcp socket connection from the client to the server. That information bubbles up to PHP from the IP layer, to the server, and finally to PHP's $_SERVER superglob. The problem is, that a client could have bounced through a variety of gateways, proxy servers or VPN prior to the point that you are finally connected. In many sophisticated hosting environments there are things like load balancers or reverse proxy servers that sit between the client connection and the server which interfere with $_SERVER['REMOTE_ADDR']. Rather than see the client IP, you instead see the IP of the proxy server. If you have that sort of environment, then you can examine $_SERVER['X-Forwarded-For'] or $_SERVER['HTTP_X_FORWARDED_FOR'] variables. These may be arrays with a series of addresses. Again you have the issue that these are provided by the "client" so if it is a proxy server you can depend on at least the most recent address to have been the one that made the TCP socket connection to YOUR proxy server. Other legitimate proxy servers will provide the same data. However, someone who is taking steps to hide their origin is not going to be prevented from obscuring their IP and there is absolutely nothing you can do about it. Almost everyone uses NAT in some form, so the actual person IP address of a workstation on a network is never going to be visible (and would also be useless if it was, since these will be non-routable IP addresses that are shared by hundreds of millions of users). Solutions to the issue of certification and authentication, when people have real and legitimate reasons to solve them, involve cryptography. What you are trying to do can be accomplished using X.509 certificates which have support built into browsers. In a nutshell, at account creation time you would generate an client certificate for that user, installing that into your server, and then providing the signed cert back to them in a specific header (application/x-x509-user-cert ). This will cause the browser to prompt the user to install the cert into their browser. If they accept you know have a reliable way of identifying a specific user. At that point, whenever they connect (must be under SSL) you'll be able to authenticate them back to your system via that particular certificate. Those without a client certificate will be unable to connect. You can think of this as white listing. It is highly effective but is typically used only in environments where the system knows in advance who their allowed users are. Trying to use it in a public facing website with an unknown user base is something you just don't see because the benefits of trying to do this far outweigh the tolerance that people have for a system that has that degree of odious overhead and invasion of their privacy. In conclusion: The types of things you are obsessed with are all edge case items. No quality system begins with the premise that the #1 goal is to try and catch and outsmart an imaginary horde of people attacking your site for reasons unknown. This started as a specific thread about the contents of $_SERVER variables and then escalated into fairly delusional territory, with a dash of your personal Devshed drama thrown in. And let's just be clear about one thing: If you ever bring up your personal issues regarding your Devshed access again, which are irrelevant to this community, then your access to this community will end as well. It's off topic, it's a waste of people's time and efforts here, and it's rude. I just want to be clear that I won't tolerate it again.
  7. 2 points
    the convention around here is "New question, new thread". That allows for short, direct answer to short, direct questions instead of long, rambling threads where all the "Goodness" gets lost. Some comments on the above: the use of "global" breaks encapsulation, requiring the environment "outside" the function to provide the variable. It is better to pass the data as an argument to the function. What value does admin['gender'] have? Any value passed that resolves to true will cause the ternary operator to return "Mr" and everything else will return "Mrs". The code makes no attempt to ensure that the array indexes used actually exist; this may or may not be an issue. What if the individual is female and not married? They might object to being called "Mrs". What if the individual is not gender-identifying? They would object most strongly to be referred to by either of the terms used here. Marital status and/or gender are both Personal Data and should be stored in the User's "record" (whatever form that takes) so that it can be managed by/on behalf of the User and changed over time. Regards, Phill W.
  8. 2 points
    Alternative model which allows multiple siblings jdev_nroll; jdev_sibling; +----+--------+---------+-------+-----------+------------+ +------------+----------+ | id | sname | ctclass | shift | ctstudent | dob | | sibling_id | elder_id | +----+--------+---------+-------+-----------+------------+ +------------+----------+ | 1 | Curly | 1 | 0 | N | 2007-01-20 | | 2 | 1 | | 2 | Larry | 1 | 0 | Y | 2010-12-21 | | 3 | 1 | | 3 | Mo | 1 | 0 | Y | 2011-02-22 | | 3 | 2 | | 4 | Peter | 1 | 0 | N | 2009-01-03 | | 4 | 5 | | 5 | Paul | 1 | 0 | N | 2006-12-21 | | 9 | 8 | | 6 | Mary | 1 | 0 | Y | 2010-09-20 | | 9 | 10 | | 7 | Jane | 1 | 0 | N | 2008-03-08 | | 10 | 8 | | 8 | John | 1 | 0 | N | 2006-10-04 | +------------+----------+ | 9 | George | 1 | 0 | Y | 2010-10-26 | | 10 | Ringo | 1 | 0 | Y | 2009-11-15 | +----+--------+---------+-------+-----------+------------+ SELECT a.id as sibling_id , a.sname as sibling_name , TIMESTAMPDIFF(YEAR,a.dob,curdate()) as sibling_age , a.ctclass as class , b.id as elder_id , b.sname as elder_name , TIMESTAMPDIFF(YEAR,b.dob,curdate()) as elder_age , b.ctstudent as elder_ctstudent FROM jdev_nroll a JOIN jdev_sibling s ON a.id = s.sibling_id JOIN jdev_nroll b ON s.elder_id = b.id WHERE a.ctstudent = 'Y' ORDER BY a.id +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+ | sibling_id | sibling_name | sibling_age | class | elder_id | elder_name | elder_age | elder_ctstudent | +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+ | 2 | Larry | 9 | 1 | 1 | Curly | 13 | N | | 3 | Mo | 8 | 1 | 1 | Curly | 13 | N | | 3 | Mo | 8 | 1 | 2 | Larry | 9 | Y | | 9 | George | 9 | 1 | 8 | John | 13 | N | | 9 | George | 9 | 1 | 10 | Ringo | 10 | Y | | 10 | Ringo | 10 | 1 | 8 | John | 13 | N | +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+
  9. 2 points
    For example, https://www.php.net/manual/en/datetime.createfromformat.php https://www.php.net/manual/en/datetime.format.php
  10. 2 points
    Christmas has come early! <?php const IMGDIR = 'images/'; const THUMBDIR = 'thumbs/'; const THUMBSIZE = 150; // max thumbnail dimension const NUM = 100; // number of images to be processed on each run $images = glob(IMGDIR.'{*.png,*.jpg}', GLOB_BRACE); $thumbs = glob(THUMBDIR.'{*.png,*.jpg}', GLOB_BRACE); // reduce to basenames only $images = array_map('basename', $images); $thumbs = array_map('basename', $thumbs); // copy the next NUM images to $todo list where thumbnails do not yet exist $todo = array_slice(array_diff($images, $thumbs), 0, NUM); $output = ''; foreach ($todo as $fn) { $sz = getimagesize(IMGDIR.$fn); if ($sz[0] == 0) continue; // not an image $ok = 0; $out = null; switch ($sz['mime']) { // check the mime types case 'image/jpeg': $im = imagecreatefromjpeg(IMGDIR.$fn); $ok = $im; $out = 'imagejpeg'; break; case 'image/png': $im = imagecreatefrompng(IMGDIR.$fn); $ok = $im; $out = 'imagepng'; break; default: $ok = 0; } if (!$ok) continue; // not png or jpg // calculate thumbnail dimensions if ($sz[0] >= $sz[1]) { // landscape $w = THUMBSIZE; $h = THUMBSIZE * $sz[1]/$sz[0]; } else { // portrait $h = THUMBSIZE; $w = THUMBSIZE * $sz[0]/$sz[1]; } // copy and resize the image $tim = imagecreatetruecolor(THUMBSIZE, THUMBSIZE); $bg = imagecolorallocatealpha($tim,0xFF,0xFF,0xFF,127); imagefill($tim, 0, 0, $bg); imagecolortransparent($tim, $bg); // centre the image in the 150 pixel square $dx = (THUMBSIZE - $w) / 2; $dy = (THUMBSIZE - $h) / 2; imagecopyresized($tim, $im, $dx, $dy, 0, 0, $w, $h, $sz[0], $sz[1]); imagesavealpha($tim, true); $out($tim, THUMBDIR.$fn); imagedestroy($im); imagedestroy($tim); $output .= "<img src='".THUMBDIR."$fn' alt='$fn'>\n"; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-language" content="en"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Create Thumbnails</title> <meta name="author" content="Barry Andrew"> <meta name="creation-date" content="10/09/2019"> <style type="text/css"> body { font-family: verdana, sans-serif; font-size: 11pt; } header { background-color: black; color: white; padding: 15px 10px;} img { margin: 5px; } </style> </head> <body> <header> <h1>New Thumbnail Images</h1> </header> <?=$output?> </body> </html>
  11. 2 points
    This example uses glob() to get all .png and .jpg in a folder. By default, the folder is assumed to be named "images" and is a subdirectory of the folder containing the script. Images are displayed as thumbnails, 5 in each row with 25 per page. <?php session_start(); const IMGDIR = 'images/'; const PERPAGE = 25; $page = $_GET['page'] ?? 1; $imgdir = $_GET['dir'] ?? IMGDIR; if (!isset($_SESSION['imgdir']) || $_SESSION['imgdir'] != $imgdir) { unset($_SESSION['images']); $_SESSION['imgdir'] = $imgdir; $page = 1; } if (!isset($_SESSION['images'])) { $_SESSION['images'] = glob($imgdir.'{*.png,*.jpg}', GLOB_BRACE); // get .jpg and .png images } $total = count($_SESSION['images']); /** ************************************************************************************** * display paginated images from SESSION['images] * * @param int $page * @param int $perpage */ function displayImages($page, $perpage) { $start = ($page - 1) * $perpage; $ilist = array_slice($_SESSION['images'], $start, $perpage); foreach ($ilist as $i) { $n = trim(basename($i)); list($iw, $ih,, $sz) = getimagesize($i); if ($iw >= $ih) { // landscape $w = 150; $h = 150 * $ih/$iw; } else { // portrait $h = 150; $w = 150 * $iw/$ih; } $alt = substr($n, 0, 15); echo " <div class='image'> <img src='$i' height='$h' width = '$w' alt='$alt'> </div> "; } echo "<div style='clear:both'></div>"; } /** ************************************************************************************ * function to output page selection buttons * * @param int $total total records * @param int $page current page number * @return string selection buttons html */ function page_selector($total, $page) { if ($total==0) { return ''; } $kPages = ceil($total/PERPAGE); $filler = '&nbsp;&middot;&nbsp;&middot;&nbsp;&middot;&nbsp;'; $lim1 = max(1, $page-2); $lim2 = min($kPages, $page+3); $p = $page==1 ? 1 : $page - 1; $n = $page== $kPages ? $kPages : $page + 1;; $out = "$kPages page" . ($kPages==1 ? '' : 's') . " &emsp;"; if ($kPages==1) { return $out; } $out .= ($page > 1) ? "<div class='pagipage' data-pn='$p'>Prev</div>&ensp;" : "<div class='pagipage x' data-pn='$p' disabled>Prev</div>&ensp;"; if ($page > 4) { $out .= "<div class='pagipage' data-pn='1'>1</div> $filler"; } elseif ($page==4) { $out .= "<div class='pagipage' data-pn='1'>1</div>"; } for ($i=$lim1; $i<=$lim2; $i++) { if ($page==$i) $out .= "<div class='pagicurrent'>$i</div>"; else $out .= "<div class='pagipage' data-pn='$i'>$i</div>"; } if ($page < $kPages-3) { $out .= "$filler <div class='pagipage' data-pn='$kPages'>$kPages</div>"; } $out .= $page < $kPages ? "&ensp;<div class='pagipage' data-pn='$n'>Next</div>" : "&ensp;<div class='pagipage x' data-pn='$n' disabled>Next</div>"; return $out; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-language" content="en"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="author" content="B A Andrew"> <meta name="creation-date" content="11/29/2019"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Example</title> <script type="text/javascript"> $().ready( function() { $(".pagipage").click( function() { $("#page").val( $(this).data("pn") ) $("#form1").submit() }) }) </script> <style type="text/css"> body { font-family: verdana, sans-serif; font-size: 11pt; } label { display: inline-block; width: 150px; font-weight: 600; } #image_wrapper { margin: 30px; } .image { width: 18%; min-height: 200px; margin: 10px; float: left; text-align: center; padding: auto;} /* pagination styles */ .pagipage { display: inline; width: 25px; height: 15px; padding: 3px 5px; text-align: center; font-size: 9pt; border: 1px solid #BB9A21 ; color: #BB9A21; background-color: #FFF; cursor: pointer; margin-left: -1px; } .pagipage.x { background-color: #CCC;} .pagipage:hover { background-color: #BB9A21; border-color: #F0F; color: white; } .pagicurrent { display: inline; width: 25px; height: 15px; text-align: center; font-size: 9pt; font-weight: 600; border: 1px solid #BB9A21; background-color: #BB9A21; color: white; padding: 3px 5px; } .paginate_panel { text-align: center; margin: 20px 0; width: 100%; color: #BB9A21; } </style> </head> <body> <header> <h1>Example Image List</h1> </header> <form id="form1"> <fieldset> <label>Image Folder</label> <input type="text" name="dir" value="<?=$imgdir?>" size="80"> <input type="hidden" name="page" id="page" value="<?=$page?>"> <br> <label>&nbsp;</label> <input type="submit" name="btnSubmit" value="Submit"> </fieldset> </form> <div class='paginate_panel'> <?=page_selector($total, $page, PERPAGE)?> </div> <div id="image_wrapper"> <?=displayImages($page, PERPAGE)?> </div> <div class='paginate_panel'> <?=page_selector($total, $page, PERPAGE)?> </div> </body> </html>
  12. 2 points
    Yes but you don't want to run both at the same time. If you really wanted to, you would need to change the Apache port on one of them as they both use port 80
  13. 2 points
    Hi, This is a probably a wrong way of inserting new email into the DB and can result in race conditions. You should be inserting the new email directly into the DB and your column for ermail ids should be unique so that it throws an exception for duplicate entries.
  14. 2 points
    It depends on the collation setting for the column.
  15. 2 points
    Not even close. This code... $product_details = "SELECT * FROM product WHERE product_id=".$_GET['product_id']; $prepare = $connect->prepare($product_details); $prepare->execute(); ...would embed any SQL injection code contained in the GET into the query which would then be executed. (Just as an unprepared query would) In the correct version the injection code would only be treated as data and not part of the SQL code.
  16. 2 points
    This is my take on it. I copy/pasted a couple of extra jobs to give... CODE <?php $required = ['Feasibility', 'Measure Up', 'Model Drawing', 'Concept Design', 'Developed Design', 'Resource Consent', 'Construction Documentation' ]; $colors = array_combine($required, ['w3-red', 'w3-green', 'w3-orange', 'w3-deep-orange', 'w3-teal', 'w3-yellow', 'w3-purple'] ); $staff_arr = [ 'Staff1' => 'SP', 'Staff2' => 'MB', 'Staff3' => 'BF', 'Staff4' => 'MCP', 'Staff5' => 'DG' ]; function state_dropdown($staff, $color) { return "<form action='' method='POST'>" . "<select class='w3-input w3-round $color' name ='StaffName' onchange='this.form.submit()'>" . // why is a menu of states called "StaffName" ? "<option value =''>$staff</option>" . "<option class='form-control col-sm-3 bg-white text-dark'>Feasibility </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Measure Up </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Model Drawing </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Concept Design </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Developed Design </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Resource Consent </option> " . "<option class='form-control col-sm-3 bg-white text-dark'>Construction Docs </option> " . "</select>" . "</form>"; } $xml = simplexml_load_file('plugnz.xml'); $data = []; // // collect the jobs and current task data into an array // foreach ($xml->Jobs->Job as $job) { $id = (string)$job->ID; $state = (string)$job->State; if (!in_array($state, $required)) continue; $data[$id] = [ 'name' => (string)$job->Name, 'state' => $state ]; $tasks = $job->xpath("Tasks/Task[Name='$state']"); $clr = $colors[$state]; $due = (string)$tasks[0]->DueDate; $data[$id]['due'] = date('Y-m-d', strtotime($due)); $data[$id]['display_date'] = date('M d Y', strtotime($due)); $assigned = []; foreach ($tasks[0]->Assigned->Staff as $s) { $assigned[] = $staff_arr[(string)$s->Name]; } $staff_str = join(' ', $assigned); $data[$id]['task'] = [ 'staff' => $staff_str, 'clr' => $clr ]; } // // sort the data array on the task due date DESC // uasort($data, function($a,$b) { return $b['due'] <=> $a['due']; } ); // // output the array as a table // $tdata = ''; foreach ($data as $jid => $jdata) { $tdata .= "<tr><td class='jobno'>$jid</td><td>{$jdata['name']}</td>"; foreach ($required as $stat) { if ($jdata['state']==$stat) { $tdata .= "<td>" . state_dropdown($jdata['task']['staff'], $jdata['task']['clr']) . "</td>"; } else { $tdata .= "<td>&nbsp;</td>"; } } $tdata .= "<td>&nbsp;</td>"; $tdata .= "<td>{$jdata['display_date']}</td></tr>"; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="creation-date" content="05/10/2019"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <title>Job Status Table</title> <style type="text/css"> body { font-family: verdana,sans-serif; font-size: 10pt; padding: 20px 50px; } table {border-collapse: collapse;} .th-sm-1 { font-size: 8pt; text-align: left; } .jobno { font-weight: 600; color: #2196f3; } select { width: 120px; } </style> </head> <body> <table border=1> <thead> <tr> <th class="th-sm-1">Project Number</th> <th class="th-sm-1">Project Name</th> <th class="th-sm-1">Feasibility</th> <th class="th-sm-1">Measure Up</th> <th class="th-sm-1">Model Drawing</th> <th class="th-sm-1">Concept Design</th> <th class="th-sm-1">Developed Design</th> <th class="th-sm-1">Resource Consent</th> <th class="th-sm-1">Construction Docs</th> <th class="th-sm-1">Milestone</th> <th class="th-sm-1">Due Date</th> </tr> </thead> <tbody> <?=$tdata?> </tbody> </table> </body> </html>
  17. 2 points
    Protecting a form field from what? htmlspecialchars() is for use when outputting user-supplied data data to a web page. mysql_real_escape string() is was used to protect input values to queries from SQL injection. This is now obsolete, replaced by mysqli_real_escape_string() or (better still) the use of prepared statements to completely separate the query code from the user-supplied data.
  18. 2 points
    the path being used in the opendir() statement either has a hard-coded '/home/sites/' in it or is using a variable that has that incorrect value in it. based on the path where the code is actually at, that part of the path should be - /home/customer/www/
  19. 2 points
    Store the info that the user put in the original QR code. User retrieves and edits the data, then generates new QR code.
  20. 2 points
    I have been playing around with a possible database solution to your problem Given that a postcode such as "EH12 3AB" breaks down into four parts viz +------+----------+--------+------+ | area | district | sector | unit | +------+----------+--------+------+ | EH | 12 | 3 | AB | +------+----------+--------+------+ ... I was toying with this table structure CREATE TABLE `postcode` ( `pc_id` int(11) NOT NULL AUTO_INCREMENT, `seller` int(11) DEFAULT NULL, `area` varchar(2) DEFAULT NULL, `district` varchar(2) DEFAULT NULL, `sector_min` char(1) DEFAULT NULL, `sector_max` char(1) DEFAULT NULL, `unit_min` char(2) DEFAULT NULL, `unit_max` char(2) DEFAULT NULL, `deliverable` tinyint(4) DEFAULT NULL, `price` decimal(8,2) DEFAULT NULL, PRIMARY KEY (`pc_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +-------+--------+------+----------+------------+------------+----------+----------+-------------+-------+ | pc_id | seller | area | district | sector_min | sector_max | unit_min | unit_max | deliverable | price | +-------+--------+------+----------+------------+------------+----------+----------+-------------+-------+ | 1 | 1 | EH | 1 | 1 | 4 | AA | ZZ | 1 | 1.50 | | 2 | 1 | EH | 1 | 5 | 5 | AA | BZ | 1 | 1.80 | | 3 | 1 | EH | 1 | 5 | 5 | CA | ZZ | 0 | 2.00 | | 4 | 1 | EH | 2 | 1 | 9 | AA | ZZ | 1 | 2.25 | | 5 | 1 | EH | 3 | 1 | 9 | AA | PZ | 1 | 2.50 | +-------+--------+------+----------+------------+------------+----------+----------+-------------+-------+ My code was $postcodes = [ 'EH1 2DB', 'eh15bg' , 'eh1 5ba', 'eh15dg', 'EH2 7HJ', 'EH3 2PT', 'EH3 8SX', 'EH146DE' ]; echo '<pre>'; foreach ($postcodes as $pc) { vprintf('%s%s %s%s : %s<br>', deliveryPrice($db, $pc)); } echo '</pre>'; function deliveryPrice($db, $pcode) { $pcode = strtoupper(str_replace(' ', '', $pcode)); $area = $district = ''; $sector = substr($pcode,-3, 1); $unit = substr($pcode, -2); $l = strlen($pcode); $first = str_split(substr($pcode, 0, $l-3)); foreach ($first as $c) { if (ctype_digit($c)) { $district .= $c; } else { $area .= $c; } } $res = $db->prepare("SELECT price FROM postcode WHERE area = ? AND district = ? AND ? between sector_min AND sector_max AND ? BETWEEN unit_min AND unit_max AND deliverable "); $res->execute( [ $area, $district, $sector, $unit ] ); $p = $res->fetchColumn(); $price = $p ? number_format($p, 2) : 'N/A'; return [$area, $district, $sector, $unit, $price ]; } RESULTS: EH1 2DB : 1.50 EH1 5BG : 1.80 EH1 5BA : 1.80 EH1 5DG : N/A EH2 7HJ : 2.25 EH3 2PT : 2.50 EH3 8SX : N/A EH14 6DE : N/A
  21. 2 points
    $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
  22. 2 points
    You need to specify your units for the margin values. 161px, not just 161.
  23. 2 points
    Not as it is now - if you want to tell the user which is taken you'll have to update the query. Right now it just returns a count of records that match either the username or the email. You'll have to actually select both and then check in PHP which one matches, or rewrite the query to return the offending column. However, I'd recommend just letting people know that one of the two has been taken. That way you're not confirming to an outside party which of the two actually exists in the database - a hacker that knows for a fact a username exists has less work to do and can focus only on figuring out a correct password.
  24. 2 points
    Just use var_dump if you just need to see what the array contains.
  25. 2 points
    If this is a repetitive project that is going to build all of the mentioned arrays every time it is executed, perhaps you should consider not having to re-build your second array by using the SKU as the index value of the first array and avoid creating the 2nd array. Change this: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; to: $product_table[$sku][] = ['Label' => $attribute_name, 'Value' => $term_obj->name ];
  26. 2 points
    You may find my reply to one of your previous topics of interest here. (I sometimes ask myself why we bother)
  27. 2 points
    here's a list of things i saw in the posted code - 1. don't put php variables inside of double-quotes if they are the only thing in the string. 2, don't use or die() for error handling. use exceptions and in most cases let php catch the exception. note: your use of mysqli_error(...) in the connection code won't work because there's no connection to use. 3. don't unconditionally output database errors onto a web page (this will go away when you get rid of the or die() logic.) 4. don't run queries inside of loops. learn to do JOIN queries. 5. if your code is tabbed that far over because it is located inside your html document, you need to put the php code that's responsible for getting/producing data before the start of your html document, fetch the data into appropriately named php variable(s), then use those variable(s) in the html document. 6. handling the negative/failure case is usually shorter then the positive/successful case. if you invert the logic tests and handle the negative/failure condition first, your code will be clearer. you won't have logic for the negative/failure case 10's/100's of lines later in the code. 7. don't use loops to fetch what will be at most one row of data. just directly fetch the single row of data. 8. don't put static calculations inside of loops. the various date values shouldn't change during one report (where they are at now, they will if the request spans midnight.) put them before the start of the loop. 9. don't put quotes around numbers. 10. don't selected things that are not used and don't create variables that are not used (given the amount of code, the cases i saw of this may not be accurate.) 11. if you are looping to do something (should go away with JOINed queries), don't evaluate count() statements in the loop. determine the loop count, once, before the start of the loop. 12. doing some of these things will simplify variable naming. you won't have to think up unique names for variables because you will only have one instance in the code. 13. the $AffID is probably from external/unknown data. you should NOT put eternal/unknown data directly into an sql query statement. use a prepared query, with a place-holder for each data value, then supply the data when the query gets executed. switching to the much simpler php PDO extension will make using prepared queries easy compared to the php mysqli extension.
  28. 2 points
    In the absence of a reply, I estimated the radius to be about 3.5m from that photo. This gives a table of volmes and weights based on that radius. Note the absence of if..., if..., if..., if...) <?php const R = 350; // radius of tank cm NOTE: estimated - replace with actual radius const HC = 40; // cone height cm function tank_volume ($h) { $k = M_PI * R**2 ; if ($h <= HC) { $vol = $k * $h / 3 ; } else { $vol = $k * HC / 3 + $k * ($h - HC); } return $vol; } $results = []; foreach (range(1,500) as $h) { $vol = tank_volume($h); $results[] = [ 'ht' => $h, 'vol' => number_format($vol, 0), 'Kg' => number_format($vol/1000, 0) ]; } $chunks = array_chunk($results,100); $output = ''; foreach ($chunks as $ch) { $output .= "<div class='output'> <table><tr><th>Height<?th><th>Volume (cc)</th><th>Kg</th></tr> "; foreach ($ch as $res) { $cls = $res['ht'] < 41 ? "class='cone'" : ''; $output .= "<tr $cls><td>".join('</td><td>', $res)."</td></tr>\n"; } $output .= "</table></div>\n"; } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)"> <title>Tank Volumes</title> <meta name="author" content="Barand"> <link rel="shortcut icon" href=""> <meta name="creation-date" content="02/01/2019"> <style type='text/css'> body { font-family: calibri, arial, sans-serif; font-size: 10pt; } #title { height: 50px; font-size: 24px; font-weight: 600; background-image: linear-gradient(#2DABE1, #FFFFFF); color: #FFF; padding: 15px; } .output { width: 300px; font-size: 20px; float: left; padding: 2px; border-right: 1px solid #BB9A21; } table { width: 100%; font-size: 10pt; } th { background-color: #BB9A21; color: #FFF; padding: 5px; } td { text-align: right; padding: 2px 5px; } .cone { background-color: #EEE; } </style> </head> <body> <div id='title'>Tank Volumes and Weights</div> <?=$output?> </body> </html> Sample output
  29. 2 points
    Use absolute URLs <link rel="shortcut icon" href="/images/favicon.ico.png"> <a href="/index"> <img src="/images/logo.PNG" alt="logo" /> I don't understand how so many people can be unaware of them.
  30. 2 points
    Use array_intersect(), arrays, and CSS and save yourself all that repetition <?php $arrays = [ 'A' => [2, 6, 8, 11, 14, 18, 24], 'B' => [1, 2, 9, 10, 13, 14, 25, 28], 'C' => [1, 3, 7, 9, 13, 15, 20, 21, 24], 'D' => [4, 5, 12, 22, 23, 27, 28, 29] ]; $input = '2,15,37,13,28'; $parts = explode(',', $input); ?> <!DOCTYPE html> <html> <title>Example</title> <style type='text/css'> table { border-collapse: collapse; } th, td { font-family: verdana,arial,helvetica,sans-serif; font-size: 12px; } th { background-color: #DCDCDC; color: #000; text-align: left; padding: 4px; } td { padding: 4px; } </style> <body> <table border='1'> <?php foreach ($arrays as $gp => $a) { echo "<tr><th>GROUP $gp</th><td>" . join(', ', array_intersect($a, $parts) ) . "</td></tr>\n"; } ?> </table> </body> </html>
  31. 2 points
    I like what you've done with the avatars. Merry Christmas!
  32. 2 points
    For example $a = 1010 $b = 1111 $b ^= $a // Xor $b = 0101 $b ^= $a // repeat Xor $b = 1111 // $b restored
  33. 2 points
    Text areas do not have a value attribute. EG <textarea rows="10" cols="100" name="page_description" >Text area content goes here</textarea> The text content goes between the <textarea> and </textarea> tags. As you don't have the closing </textarea> it assumes everything following is still part of the text content.
  34. 2 points
    It also doesn't say so on the documentation for explode() or mysqli_connect(). That function is part of the GeoIP package, which has a whole section dedicated to setting it up.
  35. 2 points
    OK, I've donned my red costume and white beard. Here's an example of displaying more or less text Data CREATE TABLE `product` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `description` text, PRIMARY KEY (`product_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `product` (`description`) VALUES ('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem.'), ('In porttitor. Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy. Fusce aliquet pede non pede. Suspendisse dapibus lorem pellentesque magna. Integer nulla. Donec blandit feugiat ligula. Donec hendrerit, felis et imperdiet euismod, purus ipsum pretium metus, in lacinia nulla nisl eget sapien.'), ('Donec ut est in lectus consequat consequat. Etiam eget dui. Aliquam erat volutpat. Sed at lorem in nunc porta tristique. Proin nec augue. Quisque aliquam tempor magna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc ac magna. Maecenas odio dolor, vulputate vel, auctor ac, accumsan id, felis. Pellentesque cursus sagittis felis.'); Example code <?php include('db_inc.php'); $db = pdoConnect("test"); // connect to "test" database // // this bit handles the AJAX request to get the full or partial description // if (isset($_GET['ajax'])) { $stmt = $db->prepare("SELECT description FROM product WHERE product_id = ? "); $stmt->execute( [ $_GET['id'] ] ); $descrip = $stmt->fetchColumn(); switch ($_GET['ajax']) { case 'more': $less = "<span class='less' data-id='{$_GET['id']}'> (less)</span>"; exit($descrip.$less); // send back the description in the ajax response case 'less': $words = explode(' ', $descrip); $partial_descrip = join(' ', array_slice($words, 0, 25)); $more = "<span class='more' data-id='{$_GET['id']}'> ...more</span>"; exit($partial_descrip.$more); } } // // select the product details from the table // $res = $db->query("SELECT product_id , description FROM product "); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)"> <title>Example</title> <style type='text/css'> .descrip { font-family: verdana, sans-serif; font-size: 10pt; margin-left: 50px; width: 50%; } .more, .less { color: blue; cursor: pointer; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type='text/javascript'> $().ready( function() { $(".more").click( function() { var id = $(this).data('id') var target = $(".descrip[data-id="+id+"]") // find descrip div with matching data-id $.get ( "", // send request to "self" { "ajax" : "more", "id" : id }, function(resp) { target.html(resp) // put returned description in target div enableLess() }, "TEXT" ) }) }) function enableLess() { $(".less").click( function() { var id = $(this).data('id') var target = $(".descrip[data-id="+id+"]") // find descrip div with matching data-id $.get ( "", // send request to "self" { "ajax" : "less", "id" : id }, function(resp) { target.html(resp) // put returned description in target div }, "TEXT" ) }) } </script> </head> <body> <?php // // display the data, putting description in its own div // foreach ($res as $row) { $words = explode(' ', $row['description']); $partial_descrip = join(' ', array_slice($words, 0, 25)); // show first 25 words of description $more = "<span class='more' data-id='{$row['product_id']}'> ...more</span>"; echo "<div class='product'> <h3>Product {$row['product_id']}</h3> <div class='descrip' data-id='{$row['product_id']}'> <h4>Description</h4> $partial_descrip $more </div> </div>\n"; } ?> </body> </html> Sample output
  36. 2 points
    You could assign the event names to an array, for example: $name = array(); while ($row_events = $sth_events->fetch(PDO::FETCH_ASSOC)) { $name[] = $row_events['name']; } Then you could use implode() to output the array. Note that I streamlined the following code a bit: $week .= '<td><div class="'; $week .= ($today == $date) ? 'today' : 'day'; $week .= '">' . $day . '</div>' . implode('<br>', $name) . '</td>'; With that said, it would be better to rewrite the script, as requinix is suggesting, so that you're not running queries inside of loops.
  37. 2 points
    I've been wrestling with this logic puzzle for days... My website lists item prices as they are posted: First item: item# ABC1234 = Hammer $5.00 Visitor then submits (to the same page) more item numbers (e.g. item# DEF9999) and the displayed list will grow: item# ABC1234 = Hammer $5.00 item# DEF9999 = Crowbar $6.00 --------------------------------------- However, when website gets visited via Affiliate, I want PHP to launch a Session to "remember" the First Referred Item, along with the Affiliate: // http://www.example.com/salePrice.php?Affiliate=SomeExampleCompany&item=ABC1234 <?php if(isset($_GET["Affiliate"])) { session_start(); $_SESSION["Affiliate"] = sanitized($_REQUEST["Affiliate"]); $_SESSION["item"] = sanitized($_REQUEST["item"]); } ?> <body> <form action="salePrice.php" method="post"> etc. etc. etc. The problem: Session won't stay running if visitor subsequently posts more items to the same page. (I thought once a Session starts, the Session will run as long as you don't navigate away from the page.) Without having to put "session_start()" on the top of the page (and have Sessions running no matter what), what is the trick to get this to work?
  38. 2 points
    OR if you use the same named hidden field for all the forms, 'action' for example, each with a unique value, you can eliminate any isset() tests for that field since it will be set if the request method is post.
  39. 2 points
    Added some extra lines to facilitate output (commented) <?php $results = []; $teamnames = []; // array to gather the unique team names foreach ($data as $yr => $ydata) { if (!isset($results[$yr])) { $results[$yr] = []; } foreach ($ydata as $tdata) { if (!isset($results[$yr][$tdata['team']])) { $results[$yr][$tdata['team']] = 0; } $results[$yr][$tdata['team']] += $tdata['value']; $teamnames[$tdata['team']] = 0; // put teamname in array as the key. } } $thead = "<tr><th>Year</th><th>" . join('</th><th>', array_keys($teamnames)) . "</th></tr>\n"; $tdata = ''; foreach ($results as $yr => $tresults) { $totals = $teamnames; // copy of the empty teamnames array foreach ($tresults as $tm => $tot) { $totals[$tm] = $tot; /// put the totals into the team column } $tdata .= "<tr><td>$yr</td><td>" . join('</td><td>', $totals) . "</td></tr>\n"; } ?> <html> <body> <table border='1' style='border-collapse:collapse'> <?=$thead?> <?=$tdata?> </table> </body> </html>
  40. 2 points
    One of the lines comes from the engine is controlled by the display_errors ini setting. These are printed on STDOUT. The second line is from the -l setting showing the specific error it encountered. These are printed on STDERR. So, you can do two different things. 1) You could turn off display_errors to prevent one of the messages on STDOUT. You can do this by passing -d display_errors=0 2) You could redirect either STDOUT or STDERR to /dev/null (or elsewhere) to ignore or capture them specifically.
  41. 2 points
    So we all (most of us) know some CSS. You might not consider yourself a web designer, be fluent with all the popular libraries, but you know your way around how to do it. Like if you want to make something bold you could inline it <span style="font-weight:bold;">An important statement</span> but you're smarter and you know you should .bold { font-weight: bold; } <span class="bold">An important statement</span> A trivial example, of course, but it demonstrates how you should use CSS. Right? No. God damn *#(*^y$&#ing NO. So maybe it's a bad example. People don't actually do that. Okay. Let's look at some official Bootstrap examples instead. <button type="button" class="btn btn-lg btn-default">Default</button> No. <table class="table table-striped"> Stop that. <ul class="list-group"> <li class="list-group-item">Cras justo odio</li> Dude. What's the problem here? You're restating the obvious! I know that button is a button. It's got #*^(ing "button" right in the (*^-@$ markup. Ooh, it's a LARGE button. Wow! And hey, that table has stripes? Amazing! And you mean to tell me that UL is a list and the LI is an item? You're blowing my mind! You're also DOING IT WRONG. The power behind CSS is (a) not having to tell the browser that yes, in fact, that button really is a button, and (b) not having to say the same thing over and over again in different places. And that is where Bootstrap fails miserably. You want to create a button? Go ahead. Create the button. Then throw a few classes at it so it looks the way you want. Want another button? Create another button and throw classes at that one too. Created a button and it doesn't look right? Oh damn, you forgot one of the classes you have to include. Ha ha, oops. "But that's how CSS should be used!" No. You're all missing the (*@#*^ing point and making everything hard on yourself and the people who have to deal with your crap. What if I want to add a dropdown list of items? What should I do? The page already has a couple dropdowns on it so I know the styling is in place. I'll add a simple <select> and... nope, looks like a plain list. No styling applied. What happened? What happened is that I didn't apply the handful of classes necessary to make the list appear like the damn list it should already be. What happened is that I forgot I have to add in the presentation aspects to my HTML. And that's what this whole stupid thing boils down to: people can't shift their mindset away from the presentation, and while they know not to mix presentation with markup they've not noticed that all they did was trade one syntax for another. The problem is still (@^$ there. "Oh, right, yeah, if you're so smart then how would you do it?" Thank you for asking. You want a button. You want a large button. You want a large button that draws peoples' eyes to it because it's the button they probably want to use and so it's the default. That's presentation. Forget about presentation. You want a default button. That's it. That's all you should have to care about. <button type="button" class="default">Default</button> Done. "But no, it doesn't look the way I want!" I don't give a damn how you want it to look. I want to know what the button means. What is the significance behind the button. What does it represent. Because ultimately that's what the HTML markup needs to concern itself with. Write semantic markup and leave out the presentation crap because it has no place in the document. "Oh, so you think we shouldn't have any CSS at all or what?" Take those words out of my mouth before I cram them back down yours. button { /* make it look like a nice button */ } button.default { /* blue or whatever */ } There. Now the presentation is accounted for in the @(!^)$ place where it should be: CSS. And if I want to add another default button somewhere I don't have to look up the Bootstrap reference because I don't remember which 5 classes are relevant. Default button? Default button. The only way this could improve is if HTML added a way to actually identify the default button of a form, in which case that class=default goes right out the damn window and the CSS targets that new attribute or whatever it is instead. "Noo, it's not a large button!" Alright. Fine. Let me take a deep breath before I have to deal with you. So. Why do you want it to be large? Don't give me some stupid reason like "because I want it to be large". What is the reason behind making it large? What decision process did you go through in your head that resulted in the button needing to be larger? Why is the normal size for buttons not appropriate? Maybe the form is a modal and you want larger buttons? Okay. Did you mark the form as modal? Because that's the first thing you have to do. <form class="modal"> form.modal button { /* larger */ } And done. Problem solved. Problem solved in a way that keeps the appearance of the button separate from the markup of the button. Want to add another button to the modal? Go on. Add another stupid button. One that doesn't require any classes just because it's supposed to be larger. What you might be able to realize here is that now I've established a rule saying "buttons in modal forms are larger". And it applies everywhere you have a modal form. If you make another modal form then magically the buttons are larger there too! And without having to find that first place you had that one modal form, what page was that again, oh right, over here, now what classes and CSS files did I have to use for it to make it look that way, oh right, those classes. How about a striped table? Why is it striped? Because it's a table that will grow vertically and has enough data in its columns that people need help scanning through them? So what you're telling me is that the table is, say, "dense"? <table class="dense"> table.dense > tbody > tr:nth-child(odd) { /* striped */ } Somehow I'm able to rub a couple brain cells together and end up with a way of identifying the table for what it is and not what I want it to look like on the page. How about a regular list? Nothing special? <ul> <li>Cras justo odio</li> Nothing (*&^!@ special. Now when I come along, I can write markup into your fancy page you spent a couple days tweaking until it looked oh so pretty, and I don't have to run off to the kitchen where I can cool my heels instead of planning your "accidental" death because I can write simple, logical, and minimal HTML that represents what I'm adding without having to fire up five different browsers to see that I got all the required classes. What's more, if someone decides that modal dialogs on mobile devices need to look a little different, I don't have to spend a day searching the codebase for anything modal because the work has gone from "go fix all the modal dialogs to use this new CSS class someone wrote" to "apply media queries to adjust the existing modal dialog to better suit mobile screens". This isn't damn rocket science. I know you web designers had a hard time in college with your liberal arts degree and that's it's so unfair you have to work with computer graphics instead of living in a loft painting bowls of fruit all day, but surely even you are smart enough to understand these principles. Stop thinking with your eyes and start thinking with your brain. And now I go back to work. Dealing with stupid crap. That I put off by ranting about it here.
  42. 2 points
    use array_filter() with the ARRAY_FILTER_USE_KEY flag set. EDIT: Of course the easiest method is not to put data into the array that you then want to remove PS If you prefer to use a foreach loop then $result = []; foreach ($array as $k => $v) { if ($k) { $result[$k] = $v; } }
  43. 2 points
    As you are sorting on "name", which is the first element of the sub-arrays, you can just use an ordinay sort() or rsort() call. (By default it will sort on the values oof the first element) EG $tadminlist["pvp"] = [ [ 'name' => 'mapname1', 'type' => 'pvp', 'beta' => 'y', 'final' => 'n', 'modded' => '', 'classification' => 'land', 'sf' => 'n', 'tod' => 'dawn', 'weather' => 'fog', 'es2' => 'y' ], [ 'name' => 'mapname3', 'type' => 'pvp', 'beta' => 'yy', 'final' => 'n', 'modded' => 'y', 'classification' => 'air', 'sf' => 'y', 'tod' => 'day', 'weather' => 'rain', 'es2' => 'n' ], [ 'name' => 'mapname2', 'type' => 'pvp', 'beta' => 'n', 'final' => 'y', 'modded' => 'n', 'classification' => 'sea', 'sf' => 'n', 'tod' => 'night', 'weather' => 'clear', 'es2' => 'n' ], ]; echo "line = " . join(', ', array_keys($tadminlist["pvp"][0])) . '<br><br>'; listData($tadminlist["pvp"]); echo "<br>SORTED ASC<br>"; sort($tadminlist["pvp"]); listData($tadminlist["pvp"]); echo "<br>SORTED DESC<br>"; rsort($tadminlist["pvp"]); listData($tadminlist["pvp"]); function listData($arr) { foreach ($arr as $tlist) echo join(', ', $tlist) . '<br>'; } OUTPUTS line = name, type, beta, final, modded, classification, sf, tod, weather, es2 mapname1, pvp, y, n, , land, n, dawn, fog, y mapname3, pvp, yy, n, y, air, y, day, rain, n mapname2, pvp, n, y, n, sea, n, night, clear, n SORTED ASC mapname1, pvp, y, n, , land, n, dawn, fog, y mapname2, pvp, n, y, n, sea, n, night, clear, n mapname3, pvp, yy, n, y, air, y, day, rain, n SORTED DESC mapname3, pvp, yy, n, y, air, y, day, rain, n mapname2, pvp, n, y, n, sea, n, night, clear, n mapname1, pvp, y, n, , land, n, dawn, fog, y To sort by any other element would require usort, eg to sort by classification usort($tadminlist["pvp"], function($a, $b) { return $a['classification'] <=> $b['classification']; } );
  44. 2 points
    Alternative for Windows users with no money_format() function $prices = [ 39.99, 35.99, 69.99, 89.99 ]; function deu_money($n) { return '&euro;'.number_format($n, 2, ',', '.'); } $prices = array_map( 'deu_money' , $prices); giving $prices Array ( [0] => €39,99 [1] => €35,99 [2] => €69,99 [3] => €89,99 )
  45. 2 points
    Applying opacity to a div affects everything within the div, including type and nested divs. Use background opacity via rgba() to do what you're wanting: body{ background: url("https://image.ibb.co/h93Ndo/abstract.jpg") top right no-repeat; background-attachment: fixed; } .body-container{ display: flex; flex-direction: column; justify-content: stretch; align-items: stretch; background: red; color: white; min-height: 100vh; } .header{ flex-grow: 0; background: rgba(58, 152, 253, 1); } .two-cols{ flex-grow: 1; display: flex; flex-direction: row; justify-content: stretch; } .left-container{ display: flex; flex-direction: column; justify-content: flex-start; flex-grow: 1; flex-basis: 20%; background: rgba(59, 74, 83, 1); } .content{ display: flex; flex-direction: column; justify-content: flex-end; flex-grow: 1; flex-basis: 80%; background: rgba(255, 255, 255, .7); } Also, is there any reason why you needed to add the !important to the display rule on the .body-container div? @gizmola - apparently I'm going to need to read that article as well as I've not found float collapse to be an issue using flexbox. Or at least I've not recognized that that's what it is... Anyway - thanks for the link!
  46. 2 points
    1) set php's error_reporting to E_ALL. it is not set to report exceptions and fatal runtime errors, you won't see anything for these type of errors. 2) on the old machine, what 'engine' were the tables using, InnoDB or MyISAM? if they were using MyISAM, then the various commit statements where having no affect and the queries were being executed in the order they are in the php code. 3) the usage of the various commit statements are causing the INSERT and UPDATE queries to not actually be executed until you call the ->commit() method. for prepared queries, i don't know what value the ->execute() calls return for INSERT/UPDATE queries since they are actually being executed later. 4) for the SELECT/INSERT/UPDATE queries for the vis_mistakes table. you can use one INSERT ... ON DUPLICATE KEY UPDATE ... query. if this is the reason you think you need to use the various commit statements, eliminate them and use this one query. 5) the 'output' you have posted doesn't seem to exactly match the posted code and it includes the UPDATE mysessda ... sql which should not be output if the code is really stopping, skipping conditional logic, or transferring execution to any exception handler/php. 6) speaking of an exception handler, since your code is throwing its own exceptions, do you have a custom exception handler and if so, what does it do for exception types that it does not handle, such as mysqli exceptions?
  47. 2 points
    Take a look at these two lines of code $row = mysqli_fetch_assoc($result); while($row = mysqli_fetch_assoc($result)){ and tell your rubber duck what they are doing.
  48. 2 points
    I'd go a step further and give all the checkboxes the same name EG name='problem[]' so they are posted as an array <label><input type="checkbox" name="problem[]" value="Hard Drive Crashed"> Hard Drive Crashed</label><br> <label><input type="checkbox" name="problem[]" value="Has Virus"> Has Virus</label><br> <label><input type="checkbox" name="problem[]" value="Needs Operating System"> Needs Operating System</label><br> <label><input type="checkbox" name="problem[]" value="Needs Microsoft Office"> Needs Microsoft Office</label><br> <label><input type="checkbox" name="problem[]" value="Interested In Backup Services"> Interested In Backup Services</label><br> <label><input type="checkbox" name="problem[]" value="Wants A Custom PC Build"> Wants A Custom PC Build</label><br> In your processing foreach ($_POST['problem'] as $problem) { echo $problem . '<br>'; }
  49. 2 points
    I found it here Or did you have something more like this in mind? Save this code as "stave.svg" <svg width="1000" height="200" viewBox="0 0 1000 200"> <defs> <style type="text/css"> .trebleclef { fill: black; font-size: 50pt; } .bassclef { fill: black; font-size: 40pt; } .curly { fill: black; stroke: none; font-size: 110pt; font-weight: 100; } .stave { stroke-width: 1px; stroke: gray; fill: none; } </style> </defs> <!-- treble --> <line x1='40' y1='30' x2='960' y2='30' class='stave' /> <line x1='40' y1='38' x2='960' y2='38' class='stave' /> <line x1='40' y1='46' x2='960' y2='46' class='stave' /> <line x1='40' y1='54' x2='960' y2='54' class='stave' /> <line x1='40' y1='62' x2='960' y2='62' class='stave' /> <text x='44' y='65' class='trebleclef'>&#x1D11E;</text> <!-- bass --> <line x1='40' y1='130' x2='960' y2='130' class='stave' /> <line x1='40' y1='138' x2='960' y2='138' class='stave' /> <line x1='40' y1='146' x2='960' y2='146' class='stave' /> <line x1='40' y1='154' x2='960' y2='154' class='stave' /> <line x1='40' y1='162' x2='960' y2='162' class='stave' /> <text x='44' y='165' class='bassclef'>&#x1D122;</text> <!-- stave ends --> <text x='-20' y='132' class='curly'>{</text> <path d="M 40 30 L 40 162" class='stave' /> <path d="M 960 30 L 960 162" class='stave' /> </svg> Then, in your html <div><?php include 'stave.svg'?></div> <div><?php include 'stave.svg'?></div> <div><?php include 'stave.svg'?></div> Which should give you
  50. 2 points
    Commencing with test_config.txt as # interface eth0 subnet netmask { } host cm-test1 { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address; filename "srv-050.cfg"; } host cm-test2 { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address; filename "srv-042.cfg"; } host cm-instrumenti { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address; filename "srv-050.cfg"; } host cm-nimonmehmetaj { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address; filename "srv-042.cfg"; } This is one way $unwanted = [ 'cm-instrumenti', 'cm-nimonmehmetaj' ]; // unwantedt host names $text = file_get_contents('test_config.txt'); $config = array_map('trim',explode('}', $text)); $new_config = array_filter($config, function ($v) use($unwanted) { foreach ($unwanted as $name) { if (strpos($v, $name)!==false) return false; // remove unwanted elements } return $v!=''; // remove blank entries }); file_put_contents('new_config.txt', join("\n}\n", $new_config) . "\n}\n"); giving new_config.txt as # interface eth0 subnet netmask { } host cm-test1 { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address; filename "srv-050.cfg"; } host cm-test2 { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address; filename "srv-042.cfg"; }
This leaderboard is set to New York/GMT-05:00
  • Newsletter

    Want to keep up to date with all our latest news and information?
    Sign Up
  • 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.