#FlattenTheCurve ×

Moderators

848

20,608

572

12,018

Members

565

4,207

Staff Alumni

245

4,395

## Popular Content

Showing content with the highest reputation since 09/23/2012 in all areas

1. 3 points

## Image X and Y for watermark

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

## How \$GLOBALS woks in PHP?

Don't use \$GLOBALS. Forget it exists. There is never a good reason to use it. Pretend you never saw it.
3. 3 points

## how to duplicate ascii-art-code on the fly in notepad - is this possible!?

+----------------+ +----------------+ | 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

## Simplify the PHP code

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

## How to use while loop inside a concatenation?

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

7. 2 points

## timestamps differences

Why are you even attempting to store that duration. You can get it any time you need it with a query. Rule of DB design - don't store derived data. If you really insist on storing it, why do need two queries? UPDATE attendance_records SET duration = timediff(...) WHERE ... - a single update would do the job
8. 2 points

## CSS with PHP

They aren't the same width because you don't have any sort of CSS in there that says anything about a width. It's not like the browser can read your mind about how you want it to appear... Have you tried giving the buttons a width?
9. 2 points

## Category Forum System

Not sure I would call a registration and login system less complex than threads and posts, but I guess it depends... I suggest you take a look at MariaDB's knowledge base section on database theory.
10. 2 points

## Naming Constraints

Don't do that. Not in the actual table at least. Some people recommend this stupidity to try and avoid name collisions in their queries (such as two tables have a Label column) but such issues can be easily handled using the table.column syntax in your query rather than cluttering up column names in the table. SELECT o.Label as o_label, s.Label as s_label FROM order o INNER JOIN status s ON s.Id=o.Status One of the applications I work on was original designed using a scheme like that where every column has a table specific prefix to it and it's super annoying (long names, broken autocomplete) for no real benefit. I've been slowly undoing that when I can and just giving the columns nice simple names. I'd also suggest just using the full table name in your constraint names rather than some alias. It makes things very clear when someone 6 months later needs to decipher things.
11. 2 points

## Need help to understand code piece.

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.
12. 2 points

## Help With Sub/Nested Query

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 | +------------+--------------+-------------+-------+----------+------------+-----------+-----------------+
13. 2 points

## Convert a string from 12hour time format to 24hour format

For example, https://www.php.net/manual/en/datetime.createfromformat.php https://www.php.net/manual/en/datetime.format.php
14. 2 points

## Limit to PHP array?

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>
15. 2 points

## Reading files in a directory

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>
16. 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
17. 2 points

## what wrong with this code?

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.
18. 2 points

## Php Registration code efficiency

It depends on the collation setting for the column.
19. 2 points

## is this one vulnerable ?

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.
20. 2 points

21. 2 points

## htmlspecialchars vs mysqli_real_escape_string

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.
22. 2 points

## Warning: readdir(): supplied argument is not a valid Directory resource

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/
23. 2 points

## want to change the qrcode details

Store the info that the user put in the original QR code. User retrieves and edits the data, then generates new QR code.
24. 2 points

## Postcode based delivery price

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
25. 2 points

## How to print largest even number in given string?

\$numbers = array(1,3,7,8,10,13); \$max = max(array_filter(\$numbers, function(\$v) { return \$v%2==0; })) ;
26. 2 points

## stuck block

You need to specify your units for the margin values. 161px, not just 161.
27. 2 points

## Check if User and Email already exists

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.
28. 2 points

## Echoing all \$_GET values

Just use var_dump if you just need to see what the array contains.
29. 2 points

## PHP Group Array Dealing With Duplicates

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 ];
30. 2 points

## Matching number elements

You may find my reply to one of your previous topics of interest here. (I sometimes ask myself why we bother)
31. 2 points

32. 2 points

## Is there a proper way to set this up?

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.
33. 2 points

## Table form input to output to 2nd page table

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>
34. 2 points

## ^= means what in PHP language?

For example \$a = 1010 \$b = 1111 \$b ^= \$a // Xor \$b = 0101 \$b ^= \$a // repeat Xor \$b = 1111 // \$b restored
35. 2 points

## Why Code Shows-Up in Block-Text Box ?

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.
36. 2 points

## \$_SERVER Array Variables

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.
37. 2 points

## how to create a tagging sys like in phpfreaks forum with tinymce

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
38. 2 points

## How to use while loop inside a concatenation?

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.
39. 2 points

## Start Session only if parameter exists

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?
40. 2 points

## Incorrect Total In Array

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>
41. 2 points

## Syntax checking

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.
42. 2 points

43. 2 points

## Prevent Blanks in Array

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; } }
44. 2 points

## sort multi-dimensional array by name

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']; } );
45. 2 points

## apply money_format to multiple values

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 )
46. 2 points

## absolute position

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!
47. 2 points

## mysql output lost without a "word"

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?
48. 2 points

## php mysql query with two conditions problem?

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.
49. 2 points

## How to handle form variables that aren't used

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>'; }
50. 2 points

## Delete HOST from CONF file with PHP

Commencing with test_config.txt as # interface eth0 subnet 10.0.10.0 netmask 255.255.255.0 { } host cm-test1 { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address 172.17.12.80; filename "srv-050.cfg"; } host cm-test2 { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address 172.17.13.119; filename "srv-042.cfg"; } host cm-instrumenti { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address 172.17.12.80; filename "srv-050.cfg"; } host cm-nimonmehmetaj { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address 172.17.13.119; 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 10.0.10.0 netmask 255.255.255.0 { } host cm-test1 { hardware ethernet 78:8d:f7:2b:bc:79; fixed-address 172.17.12.80; filename "srv-050.cfg"; } host cm-test2 { hardware ethernet 5c:35:3b:4d:73:4b; fixed-address 172.17.13.119; filename "srv-042.cfg"; }
This leaderboard is set to New York/GMT-04:00

Want to keep up to date with all our latest news and information?