Jump to content

Barand

Moderators
  • Posts

    23,362
  • Joined

  • Last visited

  • Days Won

    693

Community Answers

  1. 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>"; }  
  2. 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);
  3. 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');  
  4. 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.
     
  5. 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
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT TIMESTAMP  
  6. 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  
  7. 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>  
  8. 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 !?
  9. 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>  
  10. 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>}  
  11. 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?
    EDIT:
    I would have expected the squad to have a key (team_id, game_id) to show is was the team squad for that game.
  12. 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

  13. 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) {  
  14. 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  
  15. 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'].
  16. 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  
  17. 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 | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+  
  18. 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   
    try
    <?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>  
  19. 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.
  20. Barand's post in Accessing variable from a string was marked as the answer   
    Put them in an array,
    $var = [ "hello", "good bye", "back soon"]; for ($x=0; $x<3; $x++) { echo $var[$x] . '<br>'; } or
    $var0 = "hello"; $var1 = "good bye"; $var2 = "back soon"; test($var0, $var1, $var2); function test(...$vars) { for ($x=0; $x<3; $x++) { echo $vars[$x] . '<br>'; } }  
  21. Barand's post in Days until a date was marked as the answer   
    Try
    $futureDate = new DateTime('dec 25'); $now = new DateTime('today'); if ($now > $futureDate) { $futureDate->modify('+1 year'); } echo $now->diff($futureDate)->days;  
  22. Barand's post in php code ckecher was marked as the answer   
    Have you thought about subtracting the smaller number from the larger one?
  23. Barand's post in accessing global variables was marked as the answer   
    function first() { $A = [1,2,3,4,5]; return $A; } function second($arr) { return array_sum($arr); } $myarray = first(); echo second( $myarray ); //-> 15 // or echo second( first() ); //-> 15  
  24. Barand's post in Get Value of JSON Array was marked as the answer   
    <?php $jsn = '[{"OrgID":"1234567890987654321","OrderNumber":"M123456","OrigOrderNumber":"","Placed":"2022-08-17T14:04:47.653","PostCode":"AB1 2CD","BackOfficeOrderNumber":"12345678","CustomerName":"My Name","OutletName":"My Name Two","OrderStatus":"Delivered","OrderRef":"O-0012345678","AddressCount":1}]'; //convert to an array $arr = json_decode($jsn, 1); // output the array to view structure echo '<pre>' . print_r($arr, 1) . '</pre>'; ?> The resulting array is

    and you then access you required value by following the array keys (indicated), so you want
    $order_number = $arr[0]['OrderNumber'];  
  25. Barand's post in How to scrape data without api? was marked as the answer   
    I did.
    You could also try entering "curl" in the search box at the top of this page.
×
×
  • 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.