Jump to content

Barand

Moderators
  • Posts

    24,450
  • Joined

  • Last visited

  • Days Won

    809

Community Answers

  1. Barand's post in finding out the % of 2 variables was marked as the answer   
    current ------- X 100 = percent full  
  2. Barand's post in Associating cinema times with Screen numbers was marked as the answer   
    Something like this?

    CODE
    <?php include 'db_inc.php'; // YOUR CONNECTION $pdo = pdoConnect('movies'); // CODE GOES HERE ################################################################################ ## PROCESS AJAX REQUESTS ################################################################################ if (isset($_GET['ajax'])) { $res = $pdo->prepare("SELECT m.id as movie_id , m.title , m.image , g.description as genre , CONCAT(m.running_time DIV 60, ' hrs ', m.running_time % 60, ' mins') as running_time , date_format(sg.screen_on, '%W, %D %b') as date , s.name as screen_num , TIME_FORMAT(sg.screen_at, '%H:%i') as start_time FROM screening sg JOIN screen s ON sg.screen_id = s.id JOIN movie m ON sg.movie_id = m.id JOIN genre g ON g.id = m.genre WHERE dayname(screen_on) = :day ORDER BY movie_id, screen_on, sg.screen_at "); $res->execute([ 'day' => $_GET['day'] ]); $data = []; # # Put data into an array with same structure a required output # - array of movies, each movie having arrays of screenings # foreach ($res as $r) { if (!isset($data[$r['movie_id']])) { $data[$r['movie_id']] = [ 'title' => $r['title'], 'image' => $r['image'], 'genre' => $r['genre'], 'runtime' => $r['running_time'], 'screenings' => [] ]; } $data[$r['movie_id']]['screenings'][$r['date']][] = ['start' => $r['start_time'], 'sno' => $r['screen_num'] ]; } exit(json_encode($data)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta name="generator" content="PhpED 12.0 (Build 12010, 64bit)"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>olumide</title> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> function showScreenings(day) { $("#movie-listings").html("") $.get( "", {"ajax":1, "day":day}, function(resp) { $.each(resp, function(mid, mdata) { let title = `<h2>${mdata.title}</h2><h4 class='w3-text-gray'>${mdata.genre} (${mdata.runtime})</h4>` $("#movie-listings").append(title) $.each(mdata.screenings, function(dt, ddata) { let datesub = `<h3>${dt}</h3>` $("#movie-listings").append(datesub) $("#movie-listings").append("<div class='screenings'") $.each(ddata, function(k, sdata) { let scr = `<div class='screening'><b>${sdata.start}</b><br>${sdata.sno}</div>` $("#movie-listings").append(scr) }) $("#movie-listings").append("</div>") }) }) }, "JSON" ) } </script> <style type='text/css'> .days { padding: 16px; text-align: center; } .screening { width : 20%; display: inline-block; margin-right: 16px; margin-bottom: 8px; padding: 4px; border: 5px solid black; font-size: 9pt; } </style> </head> <body> <nav class="days"> <button onclick="showScreenings('Monday')">Monday</button> <button onclick="showScreenings('Tuesday')">Tuesday</button> <button onclick="showScreenings('Wednesday')">Wednesday</button> <button onclick="showScreenings('Thursday')">Thursday</button> <button onclick="showScreenings('Friday')">Friday</button> <button onclick="showScreenings('Saturday')">Saturday</button> <button onclick="showScreenings('Sunday')">Sunday</button> </nav> <div id='movie-listings'class='w3-content w3-padding w3-card-4'> <!-- LISTINGS GO HERE --> </div> </body> </html>  
  3. Barand's post in Counting based on IF statement issue was marked as the answer   
    This query should do it
    SELECT SUM(visited IS NULL AND timestampdiff(MONTH, created_at, now()) >= 15) as expired , SUM(visited IS NULL AND timestampdiff(MONTH, created_at, now()) < 3) as pending , SUM(visited IS NOT NULL) as ok FROM users;  
  4. Barand's post in Timestamp difference - using subtraction between the two in the database was marked as the answer   
    The mysql function NOW() gives the current datetime.
    mysql> SELECT timestampdiff(DAY, '2024-01-28 09:41:36', NOW() ) as diff; +------+ | diff | +------+ | 1 | +------+  
  5. Barand's post in Php mysql random link generate for a prize win was marked as the answer   
    I had in mind something like this...
    CREATE TABLE `win_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `won` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `collected` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_win_log_user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Bob (user_id #123) wins on Saturday. He also wins on Sunday.
    Each time he wins, you record the win with this query (inserting $_SESSION['user_id'] into the table)
    INSERT INTO win_log (user_id) VALUES (?); So now you have
    TABLE: win_log +----+---------+---------------------+-----------+ | id | user_id | won | collected | +----+---------+---------------------+-----------+ | 1 | 123 | 2024-01-20 18:53:21 | NULL | | 2 | 123 | 2024-01-21 10:33:45 | NULL | +----+---------+---------------------+-----------+ On Monday he goes to collect his tokens. You check he is allowed to by...
    SELECT COUNT(*) as tot FROM win_log WHERE user_id = ? AND collected IS NULL; If the returned count is > 0 he can go ahead and collect.
    You record the collection with...
    UPDATE win_log SET collected = NOW() WHERE user_id = ? AND collected IS NULL ORDER BY won LIMIT 1; You now have
    +----+---------+---------------------+---------------------+ | id | user_id | won | collected | +----+---------+---------------------+---------------------+ | 1 | 123 | 2024-01-20 18:53:21 | 2024-01-22 19:01:25 | | 2 | 123 | 2024-01-21 10:33:45 | NULL | +----+---------+---------------------+---------------------+  
  6. Barand's post in JavaScript Calculation Challenge: Updating Sub-Total and Total Less Amount Dynamically in a Table was marked as the answer   
    Use the javascript debugger to step through the code to see if it's doing what you expect and that the variables contain what you expect.
  7. Barand's post in MATCH AGAINST using my 'Terms' table and with 'Links' was marked as the answer   
    You need to join the two tables on the link_id so you match the terms to their parent link
    Do you have a specific reason for using a fulltext search? Would a simpler "LIKE" suffice. For example
    SELECT l.id as linkID , l.url , t.term FROM links l JOIN terms t ON l.id = t.link_id WHERE t.term LIKE '%ine%' OR l.url LIKE '%ine%'; linkID | url | term ----------+----------------+----------------- 2 | page2.php | zine 2 | page2.php | magazine 2 | page2.php | online
  8. Barand's post in Remove duplicate words was marked as the answer   
    PS
    I am in complete agreement with @kicken - you need to restructure your tables
     
    +---------------+ | link | +---------------+ | id (PK) |-----+ | url | | +---------------+ +---------------+ | | term | | +---------------+ | | id (PK) | +-----<| link_id (FK) | | term | +---------------+ So that your data looks like this... TABLE: link TABLE: term +-----+-------------------+ +-----+---------+---------------------+ | id | url | | id | link_id | term | +-----+-------------------+ +-----+---------+---------------------+ | 1 | page1.php | | 1 | 1 | Zeitgeist | | 2 | page2.php | | 2 | 1 | conspiracy theories | +-----+-------------------+ | 3 | 1 | 9/11 | | 4 | 1 | 9 11 | | 5 | 2 | zine | | 6 | 2 | magazine | | 7 | 2 | online | | 8 | 2 | newspaper | | 9 | 2 | press | | 10 | 2 | alternative | | 11 | 2 | coldtype | | 12 | 2 | world news | +-----+---------+---------------------+ Then all you need is a couple of simple queries. (My reply to your previous topic assumed were using a correctly normalized design as above)
  9. Barand's post in Test a value from a PHP was marked as the answer   
    That line always assigns the value "1" to $bob. When testing values for equality you need "==", therefore it should be
    if ($bob == 1)  
  10. Barand's post in Dynamic Student Selection: Populating Student Names Based on Class and Arms in a Non-Editable Session/Term Environment was marked as the answer   
    Sorry, missed the bit about the second select being year and not class. Try
    SELECT s.id , s.firstname , s.lastname , c.classname FROM class c JOIN student_class sc ON sc.classid = c.id AND semesterid = ? JOIN student s ON sc.studentid = s.id WHERE c.year = ? ORDER BY lastname;  
  11. Barand's post in Graph showing comparative analysis of students class performance. was marked as the answer   
    This query uses WINDOW function to get the class averages for each subject. (I am using MariaDB 11.1 but MySql 8 also has them). If you don't have then then us a subquery to get the class averages and join to that.
    SELECT studentid , subjectname , student_score , ROUND(AVG(student_score) OVER (PARTITION BY subjectname)) as mean FROM ( SELECT sc.semesterid, sc.classid, sc.studentid, s.subjectname, SUM(r.score) AS student_score FROM result r JOIN student_class sc ON r.studentclassid = sc.id JOIN course c ON r.courseid = c.id JOIN subject s ON c.subjectid = s.id JOIN semester sm ON sc.semesterid = sm.id WHERE sm.id = 10 AND sc.classid = 1 GROUP BY subjectname, studentid ) totals ORDER BY studentid, subjectname;  
  12. Barand's post in PHP function woes.. stuck was marked as the answer   
    Stick with your first code block. Instead of returning "true" on success return $email['fk_UserTypes_Id'].
    Then you just need to check the login return value to decide the next page.
  13. Barand's post in Feedback on Data model for Cinema ticket booking system was marked as the answer   
    Screen.rows, screen.columns, screen.capacity look like derived values to me - you can get that info from the seats for each screen.
    booking.ticket_date is no longer required - duplicates the screening.screen_on value.
    However, you need to consider the payment process. What if a user books seats and their payment is subsequntly declined?
    You would need to know who made the booking. Perhaps make the booking.ticket date an automatic timestamp and, on booking, set a status "payment pending". Set status to "paid" on successful payment. Periodically remove pending payments older than X minutes to release the seats for sale again.
  14. Barand's post in hi there im getting 0000-00-00 date value in database and html table i need helpi have tried all means was marked as the answer   
    What format is $_POST['date']?
    When binding the query params, $date is a string value - you specified "d" (double) and not "s" (string).
    Please use the code button "<>" when posting code in future.
  15. Barand's post in Styling the Success echo was marked as the answer   
    The above code is invalid php syntax. That's why there is no output.
    Try
    <?php echo "<div style='color: green;'>my_message</div>"; echo "my error"; echo 'my error 2'; ?>  
  16. Barand's post in php find earliest date in the format dd/mm/yyyy in a text file was marked as the answer   
    Alternatively
    usort($data, fn($a, $b) => isoDate($a) <=> isoDate($b)); echo $data[0]; //--> 03/11/2023 06 This is another text in the line function isoDate($text) { $d = substr($text, 0, 10); return DateTime::createFromFormat('d/m/Y', $d)->format('Y-m-d'); }  
  17. Barand's post in SQL WHERE CLAUSE syntax issue was marked as the answer   
    INSERT queries do not have a WHERE clause. You need to to use an "INSERT ... ON DUPLICATE KEY UPDATE ... "
    EG
     
    INSERT INTO table (id, col_a, col_b) VALUES (?, ?, ?) ON DUPLCATE KEY UPDATE col_a = VALUES(col_a), col_b = VALUES(col_b) ;  
  18. Barand's post in Is the MySQL PASSWORD function no longer valid? was marked as the answer   
  19. Barand's post in Use showDiv() multiply times. was marked as the answer   
    Such as by passing the id of the div to be shown/hidden as a function argument?
    function hideDiv(divid) { document.getElementById(divid).style.display = "none"; } . . . <button onclick="hideDiv('welcomeDiv')" class="loginBut" style="font-family: 'Handjet', cursive; font-size: 2EM;">Close</button>  
  20. Barand's post in Assistance thinking this through. was marked as the answer   
    I agree with Gizmola^.
    Using a multidimensional array ...
    $probs = [ 'QB' => [ 'RB' => [ 1 => 11.22, 2 => 3.91, 3 => 0.15 ], 'TE' => [ 1 => 5.17, 2 => 0.80, 3 => 0.00 ], 'QB' => [ 1 => 9.44, 2 => 0.00, 3 => 0.00 ], 'WR' => [ 1 => 10.46, 2 => 8.67, 3 => 4.53 ], 'K' => [ 1 => 3.81, 2 => 0.19, 3 => 0.00 ], 'D' => [ 1 => 2.85, 2 => 0.07, 3 => 0.00 ] ] // rinse and repeat with the other MVPs and FLEXs ]; $lineup = 'QB, WR, WR, RB, K'; $arr = array_map('trim', explode(',', $lineup)); $mvp = array_shift($arr); $counts = array_count_values($arr); $probability = 0; foreach ($counts as $p => $n) { $probability += $probs[$mvp][$p][$n]; } echo '<br>'.$probability; // 23.7  
  21. Barand's post in Sorting issue... was marked as the answer   
    ORDER BY level IS NULL, level
  22. Barand's post in What could be wrong was marked as the answer   
    Whe you join a table with M records to a table with N matching records you get M*N records returned. Therefore you are now totalling Nx more records than before.
    You need to ensure you join 1 row from 1 tablw with 1 matching record in the other. You can do this with subqueries to get the individal tables' totals.
    SELECT t1.customer_id , t2.total_sales , t3.amt_paid FROM customers t1 LEFT JOIN ( SELECT customer_id , SUM(total_price) as total_sales FROM tbl_sales GROUP BY customer_id ) t2 USING (customer_id) LEFT JOIN ( SELECT customer_id , SUM(amt_paid) as amt_paid FROM tbl_sales_total WHERE status = 0 GROUP BY customer_id ) t3 USING (customer_id) WHERE t1.customer_id = 489639 Also, you have a LEFT JOIN to tbl_sales_total t3. You therefore cannot use WHERE t3.status = 0. That condition needs to go into the join condition otherwise the query behaves as though it were an ordinary (INNER) JOIN
  23. Barand's post in PHP Get Maximum Value From DB and Set Start Value for Loop was marked as the answer   
    Something like this, maybe....
    BEFORE
    TABLE: stockid; TABLE: product +----+ (empty) | id | +----+ | 1 | | 2 | | 3 | +----+ CSV DATA ------------------------ "A1","A2","A3","A4","A5" "B1","B2","B3","B4","B5" "C1","C2","C3","C4","C5" RUN CODE
    $fp = fopen('products.csv', 'r'); // prepare product insert query $stmt = $pdo->prepare("INSERT INTO product (stock_id, prod_name) VALUES (?, ?)"); while ($row = fgetcsv($fp)) { $pdo->exec("INSERT INTO stockid (id) VALUES (NULL)"); $stock_id = $pdo->lastInsertId(); // get next stock id foreach ($row as $prod) { $stmt->execute([ $stock_id, $prod ]); } } fclose($fp); AFTER
    TABLE: stockid; TABLE: product +----+ +----+----------+-----------+ | id | | id | stock_id | prod_name | +----+ +----+----------+-----------+ | 1 | | 1 | 4 | A1 | | 2 | | 2 | 4 | A2 | | 3 | | 3 | 4 | A3 | | 4 | | 4 | 4 | A4 | | 5 | | 5 | 4 | A5 | | 6 | | 6 | 5 | B1 | +----+ | 7 | 5 | B2 | | 8 | 5 | B3 | | 9 | 5 | B4 | | 10 | 5 | B5 | | 11 | 6 | C1 | | 12 | 6 | C2 | | 13 | 6 | C3 | | 14 | 6 | C4 | | 15 | 6 | C5 | +----+----------+-----------+  
  24. Barand's post in Import data from excel to databse was marked as the answer   
    I'd do it like this...
    ################################################################################ # CREATE TEMPORARY STAGING TABLE # ################################################################################ $pdo->exec("CREATE TEMPORARY TABLE tempdata ( id int not null auto_increment primary key, sales_doc_type varchar(10), billing_date date, material varchar(10), gross_amount int, sales_office varchar(10), plant varchar(10) ) "); ################################################################################ # READ CSV, # # EXTRACT REQUIRED DATA, # # STORE IN ARRAY FOR INSERTION TO TEMP STAGING TABLE # ################################################################################ $fp = fopen('test1.csv', 'r'); $req_cols = [ 0 => 'sales_doc_type', 2 => 'billing_date', 11 => 'material', 25 => 'gross_amount', 45 => 'sales_office', 47 => 'plant' ]; $import_data = []; while ($allrow = fgetcsv($fp)) { $row = array_intersect_key($allrow, $req_cols); $randdays = rand(5,30); $row[2] = date('Y-m-d', strtotime($row[2])); $row[25] = str_replace(',', '', $row[25]); $import_data[] = vsprintf("('%s','%s','%s','%s','%s','%s')", $row); } fclose($fp); ################################################################################ # ADD RECS FROM ARRAY TO TEMP TABLE - 2000 AT A TIME # ################################################################################ $chunks = array_chunk($import_data, 2000); foreach ($chunks as $ch) { $sql = "INSERT INTO tempdata (sales_doc_type, billing_date, material, gross_amount, sales_office, plant) VALUES " . join(',', $ch); $pdo->exec($sql); } ###################################################################################################################### # # # Now we have the data from the csv stored in a temporary staging table # # which makes it easy to manipulate the data with queries to update our # # database tables with efficient queries rather than running multiple # # queries inside loops. # # # # NOTE - as I never received a reply to my question about the origin of the # # data used toupdate the members table I have had to omit that part # # of the processing. The UPDATE query will be similar to the INSERT # # below except it will update where there is a matching record # # # ###################################################################################################################### ################################################################################ # INSERT TEMPDATA REC INTO billing WHERE NO MATCHING billing_date IN members # ################################################################################ $pdo->exec("INSERT INTO billing (sales_doc_type, billing_date, gross_amount, sales_office, plant, material) SELECT t.sales_doc_type , t.billing_date , t.gross_amount , t.sales_office , t.plant , t.material FROM tempdata t LEFT JOIN members m ON DATE(t.billing_date) = m.billing_date WHERE m.billing_date IS NULL ");  
  25. Barand's post in Union Select was marked as the answer   
    perhaps
    select i.name as itemName, qs.name as sectionName, i.id as itemId, i.GBP, i.USD, i.CAD, cb.charge_by, COUNT(cp.item_id) > 0 as icConsumable from items i inner join quote_sections qs on i.section_id=qs.id inner join charge_by cb on i.charge_by_id = cb.id left join consumable_price cp ON i.id = cp.item_id group by i.id union select ci.name as itemName, qs.name as sectionName, concat("CI", ci.id) as itemId, ci.price as GBP, ci.price as USD, ci.price as CAD, cb.charge_by, 0 as isConsumable from custom_item ci inner join quote_sections qs on ci.section_id=qs.id inner join charge_by cb on ci.charge_by = cb.id  
×
×
  • 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.