-
Posts
24,566 -
Joined
-
Last visited
-
Days Won
822
Everything posted by Barand
-
... or you could put the connection credentials in a separate file which you include() in your scripts so they only need change one place. This applies to procedural and OOP.
-
This method allocates 15% of the planets to level 1, 15% of the remaining planets to level 2, and so on. The results for 10,000 planets were Level 25 : 30 Level 24 : 36 Level 23 : 42 Level 22 : 49 Level 21 : 58 Level 20 : 68 Level 19 : 81 Level 18 : 95 Level 17 : 111 Level 16 : 131 Level 15 : 154 Level 14 : 181 Level 13 : 213 Level 12 : 251 Level 11 : 295 Level 10 : 347 Level 9 : 409 Level 8 : 481 Level 7 : 565 Level 6 : 665 Level 5 : 783 Level 4 : 921 Level 3 : 1083 Level 2 : 1275 Level 1 : 1676 TOTAL :10000 Time taken : 17.430 seconds The code <?php include("db_inc.php"); // defines HOST, USERNAME and PASSWORD try { $db = new mysqli(HOST,USERNAME,PASSWORD,'test'); } catch(Exception $e) { die("DB connection error"); } $t1 = microtime(1); // start the clock /******************************************************************** * CREATE THE TEST DATA planet TABLE (uncomment if required) ********************************************************************* $db->query("DROP TABLE IF EXISTS planet"); $sql = "CREATE TABLE planet ( planet_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, planetname VARCHAR(30), level INT )"; $db->query($sql); $sql = "INSERT INTO planet (planetname) VALUES (?)"; $stmt = $db->prepare($sql); $stmt->bind_param('s', $pn); for ($i=1; $i<=10000; $i++) { $pn = "Planet $i"; $stmt->execute(); } $stmt->close(); *********************************************************************/ /******************************************************************** * define the %age distribution of the levels *********************************************************************/ $distrib_pcent = 15; /******************************************************************** * how many planets (N)? *********************************************************************/ $sql = "SELECT COUNT(*) FROM planet"; $res = $db->query($sql); list($N) = $res->fetch_row(); $planet_levels = []; // define empty array $planets = range(1,$N); shuffle($planets); // planet ids in random order /******************************************************************** * fill planet_level array with levels to be applied to each planet *********************************************************************/ $key = 0; $n = $N; for ($level = 1; $level <= 25; $level++) { $k = floor($n * $distrib_pcent / 100); // how many planets get this level? $n -= $k; // $n = remaining planets if ($n < 0) { die( $level . ' level reached<br>'); // check we don't run out of planets } for ($i=0; $i<$k; $i++) { $planet = $planets[$key++]; // next random planet id $planet_levels[$planet] = $level; // set its level } } /****************************************************************************** * update the planets with their assigned levels *******************************************************************************/ $db->query("UPDATE planet SET level=1"); // set default level $sql = "INSERT INTO planet (planet_id, level) VALUES (?,?) ON DUPLICATE KEY UPDATE level = VALUES(level)"; $stmt = $db->prepare($sql); $stmt->bind_param('ii',$pid,$level); foreach ($planet_levels as $pid=>$level) { if ($level != 1) $stmt->execute(); // EDIT: only need update those != 1 } $t2 = microtime(1); // stop the clock; /****************************************************************************** * check the results *******************************************************************************/ $sql = "SELECT level, COUNT(*) as tot FROM planet GROUP BY level ORDER BY tot"; $res = $db->query($sql); $tdata = ''; $totalPlanets = 0; while (list($lev, $tot) = $res->fetch_row()) { $tdata .= sprintf("Level %2d : %4d\n", $lev, $tot); $totalPlanets += $tot; } ?> <html> <head> <title>Planet levels</title> </head> <body> <pre> <?php echo $tdata; printf("<b></b>%8s :%5d</b> Time taken : %6.3f seconds\n", 'TOTAL', $totalPlanets, $t2-$t1); ?> </pre> </body> </html>
-
Merging orders in an array, then removing the excess orders
Barand replied to blmg2009's topic in PHP Coding Help
Then use whatever you get that is unique to a customer (name/postcode ?). How were you planning to get round the problem with your array merge? -
Upload resize and convert images turn black help
Barand replied to cobusbo's topic in PHP Coding Help
getimagesize returns array like Array ( [0] => 800 [1] => 1280 [2] => 2 [3] => width="800" height="1280" [bits] => 8 [channels] => 3 [mime] => image/jpeg ) use the mime type instead of relying on the file extesion -
Merging orders in an array, then removing the excess orders
Barand replied to blmg2009's topic in PHP Coding Help
Extract the customer_id as well as the names and group by the id -
Upload resize and convert images turn black help
Barand replied to cobusbo's topic in PHP Coding Help
Try processing it as if it were a jpeg file. That worked for me after downloading -
Merging orders in an array, then removing the excess orders
Barand replied to blmg2009's topic in PHP Coding Help
I'd do it when I extract the data from the database instead of reading the data into an array then trying to manipulate that. SELECT order_id , customer_name , product_name , MAX(length) as length , MAX(width) as width , SUM(height) as height , SUM(weight) as weight FROM whichever tables GROUP BY customer_name Job done -
Upload resize and convert images turn black help
Barand replied to cobusbo's topic in PHP Coding Help
$img (the second parameter in imagecopyresampled) is false because of the first error message - not a valid png file. -
Identifying and connecting ID's between tables
Barand replied to VanityCrush's topic in PHP Coding Help
You don't need a second query. Your first query is to list the blog and existing comments. Save the comment_id from this query and that goes in the hidden field in the comment form at the bottom <form method='post' action='' class='comments_form'> <input type='text' name='username' placeholder='your name... *' id='name'> <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea> <input type='hidden' name=blog_id' value='$saved_comment_id'> <input type='submit' name='submit' id='post' value='post'> </form> -
Merging orders in an array, then removing the excess orders
Barand replied to blmg2009's topic in PHP Coding Help
OK, the weight would be the total but the length, width and height will not all be sum of the items. You would pack them end-to-end, side-by-side or stack them, so only one of the dimensions would be the sum. The others would be the maximum values. -
Merging orders in an array, then removing the excess orders
Barand replied to blmg2009's topic in PHP Coding Help
It is difficult to see why one might want to this, particularly as you have now lost the data that Joe Bloggs also ordered a mouse. -
In that case, have separate totals array and accumulate the totals for each user in that, Added lines 25, 47, 64 /***************************************************** * first you need to get the column headings * and create array to store responses for * each question ******************************************************/ $sql = "SELECT DISTINCT name FROM kelvin ORDER BY name"; $names = array(); $res = $db->query($sql); while ($row = $res->fetch_assoc()) { $names[] = $row['name']; } $tableHeads = "<tr><th>Category</th><th>Question</th><th>Points</th><th>" . join('</th><th>', $names) . "</th></tr>\n"; $newArray = array_fill_keys($names,''); // create blank array $totals = array_fill_keys($names, 0); // create array to store totals $newArray=array_merge(array('points'=>''), $newArray); // add points to the start of array for each question /***************************************************** * then you process the table data * storing the answers for each name in the array. * indexed by categor, question, name ******************************************************/ $sql = "SELECT category, question, points, name, answer FROM kelvin ORDER BY category, question"; $qarray = $newArray; // new array to store answers to question $currq = ''; // store the current question $currc = ''; // store the current category $data = array(); $res = $db->query($sql); while (list($c,$q,$p,$n,$a) = $res->fetch_row()) { if (!isset($data[$c][$q])) { $data[$c][$q] = $newArray; } $data[$c][$q][$n] = $a; // store the answer by name $data[$c][$q]['points'] = $p; // store the points for the question $totals[$n] += $a; // accumulate total } $tableData = ''; /************************************************** * loop through the data array and output the table ***************************************************/ foreach ($data as $cat => $qdata) { $kq = count($qdata); // how many question rows? $tableData .= "<tr><td rowspan='$kq'>$cat</td> "; $k=0; foreach ($qdata as $q => $ans) { if ($k > 0) $tableData .= '<tr>'; $tableData .= "<td>$q</td><td>".join('</td><td>',$ans)."</td></tr>"; ++$k; } } $tableData .= "<tr><th colspan='3'>Totals</th><td>" . join('</td><td>',$totals) . "</td></tr>\n"; ?> <table border='1' style='border-collapse: collapse;'> <?=$tableHeads?> <?=$tableData?> </table>
-
foreach ($qdata as $q => $ans) { if ($k > 0) $tableData .= '<tr>'; $tot = array_sum(array_slice($ans,1)); // sum array excluding points value $tableData .= "<td>$q</td><td>".join('</td><td>',$ans)."</td><td>$tot</td></tr>"; ++$k; }
-
OK So now I have to change the database I set up to allow for numeric answers. Why don't you just ask the real problem from the start instead of going round the houses with the dummy questions and answers?
-
array_sum $a = [1,2,3]; echo array_sum($a); //==> 6
-
ON blog.content_id = article_comments.blog_id that is the correct join. That's why you added the foreign key. As for the duplication - that is how joins work. You get the data from A with matching data from B. The trick is to output the article data only when it changes. Without knowing exactly how you want to display the data I cannot offer much help other than this pseudocode. prev_blog_id = 0 while (get next result row) if (blog_id != prev_blog_id) output article data prev_blog_id = blog_id endif output comment data endwhile
-
see this thread - similar problem with solution http://forums.phpfreaks.com/topic/297720-php-matrix-table/?do=findComment&comment=1518791
-
$x = simplexml_load_file('members.xml'); echo $x->member[0]->firstName, $x->member[0]->lastName;
-
1. Don't connect to the database in side the function. You don't want to be connecting every time the function is called (connecting is slow). Connect once when you open your script and pass the connection as a parameter to your function. 2. INSERT queries do not have WHERE clauses, you would write the id in the insert with the other data. Are you sure you don't mean to update an existing record?
-
Creating an array from a selected column based based on order
Barand replied to bambinou1980's topic in PHP Coding Help
json_encode