Jump to content


Popular Content

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

  1. 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) 😊
  2. 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
  3. 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.
  4. 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>
  5. 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.
  6. 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
  7. 2 points
    $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
  8. 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.
  9. 2 points
    Just use var_dump if you just need to see what the array contains.
  10. 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 ];
  11. 2 points
    You may find my reply to one of your previous topics of interest here. (I sometimes ask myself why we bother)
  12. 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.
  13. 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
  14. 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.
  15. 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.
  16. 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.
  17. 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
  18. 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?
  19. 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>
  20. 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; } }
  21. 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']; } );
  22. 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 )
  23. 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!
  24. 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?
  25. 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.
  26. 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>'; }
  27. 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
  28. 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"; }
  29. 1 point
    That all depends on the person. Some will be fine, some won't, others will we be somewhere in between. To be honest, you'll never make everyone happy. The best you can do is try something and see how things go. If you're not getting the results you want, you can always adjust. Depending on how big your audience is and how much time you have for testing, you could develop 2 separate options of the sign-up process. One would require the users to validate the email address. The other would skip the validation. You could then use A/B testing to see which option results in more website signups. More information about A/B testing can be found here: https://en.wikipedia.org/wiki/A/B_testing
  30. 1 point
    Did you try anything yourself? Like https://duckduckgo.com/?q=php+qr+code+reader
  31. 1 point
    Remove the period from in front of your relative paths. The location of the files should be relative to your site document root.
  32. 1 point
    When you receive the form the first time (and every time after that) create an array of the 'values' that were checked. When you output the form again, as you build the html code check that array for the values that need to be re-checked and check them as they are built. easy-peasy.
  33. 1 point
    They have a big database of locations. Probably purchased from and/or subscribed to a service that tracks stuff like that so they don't have to try to stay up to date themselves. They know the latitude and longitude of an address, also probably from a third-party service (eg, Google Maps). A postcode has a location too, though it's obviously not quite as precise. Then they can do some pretty simple math to estimate the distance between the two points.
  34. 1 point
  35. 1 point
  36. 1 point
    Yeah, the same. You could send GETs to one place and POSTs to another, if you wanted, if there was some technical reason to do so (which isn't to say I couldn't imagine some), but normally you wouldn't.
  37. 1 point
    Then try display:inline-block with vertical-align:top.
  38. 1 point
    Turns out this is even easier than I thought. My configuration has two http servers on the same machine where one is mainwebsite.com and it makes curl requests to the other which is api.mainwebsite.com . Now, I am just sending the Slim Request to Guzzle. Originally, I sent Slim's Request with its original host (mainwebsite.com), and my $_SESSION variable kept on getting deleted. I am assuming some sort of web browser or PHP security feature? Any thoughts? Why wasn't the base_uri added to \GuzzleHttp\Client's constructor not being applied? Regardless, I was able to change the host as shown below and all now works. To use less code, I am using a loop to apply the headers to the response. Think I should hard code it like $slimResponse->withHeader('header1', $guzzleResponse->getHeader('header1'))->addMoreHeaders()->thenAddStatusAndBody()? This (I think) will eliminate needing to clone all the responses, however, will will require me to have code for each Content-Type to determine which headers are returned. But maybe that is good and I shouldn't blacklist headers as I am doing but whitelist them? If this approach is acceptable, what other headers should I blacklist? Thanks public function proxy(\Slim\Http\Request $slimRequest, \Slim\Http\Response $slimResponse):\Slim\Http\Response { //Forwards Slim Request to another server and returns the updated Slim Response. $slimRequest=$slimRequest->withUri($slimRequest->getUri()->withHost($this->getHost(false))); //Change slim's host to API server! try { $httpClient = new \GuzzleHttp\Client(['base_uri' => "https://api.mainwebsite.com"]); //Will use injection, and just shown this way ease $guzzleResponse=$httpClient->send($slimRequest); $excludedHeaders=['Date', 'Server', 'X-Powered-By', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Headers']; $headerArrays=array_diff_key($guzzleResponse->getHeaders(), array_flip($excludedHeaders)); foreach($headerArrays as $headerName=>$headers) { foreach($headers as $headerValue) { $slimResponse=$slimResponse->withHeader($headerName, $headerValue); } } return $slimResponse->withStatus($guzzleResponse->getStatusCode())->withBody($guzzleResponse->getBody()); } catch (\GuzzleHttp\Exception\RequestException $e) { if ($e->hasResponse()) { $guzzleResponse=$e->getResponse(); return $slimResponse->withStatus($guzzleResponse->getStatusCode())->withBody($guzzleResponse->getBody()); } else { return $slimResponse->withStatus(500)->write(json_encode(['message'=>'RequestException without response: '.$e->getMessage()])); } } }
  39. 1 point
    Not that I'm aware of. With that said, docker only uses the .env file to set variables that are used during the docker-compose pre-processing stage. You also might be well advised to have some directory structure where your laravel app code is not in the root of the project where it would conflict with docker files. I would also suggest taking a look at how Laradock does things.
  40. 1 point
    If you copy paste the URL from the browser you will see that the space is transformed to %20. You should not have the spaces in the first place. Spaces are considered unsafe according to the RFC.
  41. 1 point
    You are missing the point. The PHP script is working with respect to MySQL. But it is not outputting a valid HTML page that the C++ code can interpret. I highly suspect that is what the -11 is trying to tell you.
  42. 1 point
    They will both submit to the same location: the current URL. The only meaningful difference between them is that the first fills in a provided username while the second does not. I would recommend the one that behaves the way you want it to behave.
  43. 1 point
    Have read of the PHP Migration Guides
  44. 1 point
  45. 1 point
    There's a smarter solution to this. One that doesn't involve queries in a loop. Get all the events for the month. Before the loop. SELECT id, name, date_time, DAYOFMONTH(date_time) AS day FROM events WHERE date_time BETWEEN '2018-11-01 00:00:00' AND '2018-11-31 23:59:59' ORDER BY date_time The date range is $year_month-01 midnight through $year_month-31 (doesn't matter if the month has <31 days) just before midnight. And the list is sorted by the date. Go through the results and stick it all into a 2D array according to the "day" value. Then your main loop can check the array to see if it has any events.
  46. 1 point
    In addition to @ginerjm's advice Separate your php from your html as much as possible, avaiding your spaghetti-like code structure. Do your php processing first, followed by the html output Don't use "select star", specify the fields you want. Don't put user privided data directly into your query strings, use prepared statements I have rewritten your page to illustrate these points <?php $tdata = ''; $where = []; $whereclause = ''; $params = []; $class = $_GET['class'] ?? ''; $sex = $_GET['sex'] ?? ''; if (isset($_GET['todo']) && $_GET['todo']=='search') { if ($class) { $where[] = "class = ?"; $params[] = $class; } if ($sex) { $where[] = "sex = ?"; $params[] = $sex; } if ($where) { $whereclause = " WHERE " . join(' AND ', $where); } } $stmt = $dbo->prepare("SELECT name , class , session_based , mark , sex , phone , date FROM student $whereclause"); $stmt->execute($params); foreach ($stmt as $row) { $tdata .= "<tr><td>" . join('</td><td>', $row) . "</td></tr>\n"; } function classOptions($dbo, $current='') { $opts = ''; $res = $dbo->query("SELECT DISTINCT class FROM student"); foreach ($res as $r) { $sel = $r['class']==$current ? 'selected' : ''; $opts .= "<option $sel value='{$r['class']}'>{$r['class']}</option>\n"; } return $opts; } function sexOptions($dbo, $current='') { $opts = ''; $res = $dbo->query("SELECT DISTINCT sex FROM student"); foreach ($res as $r) { $sel = $r['sex']==$current ? 'selected' : ''; $opts .= "<option $sel value='{$r['sex']}'>{$r['sex']}</option>\n"; } return $opts; } ?> <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> <meta name="author" content="Barand"> <meta name="creation-date" content="09/23/2018"> </head> <body> <form method='get' action=''> <input type="hidden" name="todo" value="search"> Class <select class="form-control" name="class"> <option value=''>Any Class</option> <?=classOptions($dbo, $class)?> </select> <br> Sex <select class="form-control" name="sex"> <option value=''>All</option> <?=sexOptions($dbo, $sex)?> </select> <br> <input type="submit" value="Search"> <input type="reset" value="Reset"> </form> <br><br> <div class="container"> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th class="col-md-1">Name</th> <th class="col-md-1">Class</th> <th class="col-md-1">Session Based</th> <th class="col-md-1">Mark</th> <th class="col-md-2">Sex</th> <th class="col-md-2">Phone</th> <th class="col-md-2">Date</th> </tr> </thead> <tbody> <?=$tdata?> </tbody> </table> </div> </body> </html>
  47. 1 point
    try echo "<p><a href='$url'>Link here</a></p>";
  48. 1 point
    The domain name as seen in the browser isn't matching one of the site configurations used by Apache/nginx. Either there is no configuration, or it's not enabled, or Apache/nginx haven't been restarted since adding the configuration, or the domain names don't match.
  49. 1 point
    I would write it like this using IN or rather in this case NOT IN: AND (college NOT IN ('Wabash','DePauw')) Does that give you what you are after? I find it a lot easier to read. Hope that helps, Jon
  50. 1 point
    This is an extremely complicated question to answer and impossible with the minimal information you provided. While there are certainly development implications to your question, there could be an equal amount of DevOps capability required. The general term for setup and configuration of an environment or service, is called "Provisioning". Certainly you can create a series of scripts that do this for you and put an environment in a known state. There are all sorts of DevOps tools out there like Chef, Puppet, Salt and Ansible that do "orchestration" of environments and are built to handle whatever you might need. There's also Docker, which has a lot of features that could handle the isolation of separate computing environments. Typically the way this is done is that you have not only a copy of the database, but a separate copy of the code. While that is not strictly necessary, and adds to the redundancy, it also provides isolation of an environment. So you could have customizations or modules for customer A, that customer B does not have. Otherwise you will have to have some separate bootstrapping code that reads a separate environment for each person. In general, yes, one way to handle this is to have separate virtual host configurations and use a subdomain. user1.yourdomain.com user2.yourdomain.com Each user gets a different directory, with different db user/pw and database name. Doing this well, writing all the code to make it happen, and testing is all additional work, but by the same token, you will have extra code and complexity involved in every database query you have if you need to segment all your data by user. Ultimately, if this could develop into a business where you are providing "Software as a service" then it's probably better to take the DevOps approach and separate the environments, but then you have more system administration to deal with. If it's probably just going to be these 3 guys, you are probably better off just maintaining one system configuration and putting in the code that relates all the data to a specific user.
This leaderboard is set to New York/GMT-04: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.