-
Posts
24,584 -
Joined
-
Last visited
-
Days Won
826
Everything posted by Barand
-
<!DOCTYPE html> <html lang="en"> <head> <title>4 Queens</title> <meta charset="utf-8"> <style type='text/css'> table { border-collapse: collapse; } td { width: 40px; height: 40px; text-align: center; font-size: 16pt; } tr:nth-child(odd) td:nth-child(even), tr:nth-child(even) td:nth-child(odd) { background-color: lightgreen; } </style> </head> <body> <?php echo '<table border="1">'; for ($i = 1; $i <= 4; $i++) { echo "<tr>"; for ($j = 1; $j <= 4; $j++) { echo '<td>' . pow($i,2) + pow($j,2) . '</td>'; } echo '</tr>'; } echo "</table>\n"; ?> </body> </html> Dear Supreme Being, Can you put aside your arrogance for a moment and assume that we are 5 year olds (not a wall) and explain the theory behind your Pythagorean solution to the problem and why it "works" explain how the above square then tells us where the four queens should be positioned? I've found the 5s but there are no "opposite 10s", only 20s opposite the 5s, so the description is somewhat vague.. Having found the 5s, 10s, 20s and 25s (why those values in particular?), I now have 8 squares. Given that these are the candidates, the code then needs to find which 4 of these 8 fit the bill.
-
INSERT INTO user (fname,sex) values (inname, NULLIF(insex, '') );
-
In your php.ini file, ensure "display_startup_errors" is also set to On
-
Why the Freckle didn't you post the code that actually used to get the results you are complaining about. Once I got the data loaded, your query wouldn't even run without corrections to column names. Anyway - the answer to your question... They are in the wrong order because you order by your generated qNo column. I'd give up on that method. If you are using MariaDB, you can ORDER BY NATURAL_SORT_KEY(Q_id) If MySQL (which doesn't have that function), use FetchAll() to get an array of your results then natsort($results) use a custom sort which does a strnatcmp() on the Q_id column $res = $pdo->query(" ... "); $result = $res->FetchAll(); usort($results, fn($a,$b)=>strnatcmp($a['Q_id'], $b['Q_id'])); (Using sort($results) would have sorted using the values of the first column in each row - I assumed natsort() would do the same (silly me) )
-
FYI - it helps if the column defined as the primary key exists in the table! Same goes for the unique key in user table. Plus other syntax errors - I was trying to help but I gave up.
-
Your main problem is that mysql_*** functions have been deprecated for years and now no longer exist (unless you are using a really ancient version of PHP, in which case you should upgrade) You need to use mysqli or PDO (PDO is definitely recommended).
-
how to calculate a certain number of times a fraction?
Barand replied to NikitosKnyaz's topic in PHP Coding Help
I gained four inches just by giving up rugby, squash and badminton. -
how to calculate a certain number of times a fraction?
Barand replied to NikitosKnyaz's topic in PHP Coding Help
If it's your homework assignment, yes. If it isn't, what have you tried so far? -
how to calculate a certain number of times a fraction?
Barand replied to NikitosKnyaz's topic in PHP Coding Help
-
If you want to add another key to the results array add it to the query, and use @mac_gyver method.
-
... or ... $res = $pdo->query("SELECT Lvl , Sub FROM shadd_1 ORDER BY Lvl DESC, Sub "); $results = $res->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_COLUMN); foreach ($results as $lvl => $arr) { echo "$lvl <UL>"; foreach ($arr as $sub) { echo "<li>$sub</li>"; } echo "</ul>"; } FYI - the $results array (slightly simpler than the $data array in above post) looks like this.. Array ( [ULE] => Array ( [0] => BASIC lug [1] => BASIC lug ) [ACE] => Array ( [0] => ger ) )
-
And what are you wanting to do with that table? BTW, which values belong to which columns (do you have a problem with your keyboard's spacebar? If so you could have used the "table" button in the toolbar) What code have you tried so far?
-
Store the completion time instead of the duration. Count down until the end time is reached. My usual method is to store a variable in a hidden input field in PHP then access that field's value from javascript.
-
Check the number of rows affected by the query. https://www.php.net/manual/en/mysqli.affected-rows.php
-
@Psycho the PDO result/statement object is traversable whether you use query() or execute(). The mysqli result object is traversable (when the result of a query) but the statement object as a result of execute() is not (as well as having a different set of methods to process). This adds to my theory that mysqli result class and statement class were developed by two teams who never spoke to one another. EG $res = $pdo->query("SELECT name FROM reindeer"); foreach ($res as $r) { echo $r['name'] . "<br>"; } results... Comet Cupid Dasher Vixen Prancer Dancer Donner Blitzen
-
Don't use "select *". Specify the columns you need. Then use a foreach loop, not a for loop. Don't embed variables in the sql string, use prepared queries with placeholders, then execute with the variables passed as parameters. $sql_list = "SELECT ID FROM dados_socios WHERE usuario = ? ORDER BY ID"; $result_list = $conn->prepare($sql_list); $result_list->execute([$usario]); echo "<select>"; foreach {$result_list as $row) echo "<option>ID: {$row['ID']}</option>"; } echo "</select>";
-
PHP runs on the server. - Javascript runs on the client. On completion of the PHP it sends the page to the client where the javascript runs. At the time you "echo $array;" the js variable "i" does not yet exist. (Error thrown if turn on error reporting) By the time the javascript runs "$array" no longer exists.
-
fileinfo extension not working PHP 8.3.1
Barand replied to OkaygeBusiness999's topic in PHP Coding Help
Check the output from phpinfo() to make sure the php.ini file you edited is the one currently being used. -
I agree those are sufficient to define and draw the cell connections but, to be able to trace the paths through the network, it's a lot easier to know that A connects to B and also that B connects to A - that requires the top and left ones too. The database gave me an easy way to check for uniqueness and that I wasn't just recreating the same grid over and over.
-
With a little experimentation you could answer those questions yourself.
-
Looks very much like this... https://forums.phpfreaks.com/topic/323782-how-to-loop-through-array/?do=findComment&comment=1634454
-
Consider a student who has a maths exam at the end of each term. They score 60% in each of the first 2 terms but they are ill for the third so no score can be entered. If the "score" column in the result table is defined score int NOT NULL DEFAULT '0' then not inputting the score inserts a value of 0%. When the average score is calculated at the end of the year it is 40% ((60 + 60 + 0) / 3). On the other hand, if it is defined as score int thus allowing a NULL value if omitted, the the average is a much fairer 60% ((60 + 60) / 2). Consider NULL to be the absence of known value. Use NOT NULL when it is mandatory that a value is provided.
-
Because your table has 8 columns but you only want to insert into 3 of them, it will attempt to insert NULL values (or the columns' specified default values) into the remaining 5. Therefore, if a column is specified as NOT NULL, it should have a default value if you don't always populate it when inserting a new record. In addition, the id column should be an auto_incremented INT value by default and also excluded from the insert.
-
Welcome.
-
The advantage of SVG (Scalable Vector Graphics) is that, as the name implies, they are scalable. Resizing should not separate the elements. Take this example svg <svg width='100%' viewBox='0 0 100 100' > <circle cx='30' cy='30' r='25' fill='#333'/> <circle cx='70' cy='70' r='25' fill='#333'/> <line x1='30' y1='30' x2='70' y2='70' stroke='#333' stroke-width='8'/> </svg> The viewBox defines the source coordinate system, the width defines the output size. If I output the same image into two differently sized containers, the image expands to fit. EG <?php $svg = "<svg width='100%' viewBox='0 0 100 100' > <circle cx='30' cy='30' r='25' fill='#333'/> <circle cx='70' cy='70' r='25' fill='#333'/> <line x1='30' y1='30' x2='70' y2='70' stroke='#333' stroke-width='8'/> </svg> "; ?> <!DOCTYPE html> <html lang='en'> <meta charset='utf-8'> <head> <title>Example</title> </head> <body> <div style='width:20%'> <?=$svg?> </div> <div style='width:50%'> <?=$svg?> </div> </body> </html> You just need to to create all your connected cells inside a single SVG image. I have been having a go at this grid problem myself and now have version which has just created 500 unique 6x5 grid maps with no circular routes and no isolated groups of cells. Each time you try to connect two cells it first verifies that it will not result in a circular path. It also verifies that all cells are reachable from any other cell. The paths through the maps are saved to a database and the path is defined as UNIQUE to ensure no repeats are saved. My grid table is like this... Code... <?php require 'db_inc.php'; $pdo = mdbConnect('db1'); $invalid = 0; $num_maps_required = 500; // if 1 is required it is displayed. If multiple they as saved to database $gridWidth = 6; $gridHeight = 5; for ($g=0; $g<$num_maps_required; $g++) { ################################################################################ # BUILD THE GRID SQUARES ################################################################################ // Grid settings $svgSize = 100; $svgColor = '#333'; // Images (Icons) $iconExit = '🔒'; // Shows a lock $iconMonster = '🦖'; // Shows a dinosaur $iconStart = '🙂'; // Shows a smiley $iconTreasure = '🎁'; // Shows a gift // Calculate Monsters $monsters = ceil($gridHeight * $gridWidth * 0.15); // Calculate Treasures $treasures = floor($gridHeight * $gridWidth * 0.25); // Make iconBox and shuffle $iconBox = array_merge( array_fill(0, $treasures, $iconTreasure), array($iconExit), array_fill(0, $monsters, $iconMonster), array($iconStart), array_fill(0, $gridHeight * $gridWidth - $monsters - $treasures - 2, '') ); shuffle($iconBox); $cells = []; foreach ($iconBox as $k => $icn) { $r = intdiv($k, $gridWidth); $c = $k % $gridWidth; $poss = [ $k-$gridWidth, $k-1, $k+1, $k+$gridWidth ]; if ($r == 0) unset($poss[0]); if ($r == $gridHeight - 1) unset($poss[3]); if ($c == 0) unset($poss[1]); if ($c == $gridWidth - 1) unset($poss[2]); $cnx = array_fill_keys($poss, 0); $cells[] = [ 'icon' => $icn, 'cnxs' => $cnx, 'reachable' => [] ]; } ################################################################################ # RANDOMLY CREATE A LINK BETWEEN EACH PAIR OF ADJACENT COLUMNs AND # ONE OR TWO LINKS BETWEEN EACH PAIR OF ADJACENT ROWS. ################################################################################ $rows = range(0, $gridHeight-1); $cols = range(0, $gridWidth-2); shuffle($rows); foreach ($cols as $c) { $r = array_pop($rows); $s = $r * $gridWidth + $c; $e = $s + 1; connectCells($s, $e, $cells); } $rows = range(0, $gridHeight-2); $cols = range(0, $gridWidth-1); shuffle($cols); foreach ($rows as $r) { for ($i=0; $i<rand(1,2); $i++) { $c = array_pop($cols); $s = $r * $gridWidth + $c; $e = $s + $gridWidth; connectCells($s, $e, $cells); } } ################################################################################ # FIND THE UNCONNECTED CELLS AND CONNECT THEM TO THEIR NEIGHBOURS # -- NOTE coonectCells() CHECKS NO CIRCULAR PATH IS CREATED ################################################################################ # $loneCells = array_filter($cells, fn($v)=>empty(array_filter($v['cnxs']))); $loneCells = array_filter($cells, fn($v)=>count(array_filter($v['cnxs'])) < 2 ); uasort($loneCells, fn($a, $b)=>rand(0,1)? -1: 1); foreach ($loneCells as $start => $lc) { foreach ($lc['cnxs'] as $end => $v) { if (!$v ) { connectCells($start, $end, $cells); } } } ################################################################################ # MAP NOW GENERATED # - VERIFY # - SAVE THE ROUTES THROUGH THE MAZE FOR SUBSEQUENT ANALYSIS # - PRINT THE MAP ################################################################################ $cells[0]['reachable'] = []; findReachable(0, $cells, $cells[0]['reachable']); $pathLength = count($cells[0]['reachable']); $path = join(', ', $cells[0]['reachable']); if ($pathLength != $gridHeight * $gridWidth) { ++$invalid; echo "<h1>INVALID GRID MAP $invalid</h1>" ; echo "$pathLength cells: $path<br>"; } else switch ( $num_maps_required ) { case 1: echo printMap($gridHeight, $gridWidth, $cells); break; default: saveMap($pdo, $gridHeight, $gridWidth, $path, $pathLength, $cells); break; } } ################################################################################ # FUNCTIONS ################################################################################ function saveMap(PDO $pdo, $gridHeight, $gridWidth, $path, $pathLength, &$cells) { $pdo->beginTransaction(); try { $stmtg = $pdo->prepare("INSERT IGNORE INTO grid (height, width, path, path_length) VALUES (?, ?, ?, ?)"); $stmtgc = $pdo->prepare("INSERT INTO grid_cell (grid_id, cell_no, icon) VALUES (?, ?, ?)"); $stmtcnx = $pdo->prepare("INSERT INTO cell_cnx (grid_id, from_cell, to_cell) VALUES (?, ?, ?)"); $stmtg->execute( [ $gridHeight, $gridWidth, $path, $pathLength ] ); $grid_id = $pdo->lastInsertId(); #TODO grid_cell table, cell_cnx table foreach ($cells as $cno => $cl) { $stmtgc->execute( [ $grid_id, $cno, $cl['icon'] ] ); foreach ($cl['cnxs'] as $k => $v) { if ($v && $k > $cno) { $stmtcnx->execute( [ $grid_id, $cno, $k ] ); } } } $pdo->commit(); } catch(PDOException $e) { $pdo->rollBack(); throw $e; } } /** * Recursively searches all possible paths through the maze from start * and stores new reachable cells in array * * @param int $from starting cell * @param array pointer $cells cells array * @param array pointer $reachable all reachable cells */ function findReachable($from, &$cells, &$reachable) { foreach ($cells[$from]['cnxs'] as $k => $v) { if ($v) { if (!in_array($k, $reachable)) { $reachable[] = $k; findReachable($k, $cells, $reachable); } } } } function connectCells($start, $end, &$cells) { $cells[$end]['reachable'] = []; findReachable($end, $cells, $cells[$end]['reachable']); # # if cell is already reachable then connecting to it would result in a circular path # if (in_array($start, $cells[$end]['reachable'])) { return 0; } $cells[$start]['cnxs'][$end] = 1; $cells[$end]['cnxs'][$start] = 1; return 1; } function printMap ($rows, $cols, &$cells) { $cellSize = 80; $cellBgd = '#333'; $wid = $cols * $cellSize; $ht = $rows * $cellSize; $ix = 10; $iy = 10; $cx = $cy = $cellSize/2; $isz = $cellSize - 20; $ty = 47; $ty2 = $cellSize - 14; $svg = "<svg width='$wid' viewBox='0 0 $wid $ht'> <rect x='0' y='0' width='$wid' height='$ht' fill='linen' /> "; foreach ($cells as $k => $cell) { $transx = $k % $cols * $cellSize; $transy = intdiv($k, $cols) * $cellSize; $sColor = count(array_filter($cell['cnxs']))==1 ? '#aaa' : $cellBgd; $svg .= "<g transform='translate($transx, $transy)' > <rect x='$ix' y='$iy' width='$isz' height='$isz' rx='8' ry='8' fill='$cellBgd' stroke='$sColor' stroke-width='2'/> "; foreach ($cell['cnxs'] as $c => $connected) { if ($c > $k && $connected) switch ($c - $k) { case 1: $svg .= "<path d='M $cx $cy h $cellSize' stroke='$cellBgd' stroke-width='10' />\n"; break; case $cols: $svg .= "<path d='M $cx $cy v $cellSize' stroke='$cellBgd' stroke-width='10' />\n"; break; } } $svg .= "<text x='$cx' y='$ty' font-size='24px' fill='#FFF' text-anchor='middle'>{$cell['icon']}</text> <text x='$cx' y='$ty2' font-size='12px' fill='#FFF' text-anchor='middle'>$k</text> </g> "; } $svg .= "</svg>\n"; return $svg; } ?> The next step is to be able to select a stored grid map from the DB and display it.