Jump to content

Barand

Moderators
  • Posts

    22,147
  • Joined

  • Last visited

  • Days Won

    600

Community Answers

  1. Barand's post in Introductions was marked as the answer   
    Good idea. Do you think we should have something like this ?
  2. Barand's post in OOP point to array value inside of a stdClass Object was marked as the answer   
    -> for object properties [] for array keys So
    $response->data->result[0]->value
  3. Barand's post in Updating Not Working was marked as the answer   
    I'd suggest something like this
    if($_SERVER['REQUEST_METHOD']=='POST') { $post = array_map('trim', $_POST); unset($post['submit']); // not wanted on journey $post['id'] = trim($_SESSION['id']); $post['submittedby'] = trim($_SESSION["username"]); if ($_FILES['image']['error'] = UPLOAD_ERR_OK) { // image file directory $target = "images/".basename($_FILES['image']['name']); if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) { $msg = "Image uploaded successfully"; $post['image'] = $target; }else{ $msg = "Failed to upload image"; $post['image'] = null; } } else { $post['image'] = null; } try { $sql = "UPDATE users SET name = :name, email = :email, phone = :phone, address = :address, license_number = :license_number, position = :position, role = :role, submittedby = :submittedby, image = :image WHERE id = :id "; $stmt= $db->prepare($sql); $stmt->execute($post); $message = ' <i class="fa fa-check text-success"> Record Updated!</i>'; } catch (PDOException $e) { $message = ' <i class="fa fa-check text-danger"> Something went wrong please contact the server admin.</i>'; } }  
  4. Barand's post in Randomizing posts in word press - by a random seed + a day variable was marked as the answer   
    You could just forget about the session value and
    SELECT ... ORDER BY RAND(dayofyear(CURDATE()))  
  5. Barand's post in Hours Worked Do Not WERK was marked as the answer   
    How you do it depends on how you are entering the data. The are basically two approaches...
    Create the timesheet record first then, each day add that days stafftime record Have a form where you enter the timesheet header data and all days' times at once for a user. If you use the first, have a dropdown so the user can select the timesheet record id and write that id with the day's times into stafftime.
    Doing it the second way, on posting the form you would first write the timesheet record (id would be an autoincrement column) then call lastInserId() to get the id of that new record. You then insert the time records with that last inserted id as the sheet_id.
  6. Barand's post in Not Calculating Correctly was marked as the answer   
    Never store data with multiple values like this
    '$week_ending', '$staff_name', '$monday_start', '$monday_finish', '$tuesday_start', '$tuesday_finish', '$wednesday_start', '$wednesday_finish', '$thursday_start', '$thursday_finish', '$friday_start', '$friday_finish', '$saturday_start', '$saturday_finish', '$sunday_start', '$sunday_finish', '$total_hours', '$timesheet_comment' You should always normalize your data when using an RDBMS. Once that's done, the processing can become a whole lot simpler.
    For example, if you table were like this...
    TABLE: driver TABLE: driver_timesheet +-----------+-----------+----------+ +--------------+-----------+-------------+-------------------+ | driver_id | firstname | lastname | | timesheet_id | driver_id | week_ending | timesheet_comment | +-----------+-----------+----------+ +--------------+-----------+-------------+-------------------+ | 1 | Peter | Dowt | | 1 | 1 | 2021-09-05 | 4-day week | | 2 | Laura | Norder | ----------------------------------------------------------------< | 2 | 2 | 2021-09-05 | No Saturday work | | 3 | Tom | DiCanari | | 3 | 3 | 2021-09-05 | No Sunday work | +-----------+-----------+----------+ +--------------+-----------+-------------+-------------------+ | | +------------------------------------------------------------------------------------+ TABLE: driver_time | +----------------+--------------+-------------+------------+----------+------------+ | driver_time_id | timesheet_id | driver_date | time_start | time_end | break_time | +----------------+--------------+-------------+------------+----------+------------+ | 1 | 1 | 2021-08-30 | 08:15:00 | 18:05:00 | 01:20:00 | | 2 | 1 | 2021-08-31 | 08:30:00 | 17:35:00 | 01:10:00 | | 3 | 1 | 2021-09-01 | 08:20:00 | 18:00:00 | 01:00:00 | | 4 | 1 | 2021-09-05 | 08:00:00 | 17:55:00 | 01:10:00 | | 19 | 2 | 2021-08-30 | 08:16:00 | 17:17:00 | 01:19:00 | | 20 | 2 | 2021-08-31 | 08:19:00 | 17:25:00 | 01:06:00 | | 21 | 2 | 2021-09-01 | 08:18:00 | 17:41:00 | 01:24:00 | | 22 | 2 | 2021-09-02 | 08:07:00 | 17:26:00 | 01:20:00 | | 23 | 2 | 2021-09-03 | 08:09:00 | 17:21:00 | 01:01:00 | | 25 | 2 | 2021-09-05 | 08:06:00 | 17:46:00 | 01:24:00 | | 26 | 3 | 2021-08-30 | 08:23:00 | 17:38:00 | 01:02:00 | | 27 | 3 | 2021-08-31 | 08:04:00 | 17:23:00 | 01:21:00 | | 28 | 3 | 2021-09-01 | 08:21:00 | 17:30:00 | 01:13:00 | | 29 | 3 | 2021-09-02 | 08:22:00 | 17:36:00 | 01:01:00 | | 30 | 3 | 2021-09-03 | 08:23:00 | 17:32:00 | 01:09:00 | | 31 | 3 | 2021-09-04 | 08:21:00 | 17:05:00 | 01:00:00 | +----------------+--------------+-------------+------------+----------+------------+ then all you need to do is write the data from your input form to the tables.
    To get the daily hours worked ...
    SELECT concat(firstname,' ', lastname) as name , dayname(driver_date) as day , date_format(driver_date, '%b %d') as date , time_start , time_end , break_time , timediff(timediff(time_end, time_start), break_time) as hrs_worked FROM driver_time JOIN driver_timesheet USING (timesheet_id) JOIN driver USING (driver_id) WHERE week_ending = '2021-09-05' ORDER BY driver_id, driver_date; +--------------+-----------+--------+------------+----------+------------+------------+ | name | day | date | time_start | time_end | break_time | hrs_worked | +--------------+-----------+--------+------------+----------+------------+------------+ | Peter Dowt | Monday | Aug 30 | 08:15:00 | 18:05:00 | 01:20:00 | 08:30:00 | | Peter Dowt | Tuesday | Aug 31 | 08:30:00 | 17:35:00 | 01:10:00 | 07:55:00 | | Peter Dowt | Wednesday | Sep 01 | 08:20:00 | 18:00:00 | 01:00:00 | 08:40:00 | | Peter Dowt | Sunday | Sep 05 | 08:00:00 | 17:55:00 | 01:10:00 | 08:45:00 | | Laura Norder | Monday | Aug 30 | 08:16:00 | 17:17:00 | 01:19:00 | 07:42:00 | | Laura Norder | Tuesday | Aug 31 | 08:19:00 | 17:25:00 | 01:06:00 | 08:00:00 | | Laura Norder | Wednesday | Sep 01 | 08:18:00 | 17:41:00 | 01:24:00 | 07:59:00 | | Laura Norder | Thursday | Sep 02 | 08:07:00 | 17:26:00 | 01:20:00 | 07:59:00 | | Laura Norder | Friday | Sep 03 | 08:09:00 | 17:21:00 | 01:01:00 | 08:11:00 | | Laura Norder | Sunday | Sep 05 | 08:06:00 | 17:46:00 | 01:24:00 | 08:16:00 | | Tom DiCanari | Monday | Aug 30 | 08:23:00 | 17:38:00 | 01:02:00 | 08:13:00 | | Tom DiCanari | Tuesday | Aug 31 | 08:04:00 | 17:23:00 | 01:21:00 | 07:58:00 | | Tom DiCanari | Wednesday | Sep 01 | 08:21:00 | 17:30:00 | 01:13:00 | 07:56:00 | | Tom DiCanari | Thursday | Sep 02 | 08:22:00 | 17:36:00 | 01:01:00 | 08:13:00 | | Tom DiCanari | Friday | Sep 03 | 08:23:00 | 17:32:00 | 01:09:00 | 08:00:00 | | Tom DiCanari | Saturday | Sep 04 | 08:21:00 | 17:05:00 | 01:00:00 | 07:44:00 | +--------------+-----------+--------+------------+----------+------------+------------+ and to get the weekly hours for each driver for payroll ...
    SELECT date_format(week_ending, '%d %b %Y') as wk_ending , concat(firstname,' ', lastname) as name , round(sum(time_to_sec( timediff(timediff(time_end, time_start), break_time) ))/3600, 2) as tot_hrs_dec FROM driver_time JOIN driver_timesheet USING (timesheet_id) JOIN driver USING (driver_id) WHERE week_ending = '2021-09-05' GROUP BY week_ending, driver_id +-------------+--------------+-------------+ | wk_ending | name | tot_hrs_dec | +-------------+--------------+-------------+ | 05 Sep 2021 | Peter Dowt | 33.83 | | 05 Sep 2021 | Laura Norder | 48.12 | | 05 Sep 2021 | Tom DiCanari | 48.07 | +-------------+--------------+-------------+ All your calculations done with a couple of queries.
  7. Barand's post in json_decode/encode confusion was marked as the answer   
    This fails
    $j = "{'admin': 1, 'moderator': 1}" ; $a = json_decode($j, 1); echo '<pre> a ' . print_r($a, 1) . '</pre>'; This works
    $j = '{"admin": 1, "moderator": 1}' ; $b = json_decode($j, 1); echo '<pre> b ' . print_r($b, 1) . '</pre>'; Note the quotes in the JSON string.
  8. Barand's post in Unsupported Operand Types? was marked as the answer   
    PHP v8 doesn't let you mix indeterminate types, such as adding an empty string to an int.
    $a = 1; $b = '2'; $c = ''; echo $a + $b; // 3 OK echo $a + $c; // Unsupported operand types: int + string echo $a + (int)$c; // 1 OK Use a cast to int.
    $this->hou += (int)$split[0]; That said, you really are doing the calculations the hard way
    $t1 = '09:30:00'; $t2 = '17:15:00'; $dt1 = new DateTime($t1); $dt2 = new DateTime($t2); echo $dt2->diff($dt1)->format('%H:%I:%S'); // 07:45:00  
  9. Barand's post in <div> table and css problems. Doesent do what i want it to do. Seen me blind on it. Please, HELP! was marked as the answer   
    Perhaps...
    <link rel='stylesheet' href='https://www.w3schools.com/w3css/4/w3.css'> <form id="form1"> <div class='w3-container w3-display-topright w3-light-gray w3-third' > <div class='w3-cell-row w3-padding-small'> <div class='w3-container w3-cell' style='width:120px'>Email</div> <div class='w3-container w3-cell'> <input class='w3-input w3-card w3-tiny' type='text' name='email'> </div> </div> <div class='w3-cell-row w3-padding-small'> <div class='w3-container w3-cell' style='width:120px'>Password</div> <div class='w3-container w3-cell'> <input class='w3-input w3-card w3-tiny' type='text' name='password'> </div> </div> <div class='w3-cell-row w3-padding-small'> <div class='w3-container w3-cell w3-right' style='width: 60%'> <button class='w3-btn w3-small w3-light-grey w3-border w3-right'>LogIn</button> </div> </div> </div> </form> Laptop...

    Mobile...

  10. Barand's post in mySQL query: try for one minute. was marked as the answer   
    Looks OK. I'd use a "do" loop i this case and count the records found.
    $start = time(); $query = $db->prepare("select count(*) from mytable where sku = ?"); do { sleep(1); $query->execute(['XYZ123']); $recs = $query->fetchColumn(); } while ($recs == 0 && time() < $start + 60); echo $recs == 0 ? "Try again later" : "$recs found";  
  11. Barand's post in UPDATE query not working... was marked as the answer   
    Alternatively
    ... WHERE server NOT IN ('gmail.com', 'yahoo.com')  
  12. Barand's post in Perfect mySQL one liner? was marked as the answer   
    Not necessarily...
    DATA
    +-------+-------+ | fruit | price | +-------+-------+ | grape | 5.00 | | melon | NULL | +-------+-------+ Code (PDO)
    $var = $db->query("select price from fruit where fruit = 'grape'")->fetch()['price'] ?? ''; echo '<br>Grape: ' . $var; $var = $db->query("select price from fruit where fruit = 'melon'")->fetch()['price'] ?? ''; echo '<br>Melon: ' . $var; $var = $db->query("select price from fruit where fruit = 'lemon'")->fetch()['price'] ?? ''; echo '<br>Lemon: ' . $var; Output (No exceptions were thrown during the running of this code)
    Grape: 5.00
    Melon:            (why no price?)
    Lemon:           (why no price?)
  13. Barand's post in Create a Table from pairs of array was marked as the answer   
    Rinse and repeat - exchanging u1 and u2
    $new = []; foreach ($array as $a) { if (!isset($new[$a['u1']])) { $new[$a['u1']] = []; } $new[$a['u1']][] = $a['u2']; //repeat exchanging u1 and u2 if (!isset($new[$a['u2']])) { $new[$a['u2']] = []; } $new[$a['u2']][] = $a['u1']; } // // Output $new array // echo '<pre>'; foreach ($new as $u1 => $u2s) { printf('<br><b>%4d</b> | ', $u1); foreach ($u2s as $u) { printf('%4d &vellip;', $u); } }
  14. Barand's post in Easy Forecast Delivery Day code was marked as the answer   
    I'd revise the function so it just gave a plain array of dates, then nudge the delivery by a day if the due date is the holiday array.
    So array is ...
    Array ( [0] => 2021-01-01 [1] => 2021-04-02 [2] => 2021-04-05 [3] => 2021-05-03 [4] => 2021-05-31 [5] => 2021-08-30 [6] => 2021-12-25 [7] => 2021-12-26 [8] => 2021-12-27 [9] => 2021-12-28 ) My solution: (If you don't want to be spoon-fed, ignore)


  15. Barand's post in Pagination - duplicating data was marked as the answer   
    Try
    $start_from = ($page - 1) * $num_per_page;  
  16. Barand's post in Display records in a table format dynamically was marked as the answer   
    Do you mean something like this?
    <?php // get the "name" headings that you need for the columns // and also use them as keys in a "template" array // $res = $db->query("SELECT DISTINCT name FROM dataset ORDER BY name "); $names = $res->fetchAll(); $heads = array_column($names, 'name'); $temp = array_fill_keys($heads, ''); $table_header = "<tr><td></td><td class='thead'>Result</td><td class='thead'>" . join("</td><td class='thead'>", $heads) . "</td></tr>\n"; // now get the data // store in an array by "id" // witd subarrays for each name $res = $db->query("SELECT id , edate , result , name , nos FROM maintab m JOIN dataset d ON m.id = d.mid ORDER BY id "); $data = []; foreach ($res as $r) { if (!isset($data[$r['id']])) { $data[$r['id']] = [ 'edate' => $r['edate'], 'result' => $r['result'], 'names' => $temp // the template array from earlier ]; } $data[$r['id']]['names'][$r['name']] = $r['nos']; // put value in tempate array } // now we simply output data array into html table rows $tdata = ''; foreach ($data as $row) { $tdata .= "<tr><td>{$row['edate']}</td><td>{$row['result']}</td><td>" . join('</td><td>', $row['names']) . "</td></tr>\n"; } ?> <html> <head> <title>Example</title> <style type='text/css'> td { padding: 4px 10px; } .thead { font-weight: 600; border-top: 1px solid gray; border-bottom: 1px solid gray; } </style> </head> <body> <table> <?= $table_header ?> <?= $tdata ?> </table> </body> </html> OUTPUT

    [edit] PS Sorry about the data typo. That's what happens when people post pictures instead of copyable text.
  17. Barand's post in Cookie DB was marked as the answer   
    Define the combination of fields as UNIQUE, for example to ensure domain/name are unique
    ALTER TABLE `cookies` ADD UNIQUE INDEX (domain, name);  
  18. Barand's post in unpacking a binary number (string) was marked as the answer   
    Still forgetting unpack(), for 8 bits to 8 vars
    $binary3 = 0b10110001; for ($k=0; $k<8; $k++) { $vars[$k] = ($binary3 & 2**$k) ? 1:0; } giving
    $vars = Array ( [0] => 1 [1] => 0 [2] => 0 [3] => 0 [4] => 1 [5] => 1 [6] => 0 [7] => 1 )  
  19. Barand's post in Extract email address from Stripe API was marked as the answer   
    The string you posted appears to be missing its enclosing { .. }. With those it becomes a correctly formatted JSON string...
    $details = '{"customer_details":{"email":"emailaddress@gmail.com","tax_exempt":"none","tax_ids":[]}}'; you can then decode the string...
    $data = json_decode($details); then access the email address with...
    $email = $data->customer_details->email;  
  20. Barand's post in Creating neat little sub-array from big array was marked as the answer   
    I would ...
    foreach ($array as $k => $v) { $id = substr($k, -5); if (ctype_digit($id)) { $len = strlen($k); $k = substr($k, 0, $len-5); $sku[$id][$k] = $v; } else $sku[$k] = $v; } echo '<pre>' . print_r($sku, 1) . '</pre>'; giving...
    Array ( [77777] => Array ( [newQuantity] => 3 [newPrice] => 5 [usedQuantity] => 1 [usedPrice] => 3.99 [total] => 18.99 ) [88888] => Array ( [newQuantity] => 0 [newPrice] => 0 [usedQuantity] => 4 [usedPrice] => 12 [total] => 48 ) [44444] => Array ( [newQuantity] => 2 [newPrice] => 4 [usedQuantity] => 0 [usedPrice] => 3.99 [total] => 8 ) [date] => July 25 2021 [address] => 123 Anystreet Avenue [address2] => [zipcode] => 90210 [city] => Beverly Hills [state] => CA [planet] => Mars )  
  21. Barand's post in MYSQL Insert: Whatever's inside JSON array? was marked as the answer   
    Here's a shortened version. It also uses json_decode without the "true" to give an object (containing objects)
    $all = json_decode($all_items_sold); $placeholders = $values = []; foreach ($all as $pid => $prod){ if (in_array($pid, $referred_by_Affiliate)) { $placeholders[] = "(?,?,?)"; array_push($values, $pid, $prod->item, $prod->price); } } $stmt = $db->prepare("INSERT INTO mytable (prod_id, item, price) VALUES " . join(',', $placeholders)); $stmt->execute($values);  
    A PHP join has nothing to do with MySQL joins.
  22. Barand's post in PHP not installed correctly? was marked as the answer   
    Your file name is index.html and not index.php.
    You need a php file for php code to be executed.
  23. Barand's post in Problem transferring data between pages using PHP session was marked as the answer   
    What if no new value has been posted but your session value already contains 50?
    Perhaps...
    $get_ppp = $_POST['ppp'] ?? $_SESSION['ppp'] ?? 15; $_SESSION['ppp'] = $get_ppp;  
  24. Barand's post in Get ID from jobs and insert it to Bookings was marked as the answer   
    You're making it difficult for yourself.
    The tour/job name should not be in the booking table. The only place that should occur in your database is in the tour/job table. It is just the tour id that be in the booking table.
    +------------------+ | booking | +----------------+ +------------------+ | tour/job | | booking_id | +----------------+ | tour_id |>----------------| tour_id | | cust_name | | tour_name | | cust_address | +----------------+ | order_at | | ... | | etc | +------------------+ When you create your dropdown options, the values of the options should be the id and not the name.
    Then all you do is insert $_POST['tour_name'] (which will actually be the id) into the booking data. Job done.
  25. Barand's post in FullCalendar not displaying data from MySQL was marked as the answer   
    Do not use SELECT *
    Specify what you want and your (PDO) code becomes
    $query = "SELECT id , name as title , dep_date as start , ret_date as end FROM tours ORDER BY id"; $result = $con->query($query); echo json_encode($result->fetchAll());  
×
×
  • 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.