Jump to content

Barand

Moderators
  • Posts

    24,563
  • Joined

  • Last visited

  • Days Won

    822

Everything posted by Barand

  1. Doesn't everybody who uses PDO? https://www.php.net/manual/en/pdo.construct.php
  2. The code I posted is working quite happily for me with the data I also posted. The original line 77 is not the one you indicate therefore some changes have been made to my code (warranty voided ) Also that line occurs twice in the code In the main body when building the table (line 67) In the function that is called when the + button is clicked to add a new row. (line 100) From the output image it would appear to be the first that failed as the ".308 bolt action" is added by the function call and appears to be working. To know why it is now failing I would need to see all the lines (from your new version) preceding the error line, particularly the query and processing of the query results. (I suspect the query has been changed)
  3. 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);
  4. I was going to suggest combining the arrays $systems = array_combine($systems, $Sysname); then you could foreach ($systems as $ip => $name) { // ping } However, to that that you would need the same number of names as there are IPs. It would give Array ( [192.168.9.254] => Item1 [192.168.9.205] => Item2 [192.168.9.200] => Item3 [192.168.9.201] => Item4 [192.168.9.1] => Item5 [192.168.9.2] => Item6 [192.168.9.3] => Item7 [192.168.9.4] => Item8 [192.168.9.7] => Item9 [192.168.9.13] => Item10 )
  5. Alternatively $str = 'FSOWPDHJEOSKJ3D2DF5R3FG51'; echo join('-', str_split($str, 5)); //--> FSOWP-DHJEO-SKJ3D-2DF5R-3FG51
  6. Perhaps because there apparently is no code to show another div?
  7. Seconds are optional <form> dt1 <input type='datetime-local' name='dt1' value='<?= date('Y-m-d\TH:i') ?>' > <br> dt2 <input type='datetime-local' name='dt2' value='<?= date('Y-m-d\TH:i:s') ?>' > <br> <input type='submit'> </form>
  8. One final comment - turn on PHP's and MySqli's error reporting. You and I aren't good enough to attempt development without them.
  9. I added one or two comments for you. <?php $username1=$_POST["text"] // ^^^^ there is no field named "text" $age=$_POST["number"] // ^^^^^^ there is no field named "number" $username="root"; $host="localhost"; $password=" "; $databasename="kemudb"; $conn=mysqli_connect($host, $username, $password, $databsename); // ^^ typo $sql_read="SELECT * FROM infokemu"; $result=mysqli_query($conn & $sql_read); // ^ WTF!? ?> <form method="POST" action=""> // ^^^^ as you are only getting data, your method should be GET, not POST USERNAME: <br> <input type="text" name="username1"/> <br> AGE <br> <input type="number" name="age"/> <br> <input type="submit" value="submit"/> </form> Lastly, what is the point of the query? You do nothing with the results (when you get any).
  10. If you look at the page source to see the code you are generating it should become obvious.
  11. If $id contains "Shooter" as a string value it need to be in quotes otherwise SQL thinks it is a column name $sql = "SELECT * FROM games WHERE genre = '$id' "; ^ ^
  12. I don't have your database table so I used the array to simulate the data that would be returned from a query so I could test the code. $data = $pdo->query("SELECT id , riflename , em , gm FROM rifles ORDER BY rifleName "); foreach ($data as $row) { echo "<option value={$row['id']} data-em='{$row['em']}' data-gm='{$row['gm']}'>" . htmlspecialchars( $row["rifleName"] ) . "</option>"; } Not so difficult, was it?
  13. Your script won't as it never refernces those database columns. I was under the impression that is exactly what my script is doing.
  14. When you process the query results, build an array with the required structure for your output. In this case something like $data = [ 'Kindred Coaching' => [ 2204 => [ 'Forecast' => '', 'Actual' => '' ], 2205 => [ 'Forecast' => '', 'Actual' => '' ]. 2206 => [ 'Forecast' => '345', 'Actual' => '345' ], 2207 => [ 'Forecast' => '345', 'Actual' => '' ], 2208 => [ 'Forecast' => '345', 'Actual' => '' ], 2209 => [ 'Forecast' => '345', 'Actual' => '' ], 2210 => [ 'Forecast' => '345', 'Actual' => '' ], 2211 => [ 'Forecast' => '345', 'Actual' => '' ] ] , 'Other Coaching' => [ 2204 => [ 'Forecast' => '', 'Actual' => '' ], 2205 => [ 'Forecast' => '', 'Actual' => '' ], 2206 => [ 'Forecast' => '123', 'Actual' => '234' ], 2207 => [ 'Forecast' => '123', 'Actual' => '' ], 2208 => [ 'Forecast' => '123', 'Actual' => '' ], 2209 => [ 'Forecast' => '123', 'Actual' => '' ], 2210 => [ 'Forecast' => '123', 'Actual' => '' ], 2211 => [ 'Forecast' => '123', 'Actual' => '' ] ] ]; then foreach ($data as $account => $accdata) { // start row // output account foreach ($accdata as $yrmnth => $values) { // output forecast and actual cells } // end row }
  15. Use data attributes for the options <?php $data = [ [ 'id' => 1, 'rifleName' => '.308 Bolt action', 'em' => '225', 'gm' => '1350' ], [ 'id' => 2, 'rifleName' => '7mm magnum', 'em' => '300', 'gm' => '1575' ], [ 'id' => 3, 'rifleName' => '.243 LeverAction', 'em' => '215', 'gm' => '8725' ] ]; ?> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> $().ready(function() { $("#menu").change( function() { let em = $(this).find("option:selected").data("em") let gm = $(this).find("option:selected").data("gm") $("#em").val(em) $("#gm").val(gm) }) }) </script> <select class='nameItems' id="menu" name="selection"> <option value="">Choose a Rifle</option> <?php foreach ($data as $row) { echo "<option value={$row['id']} data-em='{$row['em']}' data-gm='{$row['gm']}'>" . htmlspecialchars( $row["rifleName"] ) . "</option>"; } ?> </select> em:<input type="text" class="charge-type" name="em" id="em" value="0" disabled size="5"/> gm: <input class="charge-type" name="gm" id="gm" value="0" disabled size="5"/>
  16. Correction to above - I screwed up the array rotation bit. The if (!$placed) section should be if (!$placed) { // if we have an unseatable guest if ($passes >= count($enemies)) return 'Failed'; ++$passes; $guests = array_keys($enemies); for ($p=0; $p<$passes; $p++) $guests[] = array_shift($guests); // rotate array and try again $plan = [array_shift($guests)]; }
  17. Challenge accepted. Instead of creating all combinations (3,628,800 fo 10 guests) then eliminating, I decided to attempt the construction of feasible combinations only. First, create a useable array of the enemies of each gust and use that to place each guest, if possible. <?php $guests = 7; $enemies = [ '1-2,4', '3-4,6', '2-5' ]; ########################################################## # # # create a usable array ($e) of the enemies of eah guest # # # ########################################################## $e = array_fill_keys(range(1, $guests), []); foreach ($enemies as $a) { list($b, $c) = explode('-', $a); foreach (explode(',', $c) as $d) { $e[$b][] = $d; $e[$d][] = $b; } } ############################################################### # sort the array so those with most ememies are seated first # ############################################################### uasort($e, fn($a, $b) => count($b)<=>count($a)); echo seatPlan($e); function seatPlan(&$enemies) { $passes = 0; $guests = array_keys($enemies); $plan = [array_shift($guests)]; while(count($guests)) { // loop until all guests seated $placed = 0; foreach ($guests as $k => $g) { $p = count($plan); // if next guest is a friend, seat them if (!in_array($plan[$p-1], $enemies[$g])) { $plan[] = $g; unset($guests[$k]); $placed = 1; } } if (!$placed) { // if we have an unseatable guest if ($passes >= count($enemies)) return 'Failed'; ++$passes; $guests[] = array_shift($guests); // rotate array and try again $guests = array_keys($enemies); $plan = [array_shift($guests)]; } } return join(', ', $plan); } ?>
  18. As you are having a problem with the retrieval and display it might be an idea to show that portion of the code. As an aside, you are overwriting your date created with the date updated (and wrong format). Define those fileds in your table as created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, the omit them from your insert and update queries - they will update automatically.
  19. Sorry, but there was guesswork involved as I don't know all the table structures - you only gave os the quote table..
  20. Return values from functions. And stop conneting inside your functions! Connect once at top of script and pass the connection to your functions. I'd structure it something like this... <?php require 'includes/dbconn.php'; ## HANDLE AJAX CALL if ( isset($_GET['itemId']) ) { // if it's an ajax request exit(getItemAttributesById($pdo, $_GET['itemId'])); } function getItemAttributesById($pdo, $itemId){ $sql = "SELECT id, name, type, price_uk, price_us, price_ca, price_au, price_eu, billing_freq from item where id = :itemId"; $stmt = $pdo->prepare($sql); $bindData = [ 'itemId' => $itemId ]; $stmt->execute($bindData); $item = $stmt->fetch(PDO::FETCH_ASSOC); return json_encode($item); } ?>
  21. You only need separate connections if you are working on multiple servers. One connection is suffucient to work with several database on the same server. The connection is to the server, the database name merely defines the default database. $con->query("SELECT username FROM user"); // if querying default db $con->query("SELECT username FROM DB2.user"); // if DB2 is not the default db. To copy a table from DB1 to DB2 $con->query("CREATE TABLE DB2.tablea LIKE DB1.tablea"); $con->query("INSERT INTO DB2.tablea SELECT * FROM DB1.tablea");
  22. It happened again. My notifications indicated a post 2 hours ago (just signed on). Again it appears in "Expanded" but not in "Condensed" activity lists. Condensed Expanded
  23. or something like this to find the max quoteIds to be matched SELECT mx.quoteId, job_id as jobId, job.name as jobName, job.client_id as clientId, client.name as clientName, quote.currency, quote.version from job inner join client on client.id = job.client_id inner join ( select job_id , max(id) as quoteId from quote where quote.closed != '1' group by job_id ) mx using (job_id) inner join quote on mx.quoteId = quote.id group by job_id
  24. Why are you passing the $version to the function but always setting the parameter for :version to 1 ?
×
×
  • 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.