Jump to content

Leaderboard


Popular Content

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

  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
    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>
  5. 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
  6. 2 points
    Not even close. This code... $product_details = "SELECT * FROM product WHERE product_id=".$_GET['product_id']; $prepare = $connect->prepare($product_details); $prepare->execute(); ...would embed any SQL injection code contained in the GET into the query which would then be executed. (Just as an unprepared query would) In the correct version the injection code would only be treated as data and not part of the SQL code.
  7. 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>
  8. 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
  9. 2 points
    $numbers = array(1,3,7,8,10,13); $max = max(array_filter($numbers, function($v) { return $v%2==0; })) ;
  10. 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.
  11. 2 points
    Just use var_dump if you just need to see what the array contains.
  12. 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 ];
  13. 2 points
    You may find my reply to one of your previous topics of interest here. (I sometimes ask myself why we bother)
  14. 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.
  15. 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
  16. 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.
  17. 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.
  18. 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.
  19. 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
  20. 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?
  21. 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>
  22. 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; } }
  23. 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']; } );
  24. 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 )
  25. 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!
  26. 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.
  27. 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>'; }
  28. 2 points
    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"; }
  29. 1 point
    If your problem is how to output tab separated data with column names /* SAMPLE DATA +-------+-------+---------+------------+ | empid | fname | lname | dob | +-------+-------+---------+------------+ | 1 | Peter | Smith | 1985-01-26 | | 2 | Paul | Hartley | 1973-12-02 | | 3 | Mary | Baker | 1980-04-11 | | 4 | Jane | Doe | 1990-11-28 | +-------+-------+---------+------------+ */ $res = $db->query("SELECT empid , fname , lname , dob FROM employee; "); echo '<pre>'; $row = $res->fetch(PDO::FETCH_ASSOC); echo join("\t", array_keys($row)) . "\n"; // headings do { echo join("\t", $row) . "\n"; // data } while ($row = $res->fetch()); echo '</pre>'; Which gives Similarly, if you want to write it to a csv file for export to Excel, then $res = $db->query("SELECT empid , fname , lname , dob FROM employee; "); $fp = fopen('AAA.csv', 'w'); $row = $res->fetch(PDO::FETCH_ASSOC); fputcsv($fp, array_keys($row), "\t"); // headings do { fputcsv($fp, $row, "\t"); // data } while ($row = $res->fetch());
  30. 1 point
    I saw nothing in the documentation to explain this, and I'm confident that this is both concrete5's fault and something that they should fix. For you, a) Create a CSS file for overriding this kind of stuff, define a new font-family like "Glyphicons Halflings 2" with correct srcs, and override .ccm-ui .glyphicon and whatever else to use the corrected font-family b) Fix the concrete5 files directly
  31. 1 point
    You're looking to avoid inline styles, correct? If so, the following line of code doesn't really change anything: $("input[tabindex = "+ind+"]").css('backgroundColor', clr); You'll still end up with the style attribute attached to each individual input tag. Instead, you could define classes (as suggested by Barand) for your colors. I would name the classes based on whatever each color represents. To apply the class names to the input fields, you could use the .addClass() method. More informaiton can be found here: https://api.jquery.com/addClass/ Basically, you would define a variable like you did for "clr". Maybe the variable would be named something like "clrClass", which would be set to whatever class names you decide to use. So basically, the following lines would be replaced with the new variable and class names: if(ind<3) clr = '#ff11aa'; if(ind>=3 && ind<6) clr = '#aaff11'; if(ind>=6 && ind<=9) clr = '#11aaff'; Then use your tabindex method like the following: $("input[tabindex = "+ind+"]").addClass(clrClass);
  32. 1 point
    I have no idea what you are starting with or what you want to finish with, so here is general method of dealing with a hierarchy. category table +--------+-----------+--------+ | cat_id | catname | parent | +--------+-----------+--------+ | 1 | Cat 1 | 0 | | 2 | Cat 2 | 0 | | 3 | Cat 3 | 0 | | 4 | Cat 1 1 | 1 | | 5 | Cat 1 2 | 1 | | 6 | Cat 2 1 | 2 | | 7 | Cat 2 2 | 2 | | 8 | Cat 2 3 | 2 | | 9 | Cat 3 1 | 3 | | 10 | Cat 1 1 1 | 4 | | 11 | Cat 1 1 2 | 4 | | 12 | Cat 2 3 1 | 8 | +--------+-----------+--------+ Code output Store arrays of items belonging to each parent in an array Starting with parent 0, list its children but each time you list a child you check if it is itself a parent and list its children. The recursive function does this for you. Code $sql = "SELECT cat_id, catname, parent FROM category"; $res = $db->query($sql); // // store arrays of items for each parent in an array // while (list($id, $name, $parent) = $res->fetch_row()) { $data[$parent][] = array('id'=>$id, 'name'=>$name); } echo '<pre>', print_r($data, 1), '</pre>'; // call the recursive function displayHierarchy($data, 0); // function to print a category then its child categories function displayHierarchy(&$arr, $parent) { if (isset($arr[$parent])) echo "<ul>\n"; foreach($arr[$parent] as $rec) { echo "<li>{$rec['name']}"; if (isset($arr[$rec['id']])) displayHierarchy($arr, $rec['id']); echo "</li>\n"; } echo "</ul>\n"; }
  33. 1 point
    What "it" do you want to send to paypal? Your form provides the input values; a query statement will save that data to the table. Then what? Send that very same data to paypal in some pre-defined format that Paypal has provided for you? So - follow that format, create the proper string/array/??? that the paypal API has instructed you to do, and deliver it the way the API tells you to do.
  34. 1 point
    you would initially create an array of the dates (Y-m-d date format) you want to highlight and store this array in a class property. at the point in the code where it is producing the css class selector and the cell content, you would use in_array() to find if $this->currentDate is one of the dates in the array. note: the author of that script should have produced a $today value in the Y-m-d format and just directly compared it with $this->currentDate in the existing css class selector code.
  35. 1 point
    Good job - you've figured out the syntax issues with your query (I really do mean that sincerely). Now, before anything else, please look into prepared statements as you're using $_GET variables directly in a MySQL query. Then please google the performance pitfalls of running a 'SELECT * ...' query. As for the coach name, the PHP array from a MySQL query has no idea what table each index of each row in the resultset came from, so the MySQL aliases you set up don't help the PHP output. In other words, the array indexes 'c.coachFirst' and 'c.coachLast' don't exist. The array indexes 'coachtFirst' and 'coachLast' should exist, however.
  36. 1 point
    What you posted has nothing to do with securing your web site. Validate the data first. Then use prepared statements.
  37. 1 point
    I asked because the data you posted does not match your code ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 | | $row[3] $row[8] The name is in index position 3, not 0. Also, use prepared statements and use PDO instead of mysqli (it makes life easier) $db = pdoConnect(); $db->exec("CREATE TABLE IF NOT EXISTS zeta ( id int not null auto_increment primary key, name varchar(30), physics int, maths int, chemistry int, biology int, sst int ) "); $stmt = $db->prepare("INSERT INTO zeta (name,physics,maths,chemistry,biology,sst) VALUES (?,?,?,?,?,?) "); $fp = fopen('zeta.csv', 'r'); while ($row = fgetcsv($fp)) { if ($row[3]=='Fields' || $row[3]=='') continue; $stmt->execute(array_slice($row,3)); } fclose($fp); Giving mysql> select * from zeta; +----+-------+---------+-------+-----------+---------+------+ | id | name | physics | maths | chemistry | biology | sst | +----+-------+---------+-------+-----------+---------+------+ | 1 | Name1 | 10 | 25 | 35 | 42 | 62 | | 2 | Name2 | 80 | 45 | 45 | 45 | 25 | | 3 | Name3 | 63 | 25 | 63 | 36 | 36 | | 4 | Name4 | 82 | 36 | 75 | 48 | 42 | | 5 | Name5 | 45 | 45 | 78 | 25 | 24 | | 6 | Name6 | 36 | 36 | 15 | 75 | 36 | | 7 | Name7 | 99 | 45 | 24 | 24 | 45 | | 8 | Name8 | 45 | 85 | 85 | 85 | 96 | +----+-------+---------+-------+-----------+---------+------+
  38. 1 point
    As Kicken has already said - if YOUR code is doing the updates that you are trying to monitor afterwards, then by all means alter your code to send you a notification via email or with a simple text file on your server that tells you when and what changed.
  39. 1 point
    From the docs: This means that the expression you want to be matched is a single, text (string) value. If you're using a prepared statement, in PHP, with PDO, that means a single question mark (?) or a single ":name" placeholder if you're going for named parameters. A quick demo example: <?php $db = new PDO("sqlite::memory:"); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->exec("CREATE VIRTUAL TABLE example USING FTS5 (a, b)"); $db->exec("INSERT INTO example (a, b) VALUES ('this is an amazing message', 'kittens are lovely')"); $db->exec("INSERT INTO example (a, b) VALUES ('this is a great message', 'dogs are also lovely')"); $db->exec("INSERT INTO example (a, b) VALUES ('this is a message', 'hamsters are best')"); $query = $db->prepare('SELECT * FROM example WHERE example MATCH ?'); $query->execute(array('(b: kittens) OR (a: great)')); $rows = $query->fetchAll(); print_r($rows); The above example outputs the two matching rows. Array ( [0] => Array ( [a] => this is an amazing message [b] => kittens are lovely ) [1] => Array ( [a] => this is a great message [b] => dogs are also lovely ) ) Hope that helps.
  40. 1 point
    You are building your foreign keys the wrong way round, EG ALTER TABLE `programs` ADD FOREIGN KEY (`program_id`) REFERENCES `deal_type` (`program_id`); should be ALTER TABLE `deal_type` ADD FOREIGN KEY (`program_id`) REFERENCES `programs` (`program_id`); program_id is the primary key of the programs table. When it appears in another table (such as deal_type) it is, therefore, a foreign key linking back the programs record. Also CREATE TABLE `deal_type` ( `deal_type_id` int AUTO_INCREMENT, `affiliate_id` int, `program_id` int, `affiliate_deal_id` int, PRIMARY KEY(deal_type_id,affiliate_id,program_id,affiliate_deal_id) -- really? PK should be deal_type_id );
  41. 1 point
    I haven't done any php DOM manipulation or parsing in quite some time and as far as I can recall I've not used the Simple HTML Dom Parser library (usually just use DOMDocument), but from the docs it looks this could be what you're looking for: foreach($html->find('li') as $li){ print("<p>{$li->first_child()->innertext}</p>"); } The first_child() of each list item element should be the anchor tag, and innertext should return the contents of that anchor tag. Unless I'm not reading something correctly - it's been a long day, so it's very possible that I am...
  42. 1 point
    If you have multiple web servers, no CDN, and no other form of centralized storage, putting files in a database is how you can distribute the files across all the servers. Another is replication - databases exchanging data with other databases. If you have multiple database servers running with replication already, putting files in there means those files are replicated as well. I disagree. I'm rather surprised to even hear that statement being made. But why? Why store them in multiple places? There's no need. A file is more than just binary data. Smart browsers can recognize the data from a PNG image and not confuse it with a JPEG image. But not all browsers are good at that, and sometimes file data looks similar across different types. Which means you need to know the MIME type for a file and send it to the browser. Which means identifying what it is, storing it in your database, and sending it through your PHP script. Additionally, a request for a file doesn't have to be for the entire file. If you had a large file, a browser could try to download it, and if that process fails (eg, internet disconnected) recover from where it left off. When it tries to continue it tells the server that it doesn't have to send the whole thing - only parts of it, or starting from a certain offset. Managing that on your own in PHP is annoying. Web servers can do all that for you.
  43. 1 point
    I don't understand what you are looking for. What "content" do you want? Are you asking how to handle the error? If so, you can try/catch the error and respond the way you want. From the manual Source: http://php.net/manual/en/pdo.errorcode.php
  44. 1 point
    Fastest way is with mysql's load xml statement
  45. 1 point
    The "type" in $_FILES is not reliable. If you want to check the type then you have to find out what the type is by yourself, like by using fileinfo. Or you can not check the type and rely on the extension instead.
  46. 1 point
  47. 1 point
    It depends so much on the XML, but what you saw there would probably resemble something similar to what you need.
  48. 1 point
    I don't know if this is close to your situation. Consider this scenarion. We have a set of customer accounts account table +------------+-----------+-------------+ | account_id | name | email | +------------+-----------+-------------+ | 1 | Company A | a@gmail.com | | 2 | Company B | b@gmail.com | | 3 | Company C | c@gmail.com | +------------+-----------+-------------+ When they buy from us we raise invoices and store the dates and amounts payment_due table +----------------+------------+------------+------------+--------+ | payment_due_id | account_id | invoice_id | due_date | amount | +----------------+------------+------------+------------+--------+ | 1 | 1 | 101 | 2018-04-15 | 100.00 | | 5 | 2 | 102 | 2018-04-15 | 200.00 | | 2 | 1 | 103 | 2018-05-15 | 100.00 | | 4 | 3 | 104 | 2018-06-01 | 300.00 | | 3 | 1 | 105 | 2018-06-15 | 100.00 | +----------------+------------+------------+------------+--------+ The customers make payments (hopefully) against these invoices payments_recd table +-----------------+------------+------------+------------+---------+ | payment_recd_id | account_id | invoice_id | recd_date | payment | +-----------------+------------+------------+------------+---------+ | 1 | 1 | 101 | 2018-04-15 | 100.00 | | 5 | 2 | 102 | 2018-06-15 | 150.00 | | 4 | 3 | 104 | 2018-06-10 | 300.00 | +-----------------+------------+------------+------------+---------+ After 30 days we want to sent a reminder that any unpaid moneys are due. After 60 days we send the "red frightener" letters. So a single query like this will show the overdue payments. SELECT a.name , a.email , d.due_date , d.invoice_id , due , IFNULL(paid, 0) as paid , due - IFNULL(paid, 0) as owed , DATEDIFF(CURDATE(), d.due_date) as days_overdue FROM account a INNER JOIN ( SELECT account_id , invoice_id , due_date , SUM(amount) as due FROM payment_due GROUP BY account_id, invoice_id ) d USING (account_id) LEFT JOIN ( SELECT account_id , invoice_id , SUM(payment) as paid FROM payment_recd GROUP BY account_id, invoice_id ) p ON d.invoice_id = p.invoice_id WHERE due_date <= CURDATE() - INTERVAL 30 DAY AND due > IFNULL(paid,0) Query results +-----------+-------------+------------+------------+--------+--------+--------+--------------+ | name | email | due_date | invoice_id | due | paid | owed | days_overdue | +-----------+-------------+------------+------------+--------+--------+--------+--------------+ | Company A | a@gmail.com | 2018-05-15 | 103 | 100.00 | 0.00 | 100.00 | 33 | | Company B | b@gmail.com | 2018-04-15 | 102 | 200.00 | 150.00 | 50.00 | 63 | +-----------+-------------+------------+------------+--------+--------+--------+--------------+ (You would also need to record when the two types of email were sent and use this information to prevent multiple copies being sent to customers.)
  49. 1 point
    Don't run queries inside loops - use joins and a single query EG. If you are wanting the totals of each camera brand at each location from this sample data location_id location_name hardware_id location_id harware_type_id brand +-------------+---------------+ +-------------+-------------+------------------+---------+ | 1 | Athens | | 1 | 1 | LAPTOP | ACER | | 2 | Birmingham | | 2 | 1 | LAPTOP | DELL | | 3 | Copenhagen | | 3 | 1 | CAMERA | NIKON | | 4 | Delhi | | 4 | 1 | CAMERA | NIKON | | 5 | Edinburgh | | 5 | 1 | CAMERA | NIKON | +-------------+---------------+ | 6 | 1 | CAMERA | CANON | | 7 | 1 | CAMERA | CANON | | 8 | 2 | LAPTOP | SONY | | 9 | 2 | LAPTOP | SONY | | 10 | 2 | CAMERA | MINOLTA | | 11 | 2 | CAMERA | LEICA | | 12 | 2 | CAMERA | LEICA | | 13 | 2 | CAMERA | CANON | | 14 | 2 | CAMERA | CANON | | 15 | 3 | PHONE | SONY | | 16 | 3 | PHONE | SONY | | 17 | 3 | CAMERA | SONY | | 18 | 3 | CAMERA | SONY | | 19 | 3 | CAMERA | SAMSUNG | | 20 | 3 | CAMERA | SAMSUNG | | 21 | 3 | CAMERA | SONY | | 22 | 4 | LAPTOP | HP | | 23 | 4 | LAPTOP | HP | | 24 | 4 | CAMERA | NIKON | | 25 | 4 | CAMERA | CANON | | 26 | 4 | CAMERA | CANON | | 27 | 4 | CAMERA | CANON | | 28 | 4 | CAMERA | CANON | | 29 | 5 | LAPTOP | HP | | 30 | 5 | LAPTOP | HP | | 31 | 5 | PHONE | SAMSUNG | | 32 | 5 | PHONE | SONY | +-------------+-------------+------------------+---------+ then you can replace all your code with a single query SELECT l.location_name , h.brand , COUNT(hardware_id) as stock FROM location l INNER JOIN hardware h USING (location_id) WHERE h.hardware_type_id = 'CAMERA' GROUP BY location_id, brand; +---------------+---------+-------+ | location_name | brand | stock | +---------------+---------+-------+ | Athens | CANON | 2 | | Athens | NIKON | 3 | | Birmingham | CANON | 2 | | Birmingham | LEICA | 2 | | Birmingham | MINOLTA | 1 | | Copenhagen | SAMSUNG | 2 | | Copenhagen | SONY | 3 | | Delhi | CANON | 4 | | Delhi | NIKON | 1 | +---------------+---------+-------+
  50. 1 point
    Hi again all, I think I'm going round in circles here trying to chose a method to populate a form with a chosen name. I also think with a well crafted reply could put me right and save more lost hours. Im new to this area of coding and you could say not practised. So with a few months till my next module I thought I would reaffirm my current knowledge by launching into a project. Lol, even the smallest of ideas can involve hours and hours of commitment. I think though in my current problem Im lost because there are so many answers and I cannot decide what or which to chose. The specification is creating the registration part of a website, New User, Edit User, Delete User - sounds simple but Im trying to make it work similar to a web app so I would expect a lot of interaction between the server and the client - There is a comboBox at the top populated with the 'profile_name' information. I want the user to select a name and the form underneath the combobox to fill with all the other information. as this is only a simple practice I only need a simple form with 5 or so fields per row profile_name,profile_alias,profile_email,profile_phone,profile_mobile in a table called 'profiles'. So Im thinking I will need an 'onchanged' event so when a new name is selected I can call a javascript function to go get the info for the rest of the form, this will be returned by the php script and I then populate the form. And this is where I get stuck - As I re-write the keywords to dig out more articles about moving variables between server and client and vice-versa, the more work I dig up for myself. I mean what is the best/easiest to do? I would have thought something like this would have a simple method or function alas no. Ajax, Json, Cookies, Headers, XML, ??? and so on. I ended up confused and looking at months of learning just to send/receive variables. I think asking is the best thing here, On a different note, do I really have to rewrite the entire form everytime someone selects a different name from the combobox? It would be best if the form remained static and the content of the html boxes changed. Is this possible? and do I have my understanding of the relationship between client and php server wrong here? I was thinking the server had some control over data but if I echo the php results as said in some of the articles then my form is refreshed with a blank screen. I suppose I could change the php to rebuild the form but am I again choosing the hardest method? Thanks in advance, Phil
This leaderboard is set to New York/GMT-05:00
  • Newsletter

    Want to keep up to date with all our latest news and information?
    Sign Up
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.