Jump to content

Barand

Moderators
  • Posts

    24,566
  • Joined

  • Last visited

  • Days Won

    822

Everything posted by Barand

  1. That what MySql gave us AUTO_INCREMENT function for. Define you work order number as the PRIMARY KEY with AUTO_INCREMENT
  2. Just in case anyone is tempted to use this "shuffle and pray" shortcut approach to this problem I checked out its validity. I took arrays of N drivers and shuffled them N! times, storing each combination. I then checked to see how many were unique. These are the results ACB BAC BAC BAC CBA CBA 3 drivers: 3 duplicate combinations out of 6 (50%) ABCD ACDB ADBC ADBC ADCB BADC BCAD BCDA BCDA BDCA CABD CABD CBAD CBDA DABC DACB DACB DACB DBAC DBCA DBCA DCAB DCAB DCBA 4 drivers: 7 duplicate combinations out of 24 (29%) ABDCE ABDEC ABECD ABECD ABEDC ABEDC ACBDE ACDBE ACDBE ACDEB ADBEC ADEBC ADECB AEBDC AECBD AECDB AEDCB BACED BADCE BADEC BADEC BCAED BCDEA BCDEA BCEAD BDACE BDACE BDAEC BDAEC BDCAE BDCAE BDEAC BDECA BEDAC BEDAC BEDCA CABDE CABED CABED CAEDB CAEDB CAEDB CBAED CBDAE CBEAD CBEDA CBEDA CDABE CDAEB CDBAE CDBEA CDEAB CDEBA CDEBA CDEBA CDEBA CDEBA CEABD CEADB CEADB CEADB CEBDA CEDAB CEDAB CEDAB CEDBA DABCE DABCE DABCE DAEBC DBAEC DBCAE DBEAC DCABE DCBAE DCBEA DCBEA DCBEA DCEAB DCEBA DCEBA DEACB DEACB DEBAC DEBAC DEBCA DECAB DECAB DECBA DECBA DECBA EADBC EADBC EADBC EADBC EBACD EBACD EBACD EBACD EBCDA EBDCA EBDCA ECABD ECBAD ECBAD ECBDA ECBDA ECDAB ECDBA ECDBA EDABC EDABC EDACB EDACB EDACB EDBCA EDBCA EDCAB EDCBA EDCBA 5 drivers: 46 duplicate combinations out of 120 (38%) 6 drivers: 265 duplicate combinations out of 720 (36%) 7 drivers: 1841 duplicate combinations out of 5040 (36%) 8 drivers: 14761 duplicate combinations out of 40320 (36%) 9 drivers: 327861 duplicate combinations out of 362880 (90%) Verdict: Not fit for purpose. The code used to test: <?php $drivers = ['A','B']; $extra = ['C','D','E','F','G','H','I']; $factorials = [ 3 => 6, 4 => 24, 5 => 120, 6 => 720, 7 => 5040, 8 => 40320, 9 => 362880 ]; foreach ($extra as $e) { $drivers[] = $e; // add to drivers echo countUnique($drivers, $factorials); // test with N drivers } function countUnique($d, $facts) { $combos = []; $k = count($d); $f = $facts[$k]; for ($i=0; $i<$f; $i++) { shuffle($d); // shuffles n! times $str = join('',$d); // and stores each $combos[] = $str; // random combination } // output the smaller shuffled combo arrays to view duplicates if ($k < 6) { sort($combos); $chunks = array_chunk($combos, 12); foreach($chunks as $coms) echo join(' ', $coms)."<br>"; echo '<br>'; } $n = count(array_unique($combos)); // count how many were unique $n1 = $f - $n; // number of duplicate values $n2 = count($combos); // to check that n! were generated return sprintf('%d drivers: %6d duplicate combinations out of %6d (%d%%)<br><br>', count($d), $n1, $n2, $n1*100/$n2 ); } ?>
  3. Your code exits the function on the return statement so echo never called. Also those functions a very repetitive. Name your form inputs "qty[1]", "qty[2]" and "qty[3]" so they are posted as an array then your processing becomes a simple loop $prices = array ( 1 => 5.00, 2 => 3.00, 3 => 1.00 ); if (isset($_POST['qty'])) { $total = 0; foreach ($_POST['qty'] as $k => $qty) { $value = $qty * $prices[$k]; echo "Service $k : $value<br>"; $total += $value; // add value to the total } echo "Total : $total"; }
  4. My car isn't working at the moment. I've posted a photo of the car, can you tell me why it's not working?
  5. Change the WHERE clause to WHERE status = 2 AND DATE_FORMAT(timestamp, '%Y-%m') = DATE_FORMAT(CURDATE(), '%Y-%m')
  6. Have you included the line that increments the rank inside the foreach loop? ++$rank; // increment rank
  7. The second query should be "... FROM Accounts LEFT JOIN Transactions ..." Don't use "SELECT * ", specify the columns needed. You should be storing the Account IDs as foreign keys in the transactions table, not the account names. Are you sure the account names in the tables match exactly (no spelling errors or extra whitespace)?
  8. I wondered if you were still running queries inside a loop but apparently not. However, your were looping twice through the results. I have put the code I gave you for the rank in its correct place and removed the superfluous loop. (See comments) <?php // ob_start(); REMOVE, not required require('extra/header.php'); if(empty($_SESSION['user'])) { header("Location: login.php"); exit; } if($_SESSION['verifypend'] == 1) { header("Location: verifypend.php"); exit; } ini_set('display_errors', 1); error_reporting(E_ALL); $query = " SELECT u.username ,SUM(price) as price ,SUM(costs) as costs ,SUM(cargodamage) as cargodamage ,SUM(price - costs - cargodamage) as profit ,COUNT(driver) as 'deliveries' ,SUM(distance) as 'distance' FROM drive_routes dr INNER JOIN users u ON u.id = dr.driver WHERE status = 2 GROUP BY driver ORDER BY profit DESC "; try { $stmt = $db->prepare($query); $result = $stmt->execute(); } catch(PDOException $ex) { die("Failed to run query: " . $ex->getMessage()); } $rows = $stmt->fetchAll(); $count = $stmt->rowcount(); //$rank = 1; REMOVE // while ($rows) REMOVE // { // output row with $rank REMOVE // ++$rank; // increment it REMOVE // } REMOVE ?> <center><img src="http://pro-quest.co.uk/ITRecruitmentAgencyImages/Under_Construction-section.jpg" width="15%"></center><br> <div class="container"> <h1>Current rankings</h1> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Driver</th> <th>Profit</th> <th>Deliveries</th> <th>Distance</th> </tr> </thead> <?php // THIS SECTION BELOW IS WHERE THE REMOVED CODE SHOULD BE foreach($rows as $row): $rank = 1; ?> <tbody> <tr> <td><?php echo $rank; ?></td> // output rank <td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td> <td>€<?php echo htmlentities($row['profit'], ENT_QUOTES, 'UTF-8'); ?></td> <td><?php echo $row['deliveries']; ?></td> <td><?php echo htmlentities($row['distance'], ENT_QUOTES, 'UTF-8'); ?> KM</td> </tr> </tbody> <?php ++$rank; // increment rank endforeach; ?> </table> </div> </div> <?php require('extra/footer.php'); ?>
  9. Can we see the whole page.
  10. Do you mean the table would look like this, where user A is both Admin and Super User? mysql> SELECT * FROM permissions; +----+----------+------------+ | id | username | level | +----+----------+------------+ | 1 | A | Admin | * | 2 | B | Moderator | | 3 | C | Admin | | 4 | D | Super User | | 5 | E | Moderator | | 6 | A | Super User | * +----+----------+------------+ then WHERE level = 'Admin' AND level = 'Super User' will not find any records as there is no single record that has both values at the same time (impossible) mysql> SELECT username -> FROM permissions -> WHERE level = 'Admin' AND level = 'Super User'; Empty set (0.00 sec) Using OR instead of AND would produce mysql> SELECT username -> FROM permissions -> WHERE level = 'Admin' OR level = 'Super User'; +----------+ | username | +----------+ | A | | C | | D | | A | +----------+ However, to find only users with both mysql> SELECT A.username -> FROM permissions A -> INNER JOIN -> permissions B -> ON A.username = B.username -> AND A.level = 'Admin' -> AND B.level='Super User'; +----------+ | username | +----------+ | A | +----------+ Back to the original question. From the two arrays, $admins and $superusers, to find who is in both arrays use array_intersect() $admins = array ('A', 'C'); $superusers = array ('D', 'A'); $both = array_intersect($admins, $superusers); echo '<pre>',print_r($both, true),'</pre>'; /** RESULT ***** Array ( [0] => A ) ****************/
  11. WHERE level = 'Admin' AND level = 'Super User' would require level to have 2 values at the same time ??? Perhaps you mean WHERE level = 'Admin' OR level = 'Super User'
  12. $csv = fopen('my.csv', 'r'); $data = array(); while (list($contact_email, $contact_last, $contact_first) = fgetcsv($csv, 1024)) { $data[] = "('$contact_first', '$contact_last', '$contact_email')"; // order matches SQL INSERT order } fclose($csv); // use multiple insert $sql = "INSERT INTO contact (contact_first,contact_last, contact_email) VALUES "; $sql .= join(',', $data); $mysqli->query($sql);
  13. And your problem with that is what? SELECT prefix ,Title ,firstName ,middleName ,lastName ,houseNo ,Address1 ,postCode ,ContactNo ,DATE_FORMAT(DateOfBirth, '%d-%m-%y) as dob FROM customers
  14. As I said in reply #9 ^ $rank = 1; while (....) { // output row with $rank ++$rank; // increment it } Simples!
  15. You can reformat for display purposes in php using the date() function again or you can format in the sql using DATE_FORMAT() function EG SELECT DATE_FORMAT(dob, '%d-%m-%y') as dob FROM customers
  16. It would only matter if you are using LOAD DATA INFILE. If you are you need to specify the columns at the end of the statement
  17. I suggest you look up mysql_error in the php manual and see how it really should be used.
  18. You still need the "=" Try outputting the contents from mysql_error() after calling mysql_query()
  19. No!. One or the other, preferably "=". Use LIKE only when the user enters a partial value and preferably only use like with a wild card at the end. If you use '%...%' then SQL can not use indexes and will scan the whole table slowing down your query.
  20. Using the user's id you would select the user's record and display the current values in text boxes in a form (which would look similar to your input form). The user edits the data (don't allow changes to the id) then instead of INSERT you would use an UPDATE query to update the user's record.
  21. if($agefrom && $ageto !='') should be if($agefrom !='' && $ageto !='') You should check that there are search conditions before adding the "WHERE ". join()" bit otherwise you end up with an invalid syntax of SELECT * FROM profiles WHERE (See requinix's example in reply #2 ^ ) Are you sure there are records that meet all the entered criteria?
  22. @Birdmansplace (if you are still here after that short diversion) I have shown you how to get the combinations for my envisaged scenario using a simple cross join in the SQL. To use the scenario envisaged by grissom then the method is more complex. As it requires a recursive solution then read the data into arrays rather than have queries called recursively. The data (I restricted to 4 of each for brevity of output) $cars = [ 'Audi', 'BMW', 'Chrysler', 'Daewoo' ]; $drivers = [ 'Adam', 'Ben', 'Cathy', 'Diana' ] The code $k = count($cars); $thead = "<tr><th rowspan='2'>Round</th><th colspan='$k'>Cars</th></tr><tr><th>" . join('</th><th>', $cars) . "</th></tr>\n"; $tbody = ''; $results = []; combos($drivers, $results, []); // call the recursive function to get combinations foreach ($results as $k => $names) { $tbody .= "<tr><td>".(++$k)."</td><td>" . join('</td><td>', $names) . "</td></tr>\n"; } function combos($set, &$results, $tmp) { $k = count($set); if ($k==1) { $results[] = array_merge($tmp, $set); } else { // takes each one in turn and call with remaining set members foreach ($set as $k => $x) { $copy = $set; unset($copy[$k]); combos($copy, $results, array_merge($tmp, [$x])); } } } Output
  23. In your query, if religion if left empty then you search for ... OR religion LIKE '%%' which will select all records. Only put conditions for which there are values in the query. If you mixing OR and AND conditions, use (...) to specify the logic requires EG A OR B AND C do you want A OR (B AND C) which it will use with no parenthesis, or do you want (A OR B) AND C
  24. You need to convert the "gender is <value>" pseudocode statements to PHP/SQL condition statements EG gender = '$gender' And same with the join() statement at the end ... WHERE implode(' AND ', $conditions) Don't forget to sanitize all your POST variable with real_escape_string() before using them in the SQL statement.
  25. Keeping it simple, for the sake of my limited maths knowledge, let's say we have 3 cars (A,B,C) and 3 drivers (1,2,3). The combinations are then A1 B1 C1 A2 B2 C2 A3 B3 C3 which I count to be 9 (ie 3 x 3); Using the Grissom method the count would be 3! (ie 6), so which three would be left out?
×
×
  • 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.