Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Community Answers

  1. Barand's post in Enable PHP code in HTML was marked as the answer   
    PHP code must be in a .php file to be executed (with a standard configuration) However a .php file does not need to contain any php code, it can be html only. So any html you can do in an .html file should work in a .php file.
    Define the background image in your css - it should work the same in either.
  2. Barand's post in Derive field name from accepted / known field name [dimensional or array fieldname] was marked as the answer   
    The id of an element must be unique, so change those id="name" to class="name"
    data attributes are useful. Give each pair of fields the same data-id value. (Easier than parsing names)
    For example
    <!DOCTYPE=html> <html lang="en"> <head> <meta charset='utf-8'> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type='text/javascript'> $(function() { $(".weekday").click( function() { let id = $(this).data("id") // get data-id value of checkbox let time = $(".name[data-id="+id+"]") // find timing inut with same data-id value if ($(this).is(":checked")) { $(time).focus() } else { $(time).val("") } }) }) </script> </head> <body> <input name="weekday[8]" type="checkbox" value="21" class="weekday" checked data-id="8"> Monday <br> Timing <input name="timing[8]" type="text" class="name" value="11" size="45" data-id="8"> <br><br> <input name="weekday[9]" type="checkbox" value="99" class="weekday" data-id="9"> Tuesday <br> Timing <input name="timing[9]" type="text" class="name" value="" size="45" data-id="9"> <br><br> <input name="weekday[10]" type="checkbox" value="77" class="weekday" data-id="10"> Wednesday <br> Timing <input name="timing[10]" type="text" class="name" value="" size="45" data-id="10"> </body> </html>  
  3. Barand's post in add toolo tips to hyperlink was marked as the answer   
    You need to put it in quotes otherwise it accepts the value up to the first space only
    <a href="StatementEntry.php?ID=<?=$ID?>" title="<?=$AddDate?>"> ^ ^  
  4. Barand's post in Like Dislike front end working but in database number is not increasing .... Pls help me was marked as the answer   
    Have you got php error reporting turned on?
    Have you looked at your browser developer tools ( network tab ) to check that the ajax info is being passed OK?
    Check that your queries are working correctly - put this code just before your mysqli_connect
  5. Barand's post in Student class position generation was marked as the answer   
    Here's how I'd do it without the windowing functions
    Note: if you have
    A 98 B 98 C 95 the A and B a re ranked 1, C is ranked 3.
    $grade_class = 'JS1'; $grade_name = 'EMMANUEL OKONJI'; $grade_term = 'First Term'; $grade_year = '2022'; $student_class_position = $conn->prepare( "SELECT rank FROM ( SELECT ord.grade_id , @seq := @seq+1 as seq , @rank := CASE WHEN ord.grand_total = @prev THEN @rank ELSE @seq END as rank , @prev := ord.grand_total as grand_total FROM ( SELECT grade_id , g.grand_total FROM student_grade g ORDER BY grand_total DESC LIMIT 18446744073709551615 ) ord JOIN (SELECT @seq:=0, @rank:=0,@prev:=0) init ) ranked JOIN student_grade g ON g.grade_id = ranked.grade_id WHERE class = ? AND name = ? AND term = ? AND year = ? "); $student_class_position->bind_param('ssss', $grade_class, $grade_name, $grade_term, $grade_year); $student_class_position->execute(); $student_class_position->bind_result($position); $student_class_position->fetch(); echo $position; I used a prepared statement so user data is not inserted into the query (SQL injection attack prevention)
  6. Barand's post in Function in php was marked as the answer   
    OK - here's the "add" case...
    case 'add': $result = 0; foreach ($exp['children'] as $child) { $result += evaluate($child); } break;  
  7. Barand's post in PHP PDO query within while loop only returns first row was marked as the answer   
    Slightly different approach then. Store the category query results in an array.
    $stmt = $pdo->query("SELECT categoryID , categoryName FROM tbl_categories WHERE categoryActive = 1 ORDER BY categoryID "); $cat_options = []; /// store cat data in array foreach ($statement as $row) { $cat_options[$row['categoryID']] = $row['categoryName']; } // main loop here while ($row = $stmt->fetch()) { echo "<select name='categoryID' class='select200px' required> <option value=''>Select...</option>"; foreach ($cat_options as $id => $cat) { $sel = $row['categoryID'] == $id ? 'selected' : ''; echo "<option $sel value='$id'>$cat</option>"; } echo "</select>"; }  
  8. Barand's post in issue with a random number being inserted in the place of the right value in a query was marked as the answer   
    Looks like you are trying to store a 19 digit number in an INT field with a maximum value of 2147483647. Your voucher code is actually a string that consists of numeric characters (like a phone number) so store it as one, say VARCHAR(20);
  9. Barand's post in get all keys that match value from multidimensional array was marked as the answer   
    Use array keys instead of array_search
    $results = array_keys(array_column($data, 'oname'), 'Border.aao');  
  10. Barand's post in Warning: Undefined array key, the query mysql is working well, is a php problem was marked as the answer   
    The column names in the query results wil be
    id_chocolate name_chocolate id_type_chocolate type_chocolate id_chocolate The tablename. prefixes are not part of them.
  11. Barand's post in PHP MYSQL AJAX LONG POLLING was marked as the answer   
    Even though it is named "lastmodified", that will record the time the record was inserted. If you want to record when it was modified you need
  12. Barand's post in Verify value is UNIQUE in list was marked as the answer   
    $arr = [ 1, 2, 3, 1, 4, 5, 2, 6, ]; $arr2 = array_unique($arr); // to force a unique set of values $arr3 = array_count_values($arr); // to verify they are all unique  
  13. Barand's post in Simple show hide html span solution was marked as the answer   
    As basic as it gets...
    <!DOCTYPE html> <html lang="en"> <head> <title>Sessions &amp; Terms</title> <meta charset="utf-8"> <script type='text/javascript'> function showDiv() { let thediv = document.getElementById("mydiv") if (thediv.style.display == "block") { thediv.style.display = "none" } else { thediv.style.display = "block" } } </script> <style type='text/css'> #mydiv { display: none; } </style> </head> <body> <button onclick='showDiv()'>Show Div</button> <br> <div id='mydiv'> <h1>Hello, world</h1> </div> </body> </html>  
  14. Barand's post in how to count the number of rows preceding a given row? was marked as the answer   
    Here's a quick and dirty solution
    SELECT users_name , total_donated , total_received , ( SELECT COUNT(*)+1 FROM random_donation_clash rd2 WHERE rd2.total_received > rd1.total_received ) AS rank FROM random_donation_clash rd1 WHERE total_participant = 1 ORDER BY total_received DESC Still using mysqli !?
  15. Barand's post in Saving SELECT value on form was marked as the answer   
    Set the "selected" attributes of the options containing the selected values in each dropdown
    For example
    <?php if ($_SERVER['REQUEST_METHOD']=='POST') { echo "You ordered the following quantities<br>"; foreach ($_POST['qty'] as $i => $qty) { if ($qty) { echo "Item $i : $qty<br>"; } } echo "<hr>"; } function qtyOptions($current) { $opts = ''; for ($i=0; $i<11; $i++) { $sel = $i==$current ? 'selected' : ''; $opts .= "<option $sel value='$i'>$i</option>\n"; } return $opts; } ?> <!DOCTYPE html> <html lang='en'> <head> <title>Example</title> <meta charset='utf8'> </head> <body> <form method='POST'> Item 1 <select name='qty[1]'><?= qtyOptions($_POST['qty'][1] ?? 0)?></select> <br> Item 2 <select name='qty[2]'><?= qtyOptions($_POST['qty'][2] ?? 0)?></select> <br> Item 3 <select name='qty[3]'><?= qtyOptions($_POST['qty'][3] ?? 0)?></select> <br> <br> <input type='submit'> </form> </body> </html>  
  16. Barand's post in trying to make a div parent of all rows pulled from database was marked as the answer   
    At the moment you appear to have something like this
    start loop { <div> <div> <table> <tr> headings </tr> <tr> data </tr> </table> </div> </div>} } end loop It sound like what you want is this
    <div> <div> <table> <tr> headings </tr> start loop { <tr> data </tr> } end loop </table> </div> </div>}  
  17. Barand's post in For each in mysql query was marked as the answer   
    Does this come close to what you were after?
    SELECT p.first_name , p.last_name , p.id as playerid , sum(runs_scored) as runs FROM game g JOIN player p ON g.batting_first = p.team_id JOIN deliveries d ON p.id = d.on_strike_batter_id AND g.id = d.game_id WHERE g.id = 51 GROUP BY p.id ; +------------+-----------+----------+------+ | first_name | last_name | playerid | runs | +------------+-----------+----------+------+ | Brian | Lara | 20 | 58 | | Freddie | Flintoff | 21 | 46 | +------------+-----------+----------+------+  
    That is what I thought but what connects a squad to team?
    I would have expected the squad to have a key (team_id, game_id) to show is was the team squad for that game.
  18. Barand's post in Dynamic Menu - Active link issue was marked as the answer   
    No need to mess about exploding the URI - just use $_GET['page'].
    <style type='text/css'> a { color: gray; text-decoration: none; } a.active { color: red; font-weight: 600; } </style> <?php $selectedPage = $_GET['page'] ?? ''; // get selected page (or empty if there isn't one) $pageArray = array( 'Page1', 'Page2', 'Page3', 'Page4' ); echo "<ul>\n"; foreach ($pageArray as $p) { $act = $selectedPage == $p ? 'active' : ''; // if this is the selected page, add 'active' to class echo "<li><a class='pageitem $act' href='?page=$p'>$p</a></li>"; } echo "</ul>\n"; ?> Result

  19. Barand's post in Is this segment of code a vulnerability ? was marked as the answer   
    It's poor SQL code.
    Any data returned by the "*" in the select will be meaningless. Because you are using an aggregation function the LIMIT is redundant - there will only be a single row containing the count. It is better to use a column alias for functions $stmt = $pdo->prepare("SELECT count(*) as total FROM users WHERE forgotten_code=?"); $stmt->execute([$_GET['reset']]); $check = $stmt->fetch(); if ($check['total'] > 0) {  
  20. Barand's post in Not working properly. Grabbing name. was marked as the answer   
    Overwriting your first $stmt object with the second one perhaps?
    A couple of DON'TS for you...
    Don't use SELECT * - specify just the columns you need. That makes it more efficient and people like us can see what the query is doing. Don't run queries inside loops like that. Use a single query with a JOIN SELECT jc.user_id , u.name FROM joined_chats jc JOIN users u ON jc.user_id = u.user_id WHERE jc.room_id = ? AND NOW() <= jc.date_expire ORDER BY user_id  
  21. Barand's post in Fetch Response is drive me crazy 🤪 was marked as the answer   
    That above section of code is totally FUBAR
    You test the value of $cat['category'] and afterwards decide to see if it is set! Then having found it isn't set, you allocate this non-existant variable value to $_SESSION['category'].
  22. Barand's post in I wish to create a display page that will display results from searching the full name but always displays the entire file regardless of what is typed in was marked as the answer   
    The first thing I'd do is convert the file data into something that is easily processed...
    $filedata = file('test.txt', FILE_IGNORE_NEW_LINES); # # organise text file data into a manageable structured array # $data = []; foreach ($filedata as $line) { $rec = []; $fields = explode('|', $line); foreach ($fields as $f) { list($k, $v) = explode(':', $f); $rec[trim($k)] = trim($v); } $data[] = $rec; } giving
    $data = Array ( [0] => Array ( [Name] => John Doe [Email] => johnd@gmail.com [Staff ID] => SS1234 [Gender] => Male [School] => FECS ) [1] => Array ( [Name] => Jane Doe [Email] => doejane@gmail.com [Staff ID] => SS3454 [Gender] => Female [School] => SFS ) [2] => Array ( [Name] => Scott Doe [Email] => does@gmail.com [Staff ID] => SS9087 [Gender] => Male [School] => FBDA ) [3] => Array ( [Name] => Kelly Doe [Email] => kellydoe@gmail.com [Staff ID] => SS2093 [Gender] => Female [School] => SFS ) ) Now it's simple to loop through the array to find the record you want
    for each ($data as record} if (record is required ) output record contents end if end for each  
  23. Barand's post in how to display data value in a row was marked as the answer   
    If you had data for every day for symbol it would be relatively simple
    SELECT a.symbol , a.date as today , a.price as today_price , b.date as weekago , b.price as last_wk_price , c.date as monthago , c.price as last_mth_price , d.date as yearago , d.price as last_yr_price FROM sampletable a LEFT JOIN sampletable b ON a.symbol = b.symbol AND b.date = a.date - INTERVAL 7 DAY LEFT JOIN sampletable c ON a.symbol = c.symbol AND c.date = a.date - INTERVAL 1 MONTH LEFT JOIN sampletable d ON a.symbol = d.symbol AND d.date = a.date - INTERVAL 1 YEAR WHERE a.date = CURDATE(); which gives
    ++--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+ | symbol | today | today_price | weekago | last_wk_price | monthago | last_mth_price | yearago | last_yr_price | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+ | ABC | 2022-09-30 | 19.24 | 2022-09-23 | 5.96 | 2022-08-30 | 5.30 | 2021-09-30 | 3.86 | | DEF | 2022-09-30 | 19.52 | 2022-09-23 | 10.15 | 2022-08-30 | 7.61 | 2021-09-30 | 16.59 | | XYZ | 2022-09-30 | 15.00 | | | 2022-08-30 | 15.11 | | | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+ ABC and DEF have daily data whereas XYZ on ly has 1 or 2 per week so, as you see, some results are missing. The tricky part is finding the closest date in the table to the required date. My solution was to use a MySQL user defined function.
    CREATE FUNCTION `nearestDate`(sym varchar(20), thedate date) RETURNS date READS SQL DATA BEGIN DECLARE v_closest DATE; DECLARE v_mindiff INT; SELECT date INTO v_closest # do we have the exact date? FROM sampletable WHERE symbol = sym AND date = thedate LIMIT 1; IF v_closest IS NOT NULL THEN # if we do, return it RETURN v_closest; END IF; SELECT y.date INTO v_closest # find smallest date difference FROM ( SELECT symbol , MIN(abs(datediff(date, thedate))) as mindiff FROM sampletable WHERE symbol = sym ) x JOIN # and match to find the date ( SELECT date FROM sampletable WHERE symbol = sym ) y ON abs(datediff(y.date, thedate)) = x.mindiff; RETURN v_closest; # return found date END The query using that function becomes
    SELECT a.symbol , a.date as today , a.price as today_price , b.date as d7 , b.price as last_wk_price , c.date as d30 , c.price as last_mth_price , d.date as d365 , d.price as last_yr_price FROM sampletable a LEFT JOIN sampletable b ON a.symbol = b.symbol AND b.date = nearestDate(a.symbol, curdate()-interval 7 day) LEFT JOIN sampletable c ON a.symbol = c.symbol AND c.date = nearestDate(a.symbol, curdate()-interval 1 month) LEFT JOIN sampletable d ON a.symbol = d.symbol AND d.date = nearestDate(a.symbol, curdate()-interval 1 year) WHERE a.date = curdate(); now giving
    +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+ | symbol | today | today_price | d7 | last_wk_price | d30 | last_mth_price | d365 | last_yr_price | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+ | ABC | 2022-09-30 | 19.24 | 2022-09-23 | 5.96 | 2022-08-30 | 5.30 | 2021-09-30 | 3.86 | | DEF | 2022-09-30 | 19.52 | 2022-09-23 | 10.15 | 2022-08-30 | 7.61 | 2021-09-30 | 16.59 | | XYZ | 2022-09-30 | 15.00 | 2022-09-25 | 2.87 | 2022-08-30 | 15.11 | 2021-09-29 | 4.20 | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+  
  24. Barand's post in Using the isset function in php I want to display a confirmation message but its not showing properly was marked as the answer   
    <?php if (isset($_GET["leapyear"]) && !empty($_GET['leapyear'])) { $result = (is_leapyear($_GET["leapyear"])) ? "<span style=\"color:#008631;\">{$_GET['leapyear']} is a leap year</span>" : "<span style=\"color:#FF0000;\">{$_GET['leapyear']} is not a leap year</span>" ; } else $result = '' ; function is_leapyear($year){ if(is_numeric($year)){ if($year%4 == 0) { if($year%100 == 0) { return ($year%400 == 0); } else return true; } } return false; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Leap year form</title> </head> <body> <?= $result ?> <h1>Leap Year</h1> <form method = "get" > <label for="leapyear">Enter a year</label> <input type="text" name="leapyear" id="leapyear" autofocus/> <p><input type="submit" name="confirm" value="Check For Leap Year" /></p> </form> </body> </html>  
  25. Barand's post in Unsupported operand types: int + string in after ( php 8 update) was marked as the answer   
    Sounds like one or more of those get_fields is an empty string.
  • 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.