Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 06/04/2022 in all areas

  1. or... $res = $pdo->query("SELECT `option`, total FROM vote"); $data = $res->fetchAll(); $votes_cast = array_sum( array_column($data, 'total') ); foreach ($data as $r) { printf ("%s has %d votes (%0.1f %%)<br>", $r['option'], $r['total'], $r['total']*100/$votes_cast); }
    2 points
  2. Depending on what it is you're trying to do with the data, there are several ways to change a field. You can set up an accessor or mutator or use a query scope, for instance. Query scope sounds like what you're looking for, although should worse comes to worst you could just write a trait and use it on your model instances where needed.
    2 points
  3. Personally I always use lowercase for var names. Never have any confusion that way.
    1 point
  4. it means only write code that contributes something useful to what your application is trying to accomplish. for connection errors and errors from query(), prepare(), and most execute() calls (except for duplicate or out of range errors when inserting/updating user submitted data), there's nothing the visitor to your site can do to recover from the error, they are due to programming mistakes or a database server that's not running, ... therefore, there's no point in writing any code for these cases. just let php catch the exceptions in these cases and display (when developing code/query(ies)) or log (when on a live/public server) the actual error information, so that you, the programmer/developer, will know when these type of errors are occurring, so that you can find and fix what's causing them. the only types of database errors that the visitor to a site can do anything about are when inserting/updating duplicate or out of range visitor submitted data. this is the only case where having database error handling code in your application will do anything useful. you would catch the database exception, test the error number, setup a message telling the visitor exactly what was wrong with the data that they submitted, so that they can potentially submit a different value that will succeed.
    1 point
  5. You are missing the TRY for your CATCH
    1 point
  6. That's what confused me - your video of exactly what you did didn't show that bit. They aren't necessary as that is what your included code does. You don't need pdoConnect(). Your "connect.php" defines the $pdo connection varaiable. My db_inc.php contains const HOST = 'localhost'; const USERNAME = '????'; const PASSWORD = '????'; const DATABASE = 'test'); // default db function pdoConnect($dbname=DATABASE) { $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $db; } function myConnect($database=DATABASE) { mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); $db = mysqli_connect(HOST,USERNAME,PASSWORD,$database); $db->set_charset('utf8'); return $db; } I use the pdoConnect() and myConnect() functions to create a connection as I have dozens of databases and, depending on who I am helping, I may need a PDO or a mysqli connection. This lets me use the same include file yet allows flexibility in my connections.
    1 point
  7. the posted code contains a php syntax error (a closing ?> tag inside the function definition) and doesn't run at all, so that's not the actual code producing that error. a few possibilities why the function definition is not present in the current program scope - the function definition is inside of a conditional statement, and so isn't defined until the code where that statements is at has been executed and the conditional statement is true. the function definition is inside of another function definition, and so isn't defined until the parent function has been called. the function definition is being required (you should use require for things your program just have) using a url, not a file system path, and is not in the same instance of your program as the function call. after you correct the php syntax error, the posted code produces an undefined constant error because the function call is before the point where the constants are defined. it would take seeing the actual code producing the error to help with what is wrong with it.
    1 point
  8. Just an FYI: Pretty pictures are nice and all but we cant paste an image into our editors. In the future, please post actual code using the code tags on the post menu <>. 😃
    1 point
  9. gmail has recently stopped accepting emails that are being sent by unknown, unauthenticated email clients/systems, such as a sending mail server at some random web hosting. you must generate an OAuth token and use it to authenticate when sending to gmail. see the following post and thread it is in - prior to this, you were required to use smtp authentication against your gmail mailbox, which the php mail() function does not support, so you need to use either the phpmailer or swiftmailer class in any case.
    1 point
  10. as a separate post. this code is typical misuse of OOP. someone took a few lines of main code, building and executing an insert query, threw a class definition around it, then to make it 'work' had to add $this-> in front of everything, add a bunch more code to build the input properties, code to instantiate the class, code to call the various methods, code (if any) to test the returned values, and code (if any) to use the output properties. if this method gets called and there isn't a database connection (what the first few lines of code are testing), it means that the connection code doesn't have error handling that would have stopped the whole database dependent application from being executed upon a connection error, and for the rare cases where a connection was successfully made, but lost during execution of the code, the fatal php error that would have occurred when the non-existent connection was used should be getting logged to let you know what type of problems are occurring. edit: since the code is just returning in this case, and it's doubtful that the returned value is causing any sort of logging/reporting to occur, you will never know if this is the cause of the missing inserted data. this brings up an additional point for debugging the problem. php's error_reporting should be set to E_ALL and log_errors should be set to ON, preferably in the php.ini on the system, so that all php errors will get reported and logged. if the php/web server error log is empty, either this is not the case or the log file settings are not setup.
    1 point
  11. It's unfortunate, for someone who wants to minimize their code, that you have used a data model which considerably increases your code. +---------------------------------------------------------------+ +--------------------------------------------------+ | | | | | YOUR DATA | | MY DATA | | | | | +---------------------------------------------------------------+ +--------------------------------------------------+ rifles item +----+------------------+------+------+ +----+---------------------+------+------+--------+ | id | rifleName | em | gm | | id | itemname | em | gm | cat_id | +----+------------------+------+------+ +----+---------------------+------+------+--------+ | 1 | .308 Bolt action | 225 | 1350 | | 1 | .308 Bolt action | 225 | 1350 | 1 | | 2 | 7mm magnum | 300 | 1575 | | 2 | 7mm magnum | 300 | 1575 | 1 | | 3 | .243 LeverAction | 215 | 8725 | | 3 | .243 LeverAction | 215 | 8725 | 1 | +----+------------------+------+------+ | 4 | 6ft Longbow | 135 | 1120 | 2 | bows | 5 | 5ft Flatbow | 235 | 1345 | 2 | +----+-------------+------+------+ | 6 | Recurve | 215 | 2525 | 2 | | id | bowName | em | gm | | 7 | Purdy 12 bore | 135 | 1120 | 3 | +----+-------------+------+------+ | 8 | Beretta 12 bore | 235 | 1345 | 3 | | 1 | 6ft Longbow | 135 | 1120 | | 9 | Small bore rook gun | 215 | 2525 | 3 | | 2 | 5ft Flatbow | 235 | 1345 | | 10 | Glock 9mm | 125 | 1050 | 4 | | 3 | Recurve | 215 | 2525 | | 11 | Colt .38 | 200 | 1175 | 4 | +----+-------------+------+------+ | 12 | Derringer .22 | 115 | 3125 | 4 | shotguns +----+---------------------+------+------+--------+ +----+---------------------+------+------+ | id | shotgunName | em | gm | category +----+---------------------+------+------+ +--------+----------+ | 1 | Purdy 12 bore | 135 | 1120 | | cat_id | cat_name | | 2 | Beretta 12 bore | 235 | 1345 | +--------+----------+ | 3 | Small bore rook gun | 215 | 2525 | | 1 | Rifles | +----+---------------------+------+------+ | 2 | Bows | pistols | 3 | Shotguns | +----+---------------+------+------+ | 4 | Pistols | | id | pistolName | em | gm | +--------+----------+ +----+---------------+------+------+ | 1 | Glock 9mm | 125 | 1050 | | 2 | Colt .38 | 200 | 1175 | | 3 | Derringer .22 | 115 | 3125 | +----+---------------+------+------+ +---------------------------------------------------------------+ +--------------------------------------------------+ | | | | | YOUR CODE | | MY CODE | | | | | +---------------------------------------------------------------+ +--------------------------------------------------+ A separate block of code for each category Single block of code for all categories (For 20 categories that's a 95% reduction in coding time) If you add 4 more categories you have to write If I add more categories the code remains unchanged 4 more code blocks My code's output My code for you to try <?php require 'db_inc.php'; // contains db credentials and connection function code $pdo = pdoConnect('javanoob'); // connect setting javanoob as default db // YOU WILL NEED YOUR OWN PDO CONNECT CODE ################################################################################ ## ## ## Handle AJAX request when + button is clicked ## ## ## ################################################################################ if (isset($_GET['ajax'])) { if ($_GET['ajax'] == 'newrow') { exit( tableItemRow($pdo, $_GET['catid']) ); } } ################################################################################ ## ## ## Query db item table to get all the categrories for the output table ## ## ## ################################################################################ $res = $pdo->query("SELECT id , itemname , em , gm , cat_id , cat_name FROM item i JOIN category c USING (cat_id) WHERE cat_id IN (1,2,3,4) ORDER BY cat_id, itemname "); $data = []; foreach ($res as $r) { if (!isset($data[$r['cat_id']])) { $data[$r['cat_id']] = [ 'catname' => $r['cat_name'], 'items' => [] ]; } $data[$r['cat_id']]['items'][] = array_slice($r, 0, 4); } ################################################################################ ## ## ## Loop through the data array to build the output table ## ## ## ################################################################################ $tdata = ''; foreach ($data as $cid => $cdata) { $tdata .= "<tbody data-cat='$cid'> <tr> <td class='cat-title' colspan='4'> {$cdata['catname']} <div class='addmore' data-cat='$cid'><i class='fa fa-plus'></i></div> </td> </tr> <tr> <td><select class='item-menu' name='item[]' onchange='item_menu_changed(this)'> <option value='' data-em='0' data-gm='0'>Choose from {$cdata['catname']}</option> "; foreach ($cdata['items'] as $row) { $tdata .= "<option value={$row['id']} data-em='{$row['em']}' data-gm='{$row['gm']}'>" . htmlspecialchars( $row["itemname"] ) . "</option>"; } $tdata .= "</select></td> <td class='em ca'>0</td> <td class='gm ca'>0</td> </tr> </tbody>"; } /******************************************************************************* * generate html for additional output row * * @param PDO $db * @param int $cat_id */ function tableItemRow(PDO $db, $cat_id) { $res = $db->prepare("SELECT id , itemname , em , gm , cat_name FROM item i JOIN category c USING (cat_id) WHERE cat_id = ? ORDER BY itemname "); $res->execute([$cat_id]); $opts = ''; $data = $res->fetchAll(); foreach ($data as $row) { $opts .= "<option value={$row['id']} data-em='{$row['em']}' data-gm='{$row['gm']}'>" . htmlspecialchars( $row["itemname"] ) . "</option>"; } $rowdata = "<tr> <td><select class='item-menu' name='item[]' onchange='item_menu_changed(this)'> <option value='' data-em='0' data-gm='0'>Choose from {$data[0]['cat_name']}</option>" . $opts . "</select></td> <td class='em ca'>0</td> <td class='gm ca'>0</td> </tr>"; return $rowdata; } ?> <!--#ffa500--> <!DOCTYPE html> <html lang='en'> <head> <title>sample</title> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> $().ready( function() { $(".addmore").click( function() { let cid = $(this).data("cat") $.get ( "", {"ajax":"newrow", "catid":cid}, function(resp) { $("tbody[data-cat="+cid+"]").append(resp) }, "TEXT" ) }) }) function item_menu_changed(menu) { // // update values in current row // let therow = $(menu).parent().parent() let em = parseInt($(menu).find("option:selected").data("em")) let gm = parseInt($(menu).find("option:selected").data("gm")) $(therow).find(".em").html(em) $(therow).find(".gm").html(gm) // // calculate totals // let totem = 0 let totgm = 0 $(".em").each(function(k,v) { totem += parseInt($(v).html()) }) $(".gm").each(function(k,v) { totgm += parseInt($(v).html()) }) $("#totem").html(totem) $("#totgm").html(totgm) } </script> <style type='text/css'> body { font-family: calibri, sans-serif; } select { background-color: black; color: white; font-size: 14pt; width: 100%; padding: 4px; border: none; } table { background-color: black; color: white; border-collapse: collapse; border-color: #ffa500; margin: 50px auto; } th { font-size: 20pt; color: #ffa500; } td { font-size: 14pt; } .cat-title { background: linear-gradient(to right top, #ffa500, black); font-size: 20pt; font-weight: 600; color: black; padding: 4px 2px 4px 16px; width: 600px; } .ca { text-align: center; } .addmore { width: 20px; height: 20px; display: inline-block; padding: 2px; text-align: center; font-size: 14pt; background: linear-gradient(to right top, #666, #FFF, #666); color: black; border: 1px solid #ffa500; float: right; } </style> </head> <body> <table border='1'> <tr><th>Items</th><th>em</th><th>gm</th><th>&plus;</th></tr> <?= $tdata ?> <tbody> <tr style='border-top: 8px solid #ffa500;'> <th>Totals</th> <td class='ca' id='totem'>0</td> <td class='ca' id='totgm'>0</td> <td>&nbsp;</td> </tr> </tbody> </table> </body> </html> and the SQL code to create the test data tables -- -- Table structure for table `category` -- DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `cat_id` int(11) NOT NULL AUTO_INCREMENT, `cat_name` varchar(45) DEFAULT NULL, PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO `category` VALUES (1,'Rifles'),(2,'Bows'),(3,'Shotguns'),(4,'Pistols'); -- -- Table structure for table `item` -- DROP TABLE IF EXISTS `item`; CREATE TABLE `item` ( `id` int(11) NOT NULL AUTO_INCREMENT, `itemname` varchar(50) DEFAULT NULL, `em` int(11) DEFAULT NULL, `gm` int(11) DEFAULT NULL, `cat_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_item_cat_id` (`cat_id`) ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8; INSERT INTO `item` VALUES (1,'.308 Bolt action',225,1350,1),(2,'7mm magnum',300,1575,1),(3,'.243 LeverAction',215,8725,1),(4,'6ft Longbow',135,1120,2),(5,'5ft Flatbow',235,1345,2),(6,'Recurve',215,2525,2),(7,'Purdy 12 bore',135,1120,3),(8,'Beretta 12 bore',235,1345,3),(9,'Small bore rook gun',215,2525,3),(10,'Glock 9mm',125,1050,4),(11,'Colt .38',200,1175,4),(12,'Derringer .22',115,3125,4);
    1 point
  12. Ok, you got my respect for that. When I think about it, I think you're right. And now I even don't dare to say more, not even ask another question ( 😉 ). I feel really stupid. I saw the solution. But (as we say in Norway in Norwegian of course) I just had to shit on my own leg. I feel so embarrassed. Before I was never afraid to try new things or find solutions. It must be my age. I am getting older and the Alzheimer's is closing up on me. Requinix, SORRY FOR ASKING STUPID SELF EXPLAINED QUESTIONS. But, thank you for listening
    1 point
  13. Alternatively $str = 'FSOWPDHJEOSKJ3D2DF5R3FG51'; echo join('-', str_split($str, 5)); //--> FSOWP-DHJEO-SKJ3D-2DF5R-3FG51
    1 point
  14. echo "<a class='knil' href='high.php?id={$game['high']}'>{$game['high']}</a>";
    1 point
  15. An optional parameter would be like public static function render($post, $withPost = true) { which will default to true if not provided. You would then use $withPost to decide whether to do that ->push or not.
    1 point
  16. Oh dear. If you've got the money to buy Windows Server Datacenter then you've got the money to hire an IT person whose job it would be to deal with these matters.
    1 point
  17. Don't use a redirect. Half of the point of a 404 page is that it returns a 404, and using a redirect makes it do something different. Why not just change the 404.php to be this new page? Wouldn't that be easier?
    1 point
  18. the intended purpose of having the database name as a call-time parameter is so that you can make multiple connections, each with their own selected database. for this to work, $DBName must be removed from the global ... ; line of code, so that the call-time parameter will be the value that gets used. if there's ever a case of directly making an instance of the DBSQL class, yes. the line $this->DBSQL($DBName); would need to be changed to parent::__construct($DBName); as well.
    1 point
  19. You are grouping by jobId so you will get one row for each job. The max(quoteId) should be OK (as that is a aggregation) and also jobName and clientId from the job record, but the remaining values (like version and currency) could be arbitrarily selected from from any quote record associated with jobId.
    1 point
  20. Only out the maincat when it changes to a new value. set prevcat = maincat foreach record start new row if maincat != prevcat output maincat set prevcat = maincat else output blank endif output subcat end row end foreach
    1 point
  21. no. do not update quantities or delete data to accomplish this. databases are for recording information. by updating/deleting data, you lose an audit trail that would let you know if a programming mistake, an accidental key was pressed, or nefarious activity changed a value. you would INSERT data for every order/transaction that affects a value. a sale would insert a row into an order/transaction table with a 'type' indicating it is for a sale, then insert row(s) into an order_item table for each item that was sold with the order_id, item_id, and quantity. to void a sale, you would insert another row into the order/transaction table with a 'type' indicating it is for a void/return, with a reference to the original order_id, then insert row(s) into the order_item table, with a negative quantity for the items that are returned and will be restocked (some of the items might have been kept, some might have been damaged, and won't be restocked.) to get the total quantity you would just SUM() the quantities per item_id.
    1 point
  22. Have you considered a common format such as ".csv" file EG First_Name,Last_Name,Sex,Fruits Scott,Chegg,male,"orange, berry" Laura,Norder,female,"apple, orange" code if($_SERVER['REQUEST_METHOD']=='POST'){ if (!file_exists('file.txt')) { file_put_contents('file.txt', "First_Name,Last_Name,Sex, Fruits\n"); // write header line } $file=fopen("file.txt", "a"); $record = [$_POST['firstName'], $_POST['lastName'], $_POST['sex'], join(',', $_POST['fruit'])]; fputcsv($file, $record); }
    1 point
  23. Define it as id int not null auto_increment primary key Remove "id" and its value from the insert query - let mysql handle it.
    1 point
  24. If it isn't reporting errors it may be logging them. Check the error log.
    1 point
  25. Perhaps echo '<pre>' . htmlentities(' <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> ..... </url> <url> ..... </url> <url> ..... </url> <url> ..... </url> </urlset> ') . '</pre>';
    1 point
  26. Your html code: <?php echo " <tr> <td><b><label for='firstNum1'>$coingecko_name</label></b></td> <td style='color:#EFE1CE'>$COINGECKO_ID</td> <td style='color:#EFE1CE'>{$checkSqlRow["COINGECKO_LEGIT"]}</td> <td style='color:#EFE1CE'>$coingecko_rank</td> "; A few var names that are not defined (to us). And a bit cleaner just by using php to do your output. Now - what is the problem? You did not tell us. And where is your attempt to make some kind of selection of the image you want to be chosen? BTW. Note that I removed your use of the deprecated 'font' tag. Your use of CSS later on is much preferred nowadays.
    1 point
  27. On a typical Debian/Ubuntu system, website stuff is at /var/www. There's nothing wrong with putting their home directories in there - tons of system accounts do things like that, just check /etc/passwd. And make sure you've disabled logins for those users.
    1 point
  28. The original line was $V341be97d = preg_replace('/\^([^\^<])/e', "'`' . \$V70dda5df[ord('\\1') % 8]", $V341be97d); That was updating $V341be97d, on the left-hand side of the = assignment, with a new value coming from preg_replace. Your updated version preg_replace_callback('/\^([^\^<])/', fn($matches) => '`' . $V70dda5df[ord($matches[1]) % 8], $V341be97d); changed the preg_replace into a preg_replace_callback but it lost the $V341be97d= that was there before. Still need it, otherwise whatever this replacement was designed to handle (namely the ^0s and ^7s and such that you're now seeing) won't happen.
    1 point
  29. But I like that the user is preparing himself to practice good querying.
    1 point
  30. Feeling magnanimous today, here's the function I use to connect: function PDOConnect($l_dbname=NULL, $l_msg=null, $l_options=null) { if ($l_options == null) { // set my default options $l_options = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_FOUND_ROWS => true, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC); } if ($l_dbname == null) $host="mysql:host=localhost;charset=utf8"; else $host="mysql:host=localhost;dbname=$l_dbname;charset=utf8"; $uid = "xxx"; $pswd = "yyy"; try { $pdo = new PDO($host, $uid, $pswd, $l_options); } catch (PDOException $e) { if (strtoupper($l_msg) == "SHOWMSG") echo "Fatal Error<br>Failed to connect to mysql via PDO. PDO Error msg is:<br>".$e->getMessage(); else echo "Fatal Error<br>Possible bad dbname?<br>Failed to connect to database server. Sensitive error msg may be viewed with additional parm to call to PDOConnect(dbname,'showmsg')"; return false; } if (!$pdo) return false; else // all worked - return handle to pdo connection. return $pdo; } This assumes that you will want the assoc array format returned from your queries. You can easily override that in your fetch calls if you need to do something different at that point. Stick this in some 'php' folder outside of your web tree so that only php scripts (and not html/web pages) can see it. Then simply call it ONCE in your script by: $pdo = PDOConnect($dbname);
    1 point
  31. It's a shame the code is open-source but extremely unreadable... I'll use those two as an example. Moving away from /e goes basically like: 1. Switch the function to preg_replace_callback and drop the /e flag, obviously. 2. Change the second argument (a string) to be a function following the template function($matches) { return ___; } where you put in there the replacement string but minus the outer quotes. 3. Replace "\\1" with $matches[1], "\\2" with $matches[2], and so on, and correct any issues with the PHP syntax. So this preg_replace("/\+([\x01-\x7F])#/e", "chr(ord('\\1') + 127)", $V341be97d) starts as preg_replace_callback("/\+([\x01-\x7F])#/", function($matches) { return chr(ord('\\1') + 127); }, $V341be97d) and you replace the '\\1' string to get preg_replace_callback("/\+([\x01-\x7F])#/", function($matches) { return chr(ord($matches[1]) + 127); }, $V341be97d) What you have now is quite a bit different to the point that it won't actually work correctly. If you're using PHP 7.4 or later, you can simplify the function syntax if you want by using a function shorthand: function(...) { return ... } can be shortened to fn(...) => ... preg_replace_callback("/\+([\x01-\x7F])#/", fn($matches) => chr(ord($matches[1]) + 127), $V341be97d) The second one preg_replace("/#(#|[0-9a-f]{2})/ie", "'\\1' == '#' ? '#' : chr(hexdec('\\1'))", $V341be97d) is similar preg_replace_callback("/#(#|[0-9a-f]{2})/i", function($matches) { return '\\1' == '#' ? '#' : chr(hexdec('\\1')); }, $V341be97d) but has a little more to replace, creating preg_replace_callback("/#(#|[0-9a-f]{2})/i", function($matches) { return $matches[1] == '#' ? '#' : chr(hexdec($matches[1])); }, $V341be97d) or with the PHP 7.4 shorthand, preg_replace_callback("/#(#|[0-9a-f]{2})/i", fn($matches) => $matches[1] == '#' ? '#' : chr(hexdec($matches[1])), $V341be97d) The latest one you're working on preg_replace('/\^([^\^<])/e', "'`' . \$V70dda5df[ord('\\1') % 8]", $V341be97d) goes very much the same way preg_replace_callback('/\^([^\^<])/', function($matches) { return '`' . \$V70dda5df[ord('\\1') % 8]; }, $V341be97d) preg_replace_callback('/\^([^\^<])/', function($matches) { return '`' . \$V70dda5df[ord($matches[1]) % 8]; }, $V341be97d) except it has a wrinkle: it tries to use the $V70dda5df variable. You need to adjust the syntax a bit by removing the backslash (it was needed because the code lived inside a string) but also for the fact that variables aren't accessible inside functions... unless you explicitly tell PHP you want that with a "use" attached to the function. That results in, preg_replace_callback('/\^([^\^<])/', function($matches) use ($V70dda5df) { return '`' . $V70dda5df[ord($matches[1]) % 8]; }, $V341be97d) The thing about variables doesn't apply to shorthand functions, so with PHP 7.4 you could simply write preg_replace_callback('/\^([^\^<])/', fn($matches) => '`' . $V70dda5df[ord($matches[1]) % 8], $V341be97d)
    1 point
  32. since you finally posted the code producing the unexpected output, this is because your html markup is broken. you are not surrounding the value = '...' attribute completely/correctly with single-quotes, so the first space character becomes a stop character. in the markup.
    1 point
  33. client-side validation is a nicety for legitimate visitors. since external data can be submitted to your server-side code from anywhere, can be set to anything, and cannot be trusted, you MUST validate all data on the server before using it. since you must do this, it doesn't pay to do more than just use the browser's built in form field checks in the client. also, from the point where you have checked in the client if a value doesn't exist (you would need to use ajax to do this), to the point on the server where you actually try to insert the data, the value(s) could have been taken, and the insert query error handling is place where this check must finally occur. in the server-side code, the correct way of detecting duplicates, in the case of multiple concurrent requests to your script, is to define the column(s) to be unique indexes, then simply attempt to insert the data, and detect if a duplicate index error has occurred. in the case of more than one unique column, it is after the insert query fails, that you would execute a select query to find which column(s) already contain the submitted values. your database design is duplicating the fullname in two tables. this creates a problem in that if anyone edits a value, you must insure that all occurrences are updated. you should avoid duplicating data in multiple tables. is there some reason that you cannot just use a single table for all this user information? also, since most people have a first name and a last name, you should store these in two separate columns to avoid ambiguity. is someone's name Ross Martin or Martin Ross? as to the server-side code, this is largely derived from the bad code examples at w3schools and there's nearly twice as much code as is necessary. instead, the server-side form processing code should - use an array for the user/validation errors, with the array index being the field name. keep the form data as an array in a php array variable, then use elements in this array variable throughout the rest of the code. detect if a post method form was submitted, rather than trying to detect if the submit button is set. trim all the data ONCE. since you will be keeping the data in a php array variable, you can do this using one single line of code. there's 11 trim() statements in that code for 4 pieces of data. validate all the data, storing the errors per item #1 on this list. after the end of all the validation logic, if the array holding the errors is empty, use the submitted data. don't (switch to) use $_REQUEST variables. use the variables you expect data in. also, you are validating the trimmed input data, but are using the un-trimmed data in the sql query. after you do items #2 and #4 on this list, you will only be using the trimmed data throughout the rest of the code. you ARE using a prepared query. do NOT also apply any _escape_string() functions to the data. this will result in the escape characters being inserted into the database, messing up the stored data. don't copy variables to other variables for nothing. this is a waste of your time typing. if you switch to use the much simpler PDO database extension, about half of the database lines of code will go away. you need error handling for all the database statements that can fail - connection, query, prepare, and execute. the only place where a user can recover from a database error is when inserting/updating duplicate or out of range value. this is the only case where you should have error handling logic in your code. if you use exceptions for database statement errors and only catch and handle the exception in this case, you can remove any existing error handling logic, simplifying your code. every redirect needs an exit/die statement after it to stop php code execution. the redirect upon successful completion of the post method form processing code should be to the exact same url of the current page, to cause a get request for that page. the comment/redirect is not clear if this is what the code is doing. if there are user/validation errors at item #6 in this list, the code would continue on to display the html document, redisplay the form, with any user/validation error messages, and repopulate the appropriate form field values with the submitted values, so that user doesn't need to keep entering the same values over and over. any dynamic value that you output on a web page needs htmlentities() applied to it to help prevent cross site scripting. to get a form to submit to the same page it is on, simply leave out the entire action attribute.
    1 point
  34. As I said first thing -- the style of this code is not allowed at all. It has to be re-written. These new lines are not the same as the one you have the error on. They do not follow the same format as the bad one. I have no idea what the app is supposed to do for you but it is written rather tediously and I would have definitely found another way to do this that the mind-numbing way that the original code chose. I'm guessing that he/she too was a noob when writing it. Try this: $coronavirus_notice_banner_color = @$_POST['action']=='save_coronavirus_notice_plugin' ? $coronavirus_notice_banner_color : (get_option('coronavirus_notice_banner_color') ? esc_html(get_option('coronavirus_notice_banner_color')) : '#CC0000'); And I really don't like the use of the @ in this code. It is not a good practice.
    1 point
  35. that's not the correct call-time parameter usage for the msyqli_select_db() statement. the correct usage can be found in the php.net documentation. you can also select the database when you make the connection now, so there's generally no need to use a separate select db statement. if you arrived at this point by trying to convert old mysql_ based code to use the mysqli extension, simply by adding an 'i' to the function calls, this does not work. you must actually learn the correct usage for the mysqli statements. if you are converting old mysql_ based code, it is simpler and much better to skip over using the mysqli extension and use the PDO extension, because a huge problem with converting old code is the lack of security against sql special characters in data values breaking the sql query syntax, which is how sql injection is accomplished. the simplest way of adding security for all data types is to use a prepared query, which is very simple with the PDO extension, but more complicated and inconsistently handled with the mysqli extension.
    1 point
  36. firstly, these emails are NOT being sent from the email address that is entered in the form. they are being sent from the mail server at your web hosting and the From: and Return-path: email addresses must correspond to your web hosting. you can use the submitted email address as the Reply-to: address, after validating that it is exactly and only a validly formatted email address (checking that it contains an @ and a . is not sufficient.) your code is open to mail header injection, so, a bot script can basically build an email with anything and send it to any email address. the spam emails you are receiving are just the copy being sent to your To: email address. you MUST validate all inputs before using them. for the entered email address, after you have trimmed and validated that it is not an empty string, use php's filter_var with the FILTER_VALIDATE_EMAIL flag (do NOT use the FILTER_SANITIZE_EMAIL flag as it alters the value.) if the entered email address passes all the validation, use it in the Reply-to: mail header.
    1 point
  37. Your composer.json says it needs to use PHP ^7.2, meaning 7.2 or 7.3 or 7.4. laravel/passport needs ^7.2 as well. So downgrade your version of PHP to 7.2/7.3/7.4, or update your composer.json and laravel/passport dependency such that you can use PHP 8.1 with it.
    1 point
  38. I don't see how they can be. They may not be right but they must be different. You stated that WS occured on Saturday mornings, so why would there be more than 1 per week? (each serid only appeared on one date in the test data you provided) You came here with a problem and I helped you. Now a shedload of never before mentioned requirements and conditions suddenly appear. How many more will creep out of the woodwork? I don't like "mission creep" . As well as only accepting live services (aforementioned where condition) you could also specify the day of week for each service +-------+----------------+--------------+-----------+ | serid | service_name | service_code | dayofweek | 1=Sun,..,7=Sat +-------+----------------+--------------+-----------+ | 1 | Prayer meeting | PM | 4 | | 2 | Worship | WS | 7 | | 3 | Thanks giving | PBB | 7 | | 4 | LS | LS | NULL | unspecified | 5 | Thanks giving | D1 | NULL | | 6 | Thanks giving | D2 | NULL | | 7 | Thanks giving | D3 | NULL | +-------+----------------+--------------+-----------+ and only process dates/services that match those specified days. That will limit them to one per week. The two queries then become -- -- headers query -- SELECT DISTINCT weekofyear(entrydate) - weekofyear(?) + 1 as wk_no , date_format(entrydate, '%e/%c') as edate , concat(date_format(entrydate, '%d'), ' ', service_code) as dayser , service_code FROM attendance a JOIN service s ON a.serid = s.serid AND (dayofweek(a.entrydate) = s.dayofweek OR s.dayofweek IS NULL) WHERE month(entrydate) = ? AND stype = 1 ORDER BY entrydate, a.serid; -- -- member attendance query -- SELECT weekofyear(entrydate) - weekofyear(?) + 1 as wk_no , concat(date_format(entrydate, '%d'), ' ', service_code) as dayser , group_no , mem_name , memid FROM attendance a JOIN member m USING (memid) JOIN service s ON a.serid = s.serid AND (dayofweek(a.entrydate) = s.dayofweek OR s.dayofweek IS NULL) WHERE month(entrydate) = ? AND stype = 1 ORDER BY group_no, mem_name, dayser
    1 point
  39. the php mysqli extension on your system must be compiled to use the mysqlnd driver, for the get_result and a few other functions/methods to be available - https://www.php.net/manual/en/mysqlnd.install.php i'm not sure this can be accomplished just through the hosting control panel. you will know when you are successful when there is a mysqlnd section in the phpinfo() output on your system. if you cannot enable this, your choices are, rewrite the code to - use the much simpler, more consistent, and better designed PDO extension. it has no mysqlnd driver gotya's like this. eliminate the use of the mysqli get_result function/method, which will require you to use mysqli_stmt::bind_result, and a bunch of code to dynamically fetch data as a result set or do a bunch of typing for all the columns/variables you are selecting from each query. however, if you are going to go through this much work, for each query, you might as well just spend the time to do item #1. converting a mysqli prepared query to use the PDO extension is fairly straight forward - make the database connection using PDO, storing the connection in a variable uniquely named, such as $pdo, so that you can identify/search which code has been converted or not. the use of ? positional prepared query place-holders is the same between mysqli and PDO. change the $mysqli->prepare() calls to use the $pdo connection variable, e.g. $pdo->prepare(). take the list of variables you are supplying to the ->bind_param() call, and supply them as an array to the ->execute([...]) call. remove the bind_param() calls and the get_result() calls. fetch the data using one of PDO's fetch methods - fetch(), fetchAll(), ... note: if you are using a foreach() loop to iterate over the msyqli result object (from the get_result call), you can loop over the PDO statement object in exactly the same way. for a non-prepared query, you would just use the PDO ->query() method instead of the mysqli ->query() method, then fetch/loop over the data as described above. any use of last insert id, num rows, or affected rows would need to use the equivalent PDO statements.
    1 point
  40. Diid you try switching off then on again 😀
    1 point
  41. I've been trawling my archive and found a sample pagination script from a few years ago. Outputs... Code (There is code at the end of the script to create the test data if required) <?php /* PDO CONNECTION *********************************************/ $host = 'localhost'; $username = '????'; $password = '????'; $database = 'jointute'; $dsn = "mysql:dbname=$database; host=$host; charset=utf8"; $db = new pdo($dsn, $username, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); /***************************************************************/ const PERPAGE = 2; $res = $db->query("SELECT COUNT(*) FROM pupil "); $total = $res->fetchColumn(); $page = $_GET['page'] ?? 1; $stmt = $db->prepare("SELECT fname , lname , DATE_FORMAT(dob, '%b %D') as birthday FROM pupil ORDER BY MONTH(dob), DAY(dob) LIMIT ?,? "); $stmt->execute( [ ($page-1) * PERPAGE, PERPAGE ]); $output = ''; foreach ($stmt as $rec) { $output .= "<div class='pupil'> <div class='label'>Name:</div> {$rec['fname']} {$rec['lname']}<br> <div class='label'>Birthday:</div> {$rec['birthday']} </div>\n"; } /************************************************************************************** * function to output page selection buttons * * @param int $total total records * @param int $page current page number * @return string selection buttons html */ function page_selector($total, $page) { if ($total==0) { return ''; } $kPages = ceil($total/PERPAGE); $filler = '&nbsp;&middot;&nbsp;&middot;&nbsp;&middot;&nbsp;'; $lim1 = max(1, $page-2); $lim2 = min($kPages, $page+3); $p = $page==1 ? 1 : $page - 1; $n = $page== $kPages ? $kPages : $page + 1;; $out = "$kPages page" . ($kPages==1 ? '' : 's') . " &emsp;"; if ($kPages==1) { return $out; } $out .= ($page > 1) ? "<div class='pagipage' data-pn='$p'>Prev</div>&ensp;" : ''; if ($page > 4) { $out .= "<div class='pagipage' data-pn='1'>1</div> $filler"; } elseif ($page==4) { $out .= "<div class='pagipage' data-pn='1'>1</div>"; } for ($i=$lim1; $i<=$lim2; $i++) { if ($page==$i) $out .= "<div class='pagicurrent'>$i</div>"; else $out .= "<div class='pagipage' data-pn='$i'>$i</div>"; } if ($page < $kPages-3) { $out .= "$filler <div class='pagipage' data-pn='$kPages'>$kPages</div>"; } $out .= $page < $kPages ? "&ensp;<div class='pagipage' data-pn='$n'>Next</div>" : ''; return $out; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)"> <title>Pagination sample</title> <meta name="author" content="Barand"> <meta name="creation-date" content="07/02/2018"> <style type="text/css"> body { font-family: verdana; font-size: 10pt; } #title { font-size: 16pt; background-color: #369; color: #FFF; text-align: center; padding: 10px; margin-bottom: 40px; } .pagipage { display: inline; width: 25px; height: 15px; padding: 3px 5px; text-align: center; font-size: 9pt; border: 1px solid #3C9DBA ; color: #3C9DBA; background-color: #FFF; cursor: pointer; margin-left: -1px; } .pagipage:hover { background-color: #3C9DBA; border-color: #F0F; color: white; } .pagicurrent { display: inline; width: 25px; height: 15px; text-align: center; font-size: 9pt; font-weight: 600; border: 1px solid #3C9DBA; background-color: #3C9DBA; color: white; padding: 3px 5px; } .paginate_panel { text-align: center; margin: 20px 0; width: 100%; color: #3C9DBA; } .pupil { width: 300px; padding: 10px; margin-top: 5px; margin-left: auto; margin-right: auto; border: 1px solid gray; } .label { width: 100px; font-weight: 600; display: inline-block; } </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> $().ready( function() { $(".pagipage").click( function() { $("#page").val( $(this).data("pn") ); $("#form1").submit(); }) }) </script> </head> <body> <div id='title'> Pagination Sample </div> <form id='form1'> <input type="hidden" name="page" id="page" value="0"> </form> <?=$output?> <div class="paginate_panel"> <?=page_selector($total, $page)?> </div> <!-- DATA --- CREATE TABLE `pupil` ( `pupilID` int(10) unsigned NOT NULL AUTO_INCREMENT, `fname` varchar(45) NOT NULL, `lname` varchar(45) NOT NULL, `houseID` int(10) unsigned NOT NULL DEFAULT '1', `classid` char(1) NOT NULL DEFAULT 'A', `dob` date DEFAULT NULL, PRIMARY KEY (`pupilID`), KEY `house` (`houseID`), KEY `idx_pupil_classid` (`classid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `pupil` VALUES (1,'Adam','Simms',1,'A','2001-06-22'), (2,'Allan','Blair',2,'B','2001-03-04'), (3,'Anna','Hamilton',4,'B','2002-01-16'), (4,'Anne','Bailey',3,'D','2001-08-02'), (5,'Anthony','Bell',2,'E','2001-10-01'), (6,'Caroline','Freeman',2,'F','2000-12-13'), (7,'David','Powell',1,'A','2001-05-03'), (8,'Emma','Watson',4,'C','2001-11-20'), (9,'George','Wilson',1,'C','2001-06-30'), (10,'Henry','Irving',4,'D','2001-08-12'), (11,'Jane','Morrison',1,'E','2001-08-24'), (12,'John','Patterson',3,'F','2001-09-06'), (13,'John','Tully',3,'A','2001-09-03'), (14,'John','Watson',2,'B','2001-09-30'), (15,'Jack','Williams',2,'D','2001-09-08'), (16,'Margaret','Norton',4,'D','2001-04-23'), (17,'Mary','Blake',4,'E','2001-10-04'), (18,'Mary','Sheldon',3,'F','2001-06-14'), (19,'Mary','Whitehouse',2,'A','2001-09-06'), (20,'Michael','Grove',3,'B','2001-08-11'), (21,'Peter','Adamson',1,'C','2001-09-18'), (22,'Peter','Appleby',3,'D','2001-04-26'), (23,'Wayne','Jones',1,'E','2001-05-06'), (24,'William','Smith',4,'F','2001-12-08'); --> </body> </html>
    1 point
  42. aside from that query needing the columns you are SELECTing listed, nothing about that select query itself needed to be changed. didn't the previous pagination code cause the correct page 2, 3, ... content to be queried for and displayed? the initial sql query used a variable named $initial_page. what is the code setting the value in that variable? when you integrated the code that i gave into your existing code, did you make sure that the $initial_page variable was producing the expected result? hint: i intentionally kept the name for the page value the same throughout the code, rather than to use two different names for it. you will need to go though the code and reconcile any variable name differences for that value.
    1 point
  43. wouldn't that mean that you need to investigate why it isn't working in order to find and fix what's causing the incorrect operation?
    1 point
  44. gizmola, again thanks for your response. I am looking for ways to speed the app up so this is clearly something I'm going to have to study and implement. I'll look into Redis and learn what it will take to use it and where in my app it will help. Thanks again.
    1 point
  45. if you are interested in displaying a range of links around the current page number (there's no guarantee the OP even saw the post suggesting that), here's some example code - <?php // build pagination links: prev, 1, range around current page, total_pages, next // number of +/- links around the current page number $range = 3; // number of items per page $limit = 12; // get total number of rows using a SELECT COUNT(*) ... query $total_rows = 3121; // calculate total number of pages $total_pages = ceil($total_rows / $limit); // get current page, default to page 1 $page = $_GET['page'] ?? 1; // limit page to be between 1 and $total_pages $page = max(1,min($total_pages,$page)); // produce array of pagination numbers: 1, range around current page, total_pages, without duplicates, between 1 and total_pages $links = array_filter(array_unique(array_merge([1],range($page-$range, $page+$range),[$total_pages])), function ($val) use ($total_pages) { return $val >= 1 && $val <= $total_pages; }); // build pagination links $pagination_links = ''; // get a copy of any existing get parameters $get = $_GET; // produce previous $get['page'] = $page - 1; $qs = http_build_query($get,'', '&amp;'); $pagination_links .= $page == 1 ? 'prev ' : "<a href='?$qs'>prev</a> "; // produce numerical links foreach($links as $link) { $get['page'] = $link; $qs = http_build_query($get,'', '&amp;'); $pagination_links .= $link == $page ? "$link " : "<a href='?$qs'>$link</a> "; } // produce next $get['page'] = $page + 1; $qs = http_build_query($get,'', '&amp;'); $pagination_links .= $page == $total_pages ? 'next' : "<a href='?$qs'>next</a>"; // output pagination echo $pagination_links; note: your query to get the total number of rows should NOT select all the columns and all the rows of data. you should use a SELECT COUNT(*) ... query, then fetch the counted value.
    1 point
  46. What change are you trying to make on the created_at field?
    1 point
  47. I have recreated your attendance table and have run your code. I now know what you don't want. (109 columns labelled "31-May") Perhaps you could tell us what you do want?
    1 point
  48. For anyone following... I did a screen-share with the OP. The problem was missing files and files in the wrong place. I did a clean install of Laragon and installed (Not upgraded) Mysql 8. All is working.
    1 point
  49. What is the real question you are asking? PHP code in a PHP application is one component, loop or no loop. So it seems your real question is: 1 Query (with a join) vs. Multiple queries. 1 Query will always be faster and more efficient than multiple, unless there is something very wrong/unoptimized with the query. With that said, when you have static related tables, then having those tables cached can save you having to join the tables or do queries in a loop. As the result set will have to be "hydrated/expanded" within your PHP script to make use of those, or at least resolve the values you need from the cached lookup table, the complexity of adding all that code isn't often worth the pain, and might not even be more efficient in the long run, given a PHP script's short lifespan. What is certainly worth looking at, is the addition of a relational result cache like memcached or redis.
    1 point
  50. Most of these are named in a way that is fairly self explanatory, but sometimes you have to just take a look at the class to see what it is doing. \App\Http\Middleware\TrustProxies::class -> https://laravel.com/docs/9.x/requests#configuring-trusted-proxies (If you are using a proxy server or load balancer, this handles certain issues that arise) \Fruitcake\Cors\HandleCors::class -> https://github.com/fruitcake/laravel-cors (Configure your framework to set certain CORS related HTTP Headers) \App\Http\Middleware\PreventRequestsDuringMaintenance::class -> https://laravel.com/docs/9.x/configuration (See how to turn on Maintenance mode using artisan. Once it's turned on, this middleware enforces it) \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class -> See source https://github.com/laravel/framework/blob/5.8/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php (Notice that code just checks the configured PHP post_max_size against the size of an HTTP Post request. If the post request is too large, laravel throws a PostTooLarge exception.) The last 2 are again, very similar. Looking at the class definitions from the manual will show you what they do, and the code is simple and self explanatory, especially once you understand the things I explained about how middleware works in Laravel. See https://laravel.com/api/9.x/index.html and find the 2 classes.
    1 point
This leaderboard is set to New York/GMT-04:00
×
×
  • Create New...

Important Information

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