Jump to content

Barand

Moderators
  • Posts

    24,566
  • Joined

  • Last visited

  • Days Won

    822

Everything posted by Barand

  1. Here's an example of my method The javascript increments/decrements a counter variable when a checkbox is checked/unchecked and puts the counter value in the corresponding text field. When processing the form we get the ids that were selected from the checkboxes. This gives our IN (x,y,z) for the selection from the table. This won't affect the order of the selection since IN (x,y,z) gives the same results as IN (z,y,x). To get the right order we specify the order in which we want the id field to be selected using ORDER BY FIELD(id, y,x,z). We get the y,x,z by sorting on the $_GET['seq'] values. <?php $mysqli = new mysqli(HOST,USERNAME,PASSWORD,'test'); /** my data ******************************************* CREATE TABLE candidate ( id int not null auto_increment primary key, name varchar(40) ); INSERT INTO candidate (name) VALUES ('Anne Adamson'), ('Ben Brown'), ('Charles Cummins'), ('David Dent'), ('Emma Ellis'), ('Fiona Fleming'), ('George Glover'), ('Henry Horner'), ('Ian Illingworth'), ('Jane Jenkins'); *******************************************************/ // // process the voting form // $results = ''; if (isset($_GET['candidate'])) { $list = join(',', $_GET['candidate']); // selected candidates' ids // find the order they were selected $seqarray=[]; foreach ($_GET['seq'] as $id => $seq) { if ($seq) { $seqarray[$seq] = $id; } } ksort($seqarray); // sort ids into correct sequence $seqlist = join(',', $seqarray); // get the candidates in the required order $sql = "SELECT name FROM candidate WHERE id IN ($list) ORDER BY FIELD(id,$seqlist)"; $results = "You voted for<ol>"; $res = $mysqli->query($sql); while ($row = $res->fetch_row()) { $results .= "<li>$row[0]</li>"; } $results .= "</ol></hr>\n"; } // // create the voting input form // $sql = "SELECT id , name FROM candidate ORDER BY id "; $res = $mysqli->query($sql); $clist = "<table>\n"; while (list($id, $name) = $res->fetch_row()) { $clist .= "<tr> <td>$name</td> <td><input type='checkbox' name='candidate[]' value='$id' class='candidate'> <td><input type='text' name='seq[$id]' id='seq$id' size='2' class='seq' readonly> <tr>\n"; } $clist .= "</table>\n"; ?> <!DOCTYPE html> <html> <head> <title>Voting Form</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type='text/javascript'> var counter = 0; $().ready(function() { $("#btnReset").click(function(){counter=0;}) $(".candidate").click(function() { var id = $(this).val(); if (this.checked) { if (counter < 3) { ++counter; $("#seq"+id).val(counter); } else { this.checked = false; } } else { --counter; $("#seq"+id).val(''); } }) }) </script> </head> <body> <?=$results?> <form> <h3>Select 3 candidates in order of preference</h3> <?=$clist?> <input type='submit' name='btnSubmit' value='Vote'> <input type='reset' name='btnReset' id='btnReset' value='Reset'> </form> </body> </html>
  2. You need to save the changes so you do not reset the input each time foreach($result as $row){ // set replacement to be the string from db $str = file_get_contents("templates/staff.html", true); $replace = $row['content']; $srch = $row['location']; $str = $this->replace($srch, $replace, $str); file_put_contents("templates/staff.html", $str); // ADD }
  3. Most of your problems are to do with "variable scope". Variables used inside functions only exist within that function. so public function Init($n, $db, $g, $nl) { $Name = $n; $Database = $db; $Game = $g; $NoticeLeave = $nl; } needs to be like this to set the class properties public function Init($n, $db, $g, $nl) { $this->Name = $n; $this->Database = $db; $this->Game = $g; $this->NoticeLeave = $nl; } The same goes for your "$struct" array in the "AddDefinition()" function. Also you should avoid globals (which,BTW, should have been global $struct. A better way is for your function to return the instance then add it to the array. Finally, $struct is an array of objects and not an object so you cannot use $struct->name. Use foreach to loop through the array. class GameStruct { public $Name; public $Database; public $Game; public $NoticeLeave; public function Init($n, $db, $g, $nl) { $this->Name = $n; $this->Database = $db; $this->Game = $g; $this->NoticeLeave = $nl; } } function AddDefinition( $name, $database, $game, $notice ) { $instance = new GameStruct; $instance->Init( $name, $database, $game, $notice ); return $instance; } $struct = Array(); $struct[] = AddDefinition( "leavecsgo", "comp_user", "Csgo", "Du har nu lämnat CS:GO-turneringen!" ); $struct[] = AddDefinition( "leavesmite", "comp_user", "Smite", "Du har nu lämnat Smite-turneringen!" ); $struct[] = AddDefinition( "leavefifa", "comp_user", "Fifa", "Du har nu lämnat Fifa-turneringen!" ); $struct[] = AddDefinition( "leavehearthstone", "comp_user", "Hearthstone", "Du har nu lämnat Hearthstone-turneringen!" ); $struct[] = AddDefinition( "leavedota2", "comp_user", "Dota2", "Du har nu lämnat Dota2-turneringen!" ); foreach ($struct as $sobj) { if( !isset( $_POST[ $sobj->Name ] ) ) { $sql = $con->query("DELETE FROM `{$sobj->Database}` WHERE Username='{$Username}' AND Game='{$sobj->Game}'"); $format = 'alert("%s");'; echo '<script >'; echo sprintf( $format, $sobj->NoticeLeave ); echo '</script>'; } }
  4. That is not what the code you posted shows. We cannot help with your code if you post something different from what you are really doing.
  5. That error is a result of your processing of the query (code not shown), not the query itself. WHERE orders.due_date BETWEEN '2014-01-01' AND '2016-08-21' was OK. Do you really have future orders? Or do you want WHERE orders.due_date BETWEEN '2014-01-01' AND CURDATE()
  6. Are you asking how to subtract 1 day from $data_P?
  7. Because there is no record in course table where the course.id matches the user.course for Emma in the user table
  8. you are missing the comma before SUM and you have too many "WHERE"s. PS It is more useful to tell us what you are trying to do instead of what you are not trying to do
  9. yes, but neither will prevent you adding (2,3) and (3,2)
  10. You could set a rule that the lower id is the user and higher id is the friend when adding the record and put a unique constraint on (user_id, friend_id)
  11. A schema like this here http://forums.phpfreaks.com/topic/297801-how-can-i-write-a-query-select-from-table-where-a-pair-of-record-is-not-there/?do=findComment&comment=1518909 would fit that requrement
  12. this line $str = file_get_contents("templates/staff.html", true); needs to be before the loop otherwise you reset the content each time
  13. If you want to apply that rule then create a subquery to get both sets (user/friend and friend/user) SELECT user_id , friend_id FROM friend WHERE user_id = 2 UNION SELECT friend_id , user_id FROM friend WHERE friend_id = 2 +---------+-----------+ | user_id | friend_id | +---------+-----------+ | 2 | 3 | | 2 | 4 | | 2 | 1 | +---------+-----------+ then left join with that instead of the friend table SELECT u.id , u.name as non_friend FROM user u LEFT JOIN ( SELECT user_id , friend_id FROM friend WHERE user_id = 2 UNION SELECT friend_id , user_id FROM friend WHERE friend_id = 2 ) f ON u.id = f.friend_id WHERE u.id <> 2 AND f.friend_id IS NULL ORDER BY id; +----+------------+ | id | non_friend | +----+------------+ | 5 | user 5 | +----+------------+
  14. All arrays have keys $result = [ ['string'=>'replacement 1', 'template'=>'template1'], ['string'=>'replacement 2', 'template'=>'template2'], ]; echo '<pre>',print_r($result, true),'</pre>'; gives Array ( [0] => Array ( [string] => replacement 1 [template] => template1 ) [1] => Array ( [string] => replacement 2 [template] => template2 ) )
  15. <?php $paths = [ 'B' => 'C', 'A' => 'B', 'C' => 'D' ]; $orig = 'A'; $dest = 'D'; $start = $orig; $end = ''; while ($end != $dest) { $end = $paths[$start]; echo "$start —> $end<br>"; $start = $end; } ?>
  16. isset() is for checking if PHP variables exist, not for external physical entities such as a database. If the database didn't exist your connection code would fail EG $myconn = new mysqli($servername, $username, $password, $dbname);
  17. $user_query only gets a value if this condition is true if(isset($u992092914_trial)) If it is not true you attempt the query anyway on an empty string. Where is $u992092914_trial being set?
  18. I have changed my tables and query, which is now $sql = "SELECT username , week , SUM(points) FROM ( SELECT a.username , a.week , CASE WHEN pick=result THEN value ELSE 0 END as points FROM allpoints a INNER JOIN phpfb_picks p USING (username,gameid) INNER JOIN phpfb_schedule s USING (week,gameid) ) wktots GROUP BY username, week"; The results are the same
  19. Then turn it on! When developing you need error_reporting = E_ALL display_errors = ON
  20. My cover's blown.
  21. try putting the replacement code in a separate function then call it for each row // array to simulate db results $result = [ ['string'=>'replacement 1', 'template'=>'template1'], ['string'=>'replacement 2', 'template'=>'template2'], ]; $str = '<div class="col-xs-3 text-center"> <h4><mofish id="template1" type="text" label="Title" /></h4> <p><mofish id="template2" type="text" label="Description" /></p> </div>'; // for each row in database foreach($result as $row){ // set replacement to be the string from db $replace = $row['string']; $srch = $row['template']; $str = replace_mofish($srch, $replace, $str); } echo '<pre>',htmlentities($str),'</pre>'; // check output function replace_mofish($srch, $replace, $str) { $p2=0; $found = 0; while(($p1 = strpos($str, '<mofish', $p2)) !== false) { $p2 = strpos($str, '/>', $p1); $x = (substr($str,$p1,$p2-$p1+2)); // template contains template1 or template2 if (strpos($x, "id=\"$srch\"")) { $found = 1; break; } } if ($found) { return str_replace($x, $replace, $str); } else return $str; } gives <div class="col-xs-3 text-center"> <h4>replacement 1</h4> <p>replacement 2</p> </div>
  22. the data mysql> SELECT id, name FROM user; +----+--------+ | id | name | +----+--------+ | 1 | user1 | | 2 | user2 | | 3 | user3 | | 4 | user 4 | | 5 | user 5 | +----+--------+ mysql> SELECT id, user_id, friend_id FROM friend; +----+---------+-----------+ | id | user_id | friend_id | +----+---------+-----------+ | 1 | 1 | 2 | | 2 | 1 | 3 | | 3 | 2 | 3 | | 4 | 2 | 4 | | 5 | 4 | 5 | +----+---------+-----------+ Suppose I am logged in as user #2. The main part of the query finds all my possible friends (IE all users that are not me). So leaving out the LEFT JOIN we have SELECT u.id , u.name FROM user u WHERE u.id <> 2 ORDER BY id; +----+--------+ | id | name | +----+--------+ | 1 | user1 | | 3 | user3 | | 4 | user 4 | | 5 | user 5 | +----+--------+ So having got the possible friends we want to compare that list agianst the friends I already have to see which ones are missing. SELECT u.id SELECT user_id , u.name , friend_id FROM FROM user u friend WHERE u.id <> 2 WHERE user_id = 2 ORDER BY id +----+--------+ +---------+-----------+ | id | name | | user_id | friend_id | +----+--------+ +---------+-----------+ | 1 | user1 | | 2 | 3 | | 3 | user3 | | 2 | 4 | | 4 | user 4 | +---------+-----------+ | 5 | user 5 | | +----+--------+ | | | | | | | +-------------------LEFT JOIN---------------------+ The way to do this is to use a LEFT JOIN which will get the data from users and friends. Where there is no matching friend record the fields from friend are null. To do this we use FROM user u LEFT JOIN friend f ON u.id = f.friend_id AND f.user_id = 2 which takes those friend records for user #2 and matches the possible user ids against the existing friend ids The query is now SELECT u.id , u.name , f.friend_id FROM user u LEFT JOIN friend f ON u.id = f.friend_id AND f.user_id = 2 WHERE u.id <> 2 ORDER BY id; +----+--------+-----------+ | id | name | friend_id | +----+--------+-----------+ | 1 | user1 | NULL | | 3 | user3 | 3 | | 4 | user 4 | 4 | | 5 | user 5 | NULL | +----+--------+-----------+ Nearly there! We label the name column with an alias "non_friend" (as that is what they are). We only wanted the friend_id column to show the nulls, so that can go. Lastly, we are only interested in those with NULL values (non-matching) so we add an extra condition to the the WHERE clause AND f.friend_id IS NULL which gives the final version of the query SELECT u.id , u.name as non_friend FROM user u LEFT JOIN friend f ON u.id = f.friend_id AND f.user_id = 2 WHERE u.id <> 2 AND f.friend_id IS NULL ORDER BY id; +----+------------+ | id | non_friend | +----+------------+ | 1 | user1 | | 5 | user 5 | +----+------------+ I hope that helps.
  23. Have you got error reporting turned on in your php.ini file? db_inc.php <?php define("HOST",'localhost'); define("USERNAME",'*******'); define("PASSWORD",'*******'); define("DATABASE", '*******'); $mysqli_driver = new mysqli_driver(); $mysqli_driver->report_mode = MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT;
  24. this should do it <?php include("db_inc.php"); // define HOST, USERNAME etc $db = new mysqli(HOST,USERNAME,PASSWORD,'patsman'); $sql = "SELECT username , week , SUM(points) FROM ( SELECT a.username , a.week , CASE WHEN pick=result THEN value ELSE 0 END as points FROM allpoints a INNER JOIN picks p USING (username,week,gameid) INNER JOIN schedule s USING (week,gameid) ) wktots GROUP BY username, week"; $data = []; $weeks = range(1,17); // create initial array elements for each user $newarray = array_fill_keys($weeks,''); $newarray['total'] = 0; // store results in $data array by user $curruser=''; $res = $db->query($sql); while (list($user,$wk,$pts) = $res->fetch_row()) { if ($user != $curruser) { $data[$user] = $newarray; $curruser = $user; } $data[$user]['total'] += $pts; $data[$user][$wk] = $pts; } // sort data array by total pts desc uasort($data, function($a,$b) { return $b['total'] - $a['total']; }); // table headings $thead = "<tr><th colspan='3'>Points YTD</th><th colspan='17'>Points by week</th></tr>\n"; $thead .= "<tr><th>Rank</th><th>Name</th><th>Total</th><th>" . join('</th><th>', $weeks) . "</th></tr>\n"; // build table data $tdata = ''; $count = $rank = 1; $prevtot = 0; foreach ($data as $user => $udata) { $rank = ($udata['total']==$prevtot) ? $rank : $count; ++$count; $prevtot = $udata['total']; $tdata .= "<tr><td>$rank</td><td>$user</td><td>{$udata['total']}</td><td>" . join('</td><td>', array_slice($udata, 0, 17)) . "</td></tr>\n"; } ?> <html> <head> <title>Confidence Pool</title> </head> <body> <table border='1'> <?=$thead?> <?=$tdata?> </table> </body> </html>
×
×
  • 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.