-
Posts
24,551 -
Joined
-
Last visited
-
Days Won
821
Community Answers
-
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
-
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
-
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 & 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>
-
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 !?
-
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>
-
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>}
-
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.
-
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
-
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) {
-
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
-
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']. -
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
-
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 | +--------+------------+-------------+------------+---------------+------------+----------------+------------+---------------+
-
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>
-
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.
-
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>'; } }
-
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;
-
Barand's post in php code ckecher was marked as the answer
Have you thought about subtracting the smaller number from the larger one?
-
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
-
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'];
-
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.
-
Barand's post in How to manipulate multi-dimension array in PHP? was marked as the answer
OK - I've added the sort
usort($test, fn($a, $b) => $b['itemCount']<=>$a['itemCount']); // sort descending itemCount $seen = []; foreach ($test as $k => &$rec) { $rec['rolanID'] = array_diff($rec['rolanID'], $seen); // find new ids if ($rec['rolanID']) { // if there are some new ones ... $rec['itemCount'] = count($rec['rolanID']); // count them $seen = array_merge($seen, $rec['rolanID']); // add the new ones to those already seen } else unset($test[$k]); // if no ids, remove the array item } and I now get this (no duplicate 123)...
Array ( [0] => Array ( [supplier] => TEST2 DEPO [rolanID] => Array ( [0] => 456 [1] => 188 [2] => 200 [3] => 123 ) [itemCount] => 4 ) [1] => Array ( [supplier] => TEST DEPO [rolanID] => Array ( [1] => 234 ) [itemCount] => 1 ) [2] => Array ( [supplier] => DIFFERENT DEPO [rolanID] => Array ( [0] => 897 [1] => 487 [2] => 100 ) [itemCount] => 3 ) )
-
Barand's post in How to process the multi dimensional array into specific array? was marked as the answer
All you need to do is loop through your original array using foreach() and append the products to a new array, providing the required key values.
foreach ($orig as $rec) $new[ $rec['supplier'] ]['productID'][] = $rec['part_id']; Result for $new
Array ( [COOLDRIVE DISTRIBUTION] => Array ( [productID] => Array ( [0] => 2338117 ) ) [ROLAN] => Array ( [productID] => Array ( [0] => 2338117 [1] => 51154 ) ) )
-
Barand's post in Duplicate ID issue when trying to copy table row was marked as the answer
If you never want any data to be overwritten then you need always to insert a new record every time with a new id.
Ensure your table in the destination db has an auto_incrementing primary key, for example
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `studentname` varchar(20) DEFAULT NULL, `class_id` char(2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Let's start with db1.student and db2.student tables
db1.student db2.student +----+-------------+----------+ +----+-------------+----------+ | id | studentname | class_id | | id | studentname | class_id | +----+-------------+----------+ +----+-------------+----------+ | 1 | Peter | A1 | | 1 | Curly | A1 | | 2 | Paul | A2 | | 2 | Larry | A2 | | 3 | Mary | A3 | | 3 | Mo | A3 | +----+-------------+----------+ +----+-------------+----------+ To auto-generate a new key, the insert needs to exclude the id column. This means you cannot use "SELECT * ", you must define the column excepting the id. Similarly, the query must define the destination columns in the receiving table. So we have this (assuming we are connected to db1 as default db) ...
INSERT INTO db2.student (studentname, class_id) SELECT studentname, class_id FROM student WHERE id = 1 which, when executed, gives this in db2.student table
+----+-------------+----------+ | id | studentname | class_id | +----+-------------+----------+ | 1 | Curly | A1 | | 2 | Larry | A2 | | 3 | Mo | A3 | | 4 | Peter | A1 | +----+-------------+----------+
-
Barand's post in Date sorting not working in my html code was marked as the answer
All you needed to do was substitute your connection "$conn" for my "$pdo". My coding in this instance is mysqli/pdo neutral.
Remove the catch{} stuff.