Jump to content

Barand

Moderators
  • Posts

    24,607
  • Joined

  • Last visited

  • Days Won

    831

Everything posted by Barand

  1. I'd have to write a book to answer that question.
  2. As output is dependent on employee schedule and overlapping appointments, and I have no idea what is in your data, then you are on your own.
  3. You have a prepared statement with 10 placeholders but your execute() only provides 6 values
  4. The SQL tutorial link in my signature may help to get you started.
  5. Oops! 🥵 Hence the success with the *100 fix. Gives weight to the definition of test data : That data for which the code works.
  6. How about it ^ @ChenXiu? I've shown you mine, you show me yours.
  7. Of course, to risk stating the obvious, you will have to substitute your parameters and column names. $stmt_emp = $con->prepare(" Select employee_id from employees_schedule where employee_id = ? and day_id = ? and to_hour > ? and from_hour < ? "); $stmt_emp->execute(array($selected_employee,$day_id,$start, $result));
  8. I modified the code slightly tot add a 'total' element to each of the arrays to make sequence order easier to check. Revised code <?php $data = [ [ 'price' => 8.50, 'postage' => 3.50 ], [ 'price' => 6.18, 'postage' => 2.33 ], [ 'price' => 6.13, 'postage' => 0 ], [ 'price' => 4.19, 'postage' => 2.63 ], [ 'price' => 2.50, 'postage' => 1.80 ] ]; // add total element to arrays foreach ($data as &$a) { $a['total'] = $a['price'] + $a['postage']; } usort($data, function($a, $b) { return $a['price'] + $a['postage'] - $b['price'] - $b['postage']; }); echo '<pre>' . print_r($data, 1) . '</pre>'; // $data[1] and $data[2] are in wrong position ?> My results Array ( [0] => Array ( [price] => 2.5 [postage] => 1.8 [total] => 4.3 ) [1] => Array ( [price] => 6.13 [postage] => 0 [total] => 6.13 ) [2] => Array ( [price] => 4.19 [postage] => 2.63 [total] => 6.82 ) [3] => Array ( [price] => 6.18 [postage] => 2.33 [total] => 8.51 ) [4] => Array ( [price] => 8.5 [postage] => 3.5 [total] => 12 ) ) The order definitely looks correct.
  9. You will basically need 2 things a for() loop the modulo (%) operator (optional)
  10. Give the formatted date a column alias SELECT date_format(created_at, '%b %e %Y %h:%i%p') as created_at Without the alias you need to use $row["date_format(created_at, '%b %e %Y %h:%i%p')"]
  11. You can do it in your query with SELECT date_format(created_at, '%b %e %Y %h:%i%p'), ... or you can do it in php with date('M j Y g:ia', strtotime($row['created_at']))
  12. PS As an aside, you have a query to find employees schedules overlapping with the time period A - B. The possible overlapping cases are shown below The following WHERE clause will find all 4 types whereas yours won't. WHERE S < B AND E > A
  13. Below is the result of my running your for() loop. The highlighted bit look very much like Sunday to me
  14. Your array (with the 0) sorted correctly for me without bringing in the menagerie ???
  15. Do your prices contain the '$'?
  16. I didn't suggest a separate script - the one will suffice. if record is posted append to cart.txt end if open cart.txt for reading foreach record write table row end foreach
  17. As you add each item, write name, quantity and price to your cart.txt file. Then read the stored items back from cart.txt and display them all, each in its own row, calculating the price for each PS You may find fgetcsv() useful here.
  18. I'd go with a "token_transaction" table and store token accumulation/disposal in that instead of updating totals. TABLE: token_transaction transaction types +----+---------+------------+---------------------+-----+ +---------------+---------------+ | id | user_id | trans_type | trans_time | qty | | type | quantity | +----+---------+------------+---------------------+-----+ +---------------+---------------+ | 1 | 1 | earn | 2023-01-03 15:25:20 | 10 | | earn | +ve | | 2 | 2 | earn | 2023-01-03 15:25:20 | 10 | | receive | +ve | | 3 | 2 | donate | 2023-01-04 10:15:50 | -1 | | spend | -ve | | 4 | 3 | receive | 2023-01-04 10:15:50 | 1 | | donate | -ve | | 5 | 1 | donate | 2023-02-04 12:00:00 | -1 | | cancel | -ve | | 6 | 4 | receive | 2023-02-04 12:00:00 | 1 | +---------------+---------------+ | 7 | 1 | donate | 2023-01-14 14:49:29 | -3 | | 8 | 8 | receive | 2023-01-14 14:49:29 | 3 | | 9 | 8 | donate | 2023-01-14 14:51:13 | -2 | | 10 | 1 | receive | 2023-01-14 14:51:13 | 2 | +----+---------+------------+---------------------+-----+ When a donation is made, two transactions are generated, both with identical timestamps. negative quantity for the donor positive quantity for the recipient When you need to know how many tokens a user has, just SUM their quantities in the transactions. For example, given the transactions above SELECT user_id , username , COALESCE(SUM(qty), 0) as tokens FROM users u LEFT JOIN token_transaction t USING (user_id) GROUP BY username; +---------+----------+--------+ | user_id | username | tokens | +---------+----------+--------+ | 4 | blitzen | 1 | | 1 | comet | 8 | | 2 | cupid | 9 | | 5 | dancer | 0 | | 7 | dasher | 0 | | 3 | donner | 1 | | 6 | prancer | 0 | | 8 | vixen | 1 | +---------+----------+--------+ The donation code would then look like this <?php session_start(); include 'db_inc.php'; // USE YOUR OWN $pdo = pdoConnect(); // PDO CONNECTION CODE # # Ensure user is logged in # if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; } $errors = []; # # Get user's current token quantity # $res = $pdo->prepare("SELECT sum(qty) as wealth FROM token_transaction WHERE user_id = ? "); $res->execute([ $_SESSION['user_id']]); $wealth = $res->fetchColumn() ?? 0; # # If data was POSTed, process it # if ($_SERVER['REQUEST_METHOD'] == 'POST') { $post = array_map('trim', $_POST); if ($post['recipient']=='') { $errors[] = 'You must specify a recipient'; } if ($post['qty']==0) { $errors[] = 'You did not specify how many tokens'; } elseif ($post['qty'] > $wealth) { $errors[] = 'You have insufficient tokens'; } if (!$errors) { $now = date('Y-m-d H:i:s'); $pdo->beginTransaction(); try { $stmt = $pdo->prepare("INSERT INTO token_transaction (user_id, trans_type, trans_time, qty) VALUES (?, ?, '$now', ?) "); $stmt->execute( [ $_SESSION['user_id'], 'donate', -$post['qty'] ] ); // donor transaction $stmt->execute( [ $post['recipient'], 'receive', $post['qty'] ] ); // recipient transaction $pdo->commit(); } catch(PDOException $e) { $pdo->rollBack(); throw $e; } header("Refresh: 0"); // reload the page exit; } } # # FUNCTIONS # function userOptions(PDO $pdo, $current) { $opts = "<option value=''>- select user -</option>\n"; $res = $pdo->query("SELECT user_id , username FROM users ORDER BY username "); foreach ($res as $r) { $sel = $r['user_id'] == $current ? 'selected' : ''; $opts .= "<option $sel value='{$r['user_id']}'>{$r['username']}</option>\n"; } return $opts; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>sample</title> <meta charset="utf-8"> <script type='text/javascript'> </script> <style type='text/css'> body { font-family: arial; } header { background-color: #006EFC; color: white; padding: 16px; } #form1 { width: 500px; margin: 32px auto; padding: 16px; border: 1px solid gray; } #info { width: 500px; margin: 32px auto; padding: 16px; background-color: yellow; } label { display: inline-block; background-color: gray; color: white; padding: 8px; width: 120px } </style> </head> <body> <header> <h1>Token Donation</h1> </header> <div id='info'> <?php if ($errors) { echo "<p>" . join('<br>', $errors) . "</p>\n"; } else { echo "<p>You currently have <b>$wealth</b> tokens</p>\n"; } ?> </div> <form method='POST' id='form1'> <label for='recipient'>Donate to</label> <select name='recipient' id='recipient'> <?= userOptions($pdo, $post['recipient']??'') ?> </select> <br><br> <label for='qty'>How many?</label> <input type='number' name='qty' id='qty' min='0' max='<?=$wealth?>' value='<?= $post['qty'] ?? 1 ?>'> <br><br> <input type='submit'> </form> </body> </html>
  19. Works for me with decimal values. <?php $data = [ [ 'price' => 8.50, 'postage' => 3.50 ], [ 'price' => 2.50, 'postage' => 1.50 ], [ 'price' => 7.50, 'postage' => 2.10 ], [ 'price' => 10.00, 'postage' => 1.50 ], [ 'price' => 2.50, 'postage' => 1.80 ] ]; usort($data, function($a, $b) { return $a['price'] + $a['postage'] - $b['price'] - $b['postage']; }); echo '<pre>' . print_r($data, 1) . '</pre>'; ?> results Array ( [0] => Array ( [price] => 2.5 [postage] => 1.5 ) [1] => Array ( [price] => 2.5 [postage] => 1.8 ) [2] => Array ( [price] => 7.5 [postage] => 2.1 ) [3] => Array ( [price] => 8.5 [postage] => 3.5 ) [4] => Array ( [price] => 10 [postage] => 1.5 ) )
  20. If you look at the html source you will see that it is the same as before... <input class="form-control" type="text" value=Information and Technology disabled readonly> It needs to be <input class="form-control" type="text" value="Information and Technology" disabled readonly> ^ ^ The php needs to be <?php echo '<input class="form-control" type="text" value="'.$CategoryName.'" disabled readonly>'; ?> or, using a double-quoted string <?php echo "<input class='form-control' type='text' value=\"$CategoryName\" disabled readonly>"; ?>
  21. There are a couple of solutions that you can apply on the MySql side. 1 ) Use mysql's ROUND() function i your query mysql> create temporary table test1 (amount float); mysql> insert into test1 (amount) Values (PI()); mysql> select amount, round(amount, 1) as rounded from test1; +---------+---------+ | amount | rounded | +---------+---------+ | 3.14159 | 3.1 | +---------+---------+ 1 row in set (0.03 sec) 2 ) Define the column as DECIMAL instead of FLOAT mysql> create temporary table test2 (amount DECIMAL(8,1)); mysql> insert into test2 (amount) Values (PI()); mysql> select amount from test2; +--------+ | amount | +--------+ | 3.1 | +--------+ 1 row in set (0.00 sec)
  22. Because that is the array you want to sort? It wasn't really necessary as usort($data['listings'] would have done the same thing. But I felt your array had a surfeit of levels.
  23. You were advised to use usort(). Your custom function would compare the totals of each pair of records ($a and $b) and return a negative value if $a should sort before $b or positive if $a sorts after $b. (ie total A - total B) $listings = $data['listings']; usort($listings, function($a, $b) { return $a['item_price']['value'] + $a['postage']['price']['value'] - $b['item_price']['value'] - $b['postage']['price']['value']; }); echo '<pre>' . print_r($listings, 1) . '</pre>';
  24. Dates need to be Ymd (or Y-m-d) to be sortable
  25. try using a custom sort function # # Sort attendees on course, name # usort($attendees, function($a, $b) { $x = $a['course']<=>$b['course']; if ($x == 0) return $a['name']<=>$b['name']; return $x; }); # # Add sorted attendees to result array # $result = array(); foreach ($attendees as $attendee): $result[$attendee['course']][] = $attendee; endforeach; # # View result # echo '<pre>' . print_r($result, 1) . '</pre>'; P.S. You didn't say in what order you want them. If your aim is merely to get the courses in order then you could use ksort($result) (instead of your current sort() )to order the keys.
×
×
  • 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.