PHP - Duplicate Db Results
Hi there, I know I'm doing something stupid, but i've tried for hours to try and figure this out and I just cant seem to figure out why tutorials i've seen seem to work yet my own code doesnt.
basically i've got two functions: getAll() and get($id) inside a class, calling getAll, returns an array with one of the same record as opposed to all the records (which is my intended result). Can anyone help? thanks. Code: [Select] class Test{ protected $_db; protected $_table = "table"; protected $_friends = array(); public function __construct($db) { $this->_db = $db; } public function getAll() { $db = $this->_db; $sql = "SELECT * FROM $this->_table"; $db->query($sql); while($data = $db->fetch_array()) { $this->_friends[$data['id']] = $this->get($data['id']); } return $this->_friends; } public function get($id) { $db = $this->_db; $sql = "SELECT * FROM $this->_table WHERE id='$id'"; $db->query($sql); $data = $db->fetch_array(); return (object)$data; } } $test = new Test(new mysqlConnClass()); $arrayOfAllAsObjects = $test->getAll(); Similar TutorialsCode: [Select] $PlayerQuery = "SELECT FirstName, SurName FROM players p, rounds m, entrants e, games t WHERE p.PlayerID = e.PlayerID AND m.GameID = '$ID' AND e.EntrantID = m.Player"; $PlayerResult = mysql_query($PlayerQuery); $PlayerRow = mysql_num_rows($PlayerResult); Can someone suggest why this returns game*the number of results. For each new game it returns an extra duplicate result. For example for 2 games: j Smith j Smith t John t John etc There are no duplicate entry's! and results should be unique. Not in a loop (positive) Just finished a search script. However, when type two keywords it will return duplicate entries: Code: [Select] elseif(isset($_GET['search'])){ $search=$_POST['search']; $search=str_replace(" ", ".", $search); header("Location: ./index.php?q=".$search); } elseif(isset($_GET['q'])){ $search=$_GET['q']; $keywords=explode(".",$search); $sql10000="SELECT product_id FROM $tbl_name2 WHERE keyword LIKE '%" . implode("%' OR keyword LIKE '%",$keywords) . "%'"; $result10000=mysql_query($sql10000); if(mysql_num_rows($result10000)==0){ $content='<div class="center">Search found no results.</div>'; } else{ while($row10000=mysql_fetch_array($result10000)){ $product_id3=$row10000['product_id']; $sql15000="SELECT * FROM $tbl_name WHERE product_id=".$product_id3; $result15000=mysql_query($sql15000); while($row15000=mysql_fetch_array($result15000)){ extract($row15000); $content.=$product_name; } } } } I have 3 products: Test2 - microphone Test3 - audio, microphone Test123 - audio When you search "audio" you get: Test3, Test123 When you search "microphone" you get: Test2, Test3 When you search "audio microphone" you get: Test2, Test3, Test3, Test123 with Test3 being a duplicate. Is there anyway to correct this? I tried SELECT DISTINCT * FROM, but there's no difference in the results returned, from what I have now. Hey all, I've been re-developing a cracker for my site, and when i enter the hash to crack it displays the results 3 times. Example: http://www.just-hack.com/index.php?action=cracker Here's my source: Code: [Select] <?php /** * * @PHP Dictionary Cracker for SMF, v1.0 * */ function template_main() { echo " <table width='100%' border='0' cellspacing='0' cellpadding='4' align='center' class='tborder'> <tr class='catbg'> <td>Cracker</td> </tr> <tr> <td class='windowbg'> <div align='center'>"; function des($word) { return crypt($word, "sl"); } function undes($word, $hash) { $salt = substr($hash, 0, 2); return crypt($word, $salt); } if (!$_POST["encrypt"]) { if (!$_POST["decrypt"]) { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $hash = $_POST['hash']; } else { $hash = $_POST['hash']; if($hash==""){ echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a hash to Crack!</td></table><br />"; } else { if ($type == "DES") { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; //DES } else { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $type = $_POST['type']; } } } } else { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Hash: <input type='text' style='width:50%;'name='hash' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='decrypt' value='Crack' /> </form></td></table><br /> <table width='80%' cellspacing='5' cellpadding='5' align='center'> <form method='post'> <td class='windowbg2' align='center'><br />Word: <input type='text' style='width:50%;'name='word' /> <select name='type'> <option>MD5</option> <option>DES</option> <option>SHA1</option> </select> <input type='submit' name='encrypt' value='Encode' /> </form></td></table><br />"; $type = $_POST['type']; if ($type == "DES") { $word = strip_tags($_POST['word']); if($word == ""){ echo "<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = des($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } elseif ($type == "MD5") { $word = strip_tags($_POST['word']); if($word == ""){ echo "<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = md5($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } elseif ($type == "SHA1") { $word = strip_tags($_POST['word']); if($word == ""){ echo"<table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Type a word to encode!</td></table><br />"; } else { $enc = sha1($word); echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Encoded: <br /> $word = $enc</td></table><br />"; } } else { echo ("Error?!"); } } $hash = $_POST['hash']; $words = file("wordlist.txt"); foreach ($words as $word) { $word = rtrim($word); if (undes($word, $hash) == $hash) { echo " <table width='80%' cellspacing='5' cellpadding='5' align='center'> <td class='windowbg2' align='center'>Plaintext found! <br /> $hash = $word</td></table><br />"; } } $file = "wordlist.txt"; $lines = count(file($file)); echo "There are $lines words in our wordlist!"; echo "</td></div></tr></table>"; } ?> I'm working on a directory component and have kind of a tricky thing I need to do. The list of results pop through ajax on the left side along with it's google map number tag, and the google map pops on the right side. To make it even trickier the results are popped through a radius search by proximity. The problem is if there are multiple results with the same address you end up having all of the number tags on the map buried under the last tag with that address, plus it makes for kind of a long list. What I need to do is run a check to see if the previous result is the same address, and if yes not pop that result in a new table cell, rather stick it in a jquery drop down div so that all of the following results with the same address are stuffed in the jquery drop down in the same table cell under the first result with that address. In a perfect world all of the listings with the same addresses would be submitted in order so I could just do a check for the previous itemid's address, but of course that's not the case. I thought about running a query to grab ALL of the addresses and then check the item's address against it to see if it matches and if yes echo the jquery div instead of the <td>, but obviously that won't work because that will cause the first item with that address to be put in the div also. Plus I don't know if that's a very efficient way to go about it anyway. Here's kind of the basic thing I'm working with: Code: [Select] $query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid = 76 AND itemid = $mySobi->id"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $myaddress = $row['data_txt']; } echo "<td $style>"; Any ideas? Alright, I need to find a way to display the top ten duplicated rows for a table in my database. I have tried multiple methods but I have failed. Can you please assist me with this problem. I currently run a query in phpmyadmin to get the result, but i cant figure out how to properly code the php script. I am inserting the two records below simultaneously (one after the other), but what I want to do write the second ONLY if the first isn't a duplicate. Help? Code: [Select] //FIRST INSERT mysql_query("INSERT INTO spam (id, scm_mem_id) VALUES('', '$social_mem_id' ) ON DUPLICATE KEY UPDATE scm_mem_id=$social_mem_id") or die(mysql_error()); //SECOND INSERT mysql_query("INSERT INTO sc_messages (smg_from, smg_to, smg_subject, smg_body, smg_sent_del, smg_postdate) VALUES ('$social_mem_id','1','$subject','$body','1','$time')") or die(mysql_error()); Hey folks, Sorry for being a pain in the ass. I am trying to submit data to my database via a form and when I click Submit, I get: Duplicate entry '' for key 1 I understand that it means I have a duplicate entry with the ID of 1 or something like that. I can't find where the issue is. Here is the form: <form actin="" id="settings" name="settings"> <table class="listing form" cellpadding="0" cellspacing="0"> <tr> <th class="full" colspan="2"><?php echo $lang_settings; ?></th> </tr> <tr> <th colspan="2"><?php echo $lang_settings_description; ?></th> </tr> <tr> <td><?php echo $lang_sitename; ?>: </td> <td><input type="text" name="sitename" value="<?php echo $site_name; ?>" width="172" /> <em>Site name for logo</em></td> </tr> <tr> <td><?php echo $lang_email; ?>: </td> <td><input type="text" name="email" value="<?php echo $site_email; ?>" width="172" /> <em>Your email address</em></td> </tr> <tr> <td><?php echo $lang_yourname; ?>: </td> <td><input type="text" name="name" value="<?php echo $your_name; ?>" width="172" /> <em>Your own name</em></td> </tr> <tr> <td><?php echo $lang_meta_description; ?>: </td> <td><input type="text" name="meta-description" value="<?php echo $description; ?>" width="172" /> <em>SEO</em></td> </tr> <tr> <td><?php echo $lang_keywords; ?>: </td> <td><input type="text" name="meta-keywords" value="<?php echo $keywords; ?>" width="172" /> <em>Separate with Commas</em></td> </tr> <tr> <td><input type="submit" class="button" name="submit" value="<?php echo $lang_button_savesettings; ?>"></td> </tr> </table> </form> Here is the Insert code: $insert = "INSERT INTO settings (site_name, description, keywords, email, name) VALUES ('$sitename', '$meta_description', '$meta_keywords', '$site_email', '$your_name')"; mysql_query($insert) or die(mysql_error()); Can anyone please tell me where I am going wrong here? Much appreciated. Hi.. So im currently working on a script.. My script generates a "oid" based on timestamp. Ive made the "oid" field unique in my db, so if i do a quick refresh i get the message: Duplicate entry '1283195988' for key 'oid' Is there some way i can check if its a dublicate, and if it is + it with 1 or something? Hey guys just wondering if this piece of code is correct because i get a mysql error saying Duplicate entry '*********' for key 2 this is the code i have and table structure. $sql = " INSERT INTO `IP_Address` VALUES(NULL,'".$ip."','".$date."','".$time."') ON DUPLICATE KEY UPDATE `date` = `".$date."`, `time` = `".$time."` "; Hey guys! I know, I know this problem is EVERYWHERE but i just dont understand! I have a solid knowlage of php but my SQL skills are low, so i dont know too much about Keys and stuff. But my error is: Duplicate entry '' for key 2. The thing that im working on at this section is logging in with facebook. The code that presents my error is: $sql = "SELECT * FROM users WHERE uid=".$uid; $fbid = mysql_query($sql); $num_rows = mysql_num_rows($fbid); if(mysql_num_rows($fbid) < 1) { echo "You are not logged in. "; mysql_query("INSERT INTO `users` (`uid`) VALUES ('".$uid."')") or die(mysql_error()); } else { mysql_query("UPDATE users SET logged = '1' WHERE uid=".$uid); //mysql_query("UPDATE users SET full_name = $me WHERE uid=".$uid); echo "Your Logged in "; echo $me['name']; ?> Continue to <a href="removed :)"> My Settings </a>. <? } Any help is welcome Hi, I have a function that returns the value of a array if it matches $string, but it only returns Test 1 instead of returning Test 1, Test 2. Can you someone see what I'm doing wrong? And it has to return N if nothing found. Code: Code: [Select] function fes($string){ $fes['Test 1'] = '104'; $fes['Test 2'] = '104'; return in_array($string, $fes) ? array_search($string, $fes) : 'N'; } echo fes('104'); thanks, Cyto Code: [Select] foreach ($items as $product ) { echo $product; ?><input type="text" size="2" value="<?php \\display quantity here ?>" name="quantity" /><?php } $items is an array. It has multiple values, some duplicate. How do i count the duplicate values in the array and display in this foreach loop? i know array_count_values($product) but putting that in the foreach loop won't accomplish what i want. another thing. i can get the foreach loop to not display duplicates by doing this Code: [Select] foreach (array_unique($items) as $product ) { echo $product; ?><input type="text" size="2" value="<?php \\display quantity here ?>" name="quantity" /><?php } how would i accomplish both. basically i want it to display the quantity without displaying duplicate rows. aka shopping cart. Hi, I have a multidimentional array which looks like this : Code: [Select] array(2) { ["HOKIT100E-041"]=> array(3) { [0]=> string(26) "Honda Cr 125-250 2000-2001" [1]=> string(5) "89.99" [2]=> string(1) "1" } ["WAFAXS"]=> array(3) { [0]=> string(27) "Wulf Flite-x Helmet - Green" [1]=> string(5) "65.94" [2]=> string(1) "1" } } howver when I do a foreach on it, the 1st array is being duplicated and I have no idea why this is the code I have : Code: [Select] foreach($basketArray as $key => $value) { echo$nvpstr = $nvpstr ."<br/><br/>&L_PAYMENTREQUEST_0_NUMBER$q=".$key." <br/>&L_PAYMENTREQUEST_0_NAME$q=".$value[0]." <br/>&L_PAYMENTREQUEST_0_AMT$q=".$value[1]." <br/>&L_PAYMENTREQUEST_0_QTY$q=".$value[2]; $q++; } this is what is output : Quote &L_PAYMENTREQUEST_0_NUMBER0=HOKIT100E-041 &L_PAYMENTREQUEST_0_NAME0=Honda Cr 125-250 2000-2001 &L_PAYMENTREQUEST_0_AMT0=89.99 &L_PAYMENTREQUEST_0_QTY0=1 &L_PAYMENTREQUEST_0_NUMBER0=HOKIT100E-041 &L_PAYMENTREQUEST_0_NAME0=Honda Cr 125-250 2000-2001 &L_PAYMENTREQUEST_0_AMT0=89.99 &L_PAYMENTREQUEST_0_QTY0=1 &L_PAYMENTREQUEST_0_NUMBER1=WAFAXS &L_PAYMENTREQUEST_0_NAME1=Wulf Flite-x Helmet - Green &L_PAYMENTREQUEST_0_AMT1=65.94 &L_PAYMENTREQUEST_0_QTY1=1 Have I made a schoolboy error? Thanks. hi, i have some code that i need to update existing columns in a table, but i just cant seem to get it to work if anyone caan please help it would be appreciated. Quote // select the database mysql_select_db($database) or die ("Could not select database because ".mysql_error()); $insert = mysql_query("insert into $table values ('NULL', '".$_POST['email']."', '".$_POST['password']."', '".$_POST['name']."', '".$_POST['Gender']."', '".$_POST['Age']."', '".$_POST['Race']."', '".$_POST['SpecialtyOne']."', '".$_POST['Feet']."', '".$_POST['Weight']."', '".$_POST['Eyes']."', '".$_POST['Hair']."', '".$_POST['Strength']."', '".$_POST['Stamina']."', '".$_POST['Perception']."', '".$_POST['Agility']."', '".$_POST['Intelligence']."', '".$_POST['Tech']."', '".$_POST['Luck']."', '".$_POST['Appearance']."', '".$_POST['Background']."', '".$_POST['Weapons']."', '".$_POST['Armour']."', '".$_POST['Items']."', '".$_POST['Enhancements']."', '".$_POST['Skills']."')") or die("Could not insert data because ".mysql_error()); ?> <?php I have a contact form, and I want to make sure it doesn't send a bunch of duplicates if the page is refreshed after being submitted. Simple way is to make sure this record isn't identical to the one before it: select * from `contacts` where `Name`='$name' and `Phone`='$phone' and `Message`='$message' and `Subject`='$subject' and `Email`='$email' But, that checks against all records. While not likely, this could cause problems, if the same customer came back a month later and put in the same exact contact. Any way I can check it only against the very last record in the database? Something like: and `id`=XX , where XX is one less than the current auto inc id? I have created an input field on a website for people to subscribe by their email address. The email address is stored in a database. I am using PHPMyAdmin. The email address is successfully working, but I want to prevent duplicate email address to be stored, however, I am having an error. Here are my codes: HTML codes: Code: [Select] <form action="index.php" method="post"> <input type="text" size="25" placeholder="Your email address..." name="enter"/> <input class="submit" type="submit" value="Subscribe" name="subscribe"/> <br/> PHP with Query codes: Code: [Select] <?php if ( $_SERVER['REQUEST_METHOD'] == "POST" ) { $ee = htmlentities($_POST['enter']); if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$ee) || empty($ee)){ echo '<p class="fail">Failed...Try again!</p>'; } else { @mysql_connect ('localhost', 'root', '') or die ('A problem has occurred, refresh the page and try again!'); @mysql_select_db ('links') or die ('A problem has occurred, refresh the page and try again!'); $duplicate = "SELECT * FROM `email` WHERE `emailaadress` = '{$ee}'"; $query = "INSERT INTO email (id, emailaddress) VALUES('NULL', '.$ee')"; $result = mysql_query($duplicate); if ( mysql_num_rows ( $result ) > 1) { /* Username already exists */ echo 'Username already exists'; } else { mysql_query($query); echo '<p class="success">Successfully subscribed!</p>'; } } } ?> Error I am having: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\softwareportfolio\index.php on line 68 Can someone help me? Thank Hi, I'm having a wierd problem related to session variables. It looks like variables would get duplicated inside same session, which of course should not be possible. Background: This problem exists on one page script which creating a quote request system where users can select different products and get quote for those. Quote system creates quote ID per customer and all products selected in one session should go under the same quote ID. Problem is that sometimes when user selects products second quote ID is created and after that products are randomly added into both of quotes. While trying to solve this problem I added simple logs to see what's going on, those are added below. Problem seems to be caused by duplicated session variables. At somepoint it looks like session variables are not defined any more and new quote ID is created. After that the old and new session variables seems to be used randomly. To demonstrate the problem I added session variable called 'counter' which is defined if it does not exist and incremented always when page is reloaded by submitting the form. As you can see from below logs the 'counter' variable seems to have duplicate values, see the quote value to separate two different session variable "sets". <?php session_start(); echo "\n Current session id: ".session_id(); echo "\n _SESSION['quote']: ".$_SESSION['quote']; $_SESSION['counter'] = isset($_SESSION['counter'])? $_SESSION['counter'] +1 : 0; echo "\n _SESSION['counter']: ".$_SESSION['counter']; Output when page is reloaded(form submitted): Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: $_SESSION['counter']: 0 set _SESSION['quote']: 984 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: $_SESSION['counter']: 0 set _SESSION['quote']: 985 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 1 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 2 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 984 $_SESSION['counter']: 1 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 3 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 984 $_SESSION['counter']: 2 Could anyone explain how the 'counter' can behave such way inside same session (based on session ID)? This is far beyond my knowledge and I would highly appreciate any advice or tip how to solve this porblem. Thanks. BestRegards, Laowai I have a sorting functionality, the code is he <?php $select_category = $_REQUEST['sort_category']; $sort_date_var = $_REQUEST['sort_date']; $sort_submit = $_POST['sortSubmit']; // Connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if (($select_category == 'All') || (!isset($select_category)) && (!isset($sort_date_var))) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con"; $data = mysqli_query($dbc, $query); //Loop through the array of data while ($row = mysqli_fetch_array($data)) { echo "<table class='knuffixTable'>"; // Display the score data echo "<tr><td class='knuffix_name'>"; echo "<strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "<tr><td class='knuffix_categoryDate'>" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . " </td></tr>"; echo "</table>"; } mysqli_close($dbc); } elseif (isset($select_category) && !isset($sort_date_var)) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con WHERE category = '$select_category'"; $data = mysqli_query($dbc, $query) or die (mysqli_error($dbc)); //Loop through the array of data while ($row = mysqli_fetch_array($data)) { echo "<table class='knuffixTable'>"; // Display the score data echo "<tr><td class='knuffix_name'>"; echo "<strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "<tr><td class='knuffix_categoryDate'>" . htmlentities($row['category']) . " | " . date('M d, Y', strtotime($row['contributed_date'])) . " </td></tr>"; echo "</table>"; } mysqli_close($dbc); } elseif (!isset($select_category) && isset($sort_date_var)) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con ORDER BY contributed_date $sort_date_var"; $data = mysqli_query($dbc, $query) or die (mysqli_error($dbc)); //Loop through the array of data while ($row = mysqli_fetch_array($data)) { echo "<table class='knuffixTable'>"; // Display the score data echo "<tr><td class='knuffix_name'>"; echo "<strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "<tr><td class='knuffix_categoryDate'>" . htmlentities($row['category']) . " | " . date('M d, Y', strtotime($row['contributed_date'])) . " </td></tr>"; echo "</table>"; } mysqli_close($dbc); } elseif (isset($select_category) && isset($sort_date_var)) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con WHERE category = '$select_category' ORDER BY contributed_date $sort_date_var"; $data = mysqli_query($dbc, $query) or die (mysqli_error($dbc)); //Loop through the array of data while ($row = mysqli_fetch_array($data)) { echo "<table class='knuffixTable'>"; // Display the score data echo "<tr><td class='knuffix_name'>"; echo "<strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "<tr><td class='knuffix_categoryDate'>" . htmlentities($row['category']) . " | " . date('M d, Y', strtotime($row['contributed_date'])) . " </td></tr>"; echo "</table>"; } mysqli_close($dbc); } ?> With this code I'm able to: - showcase every category by DEFAULT when someone comes to the page. - sort only by category, - sort only by date, - sort by category AND date, The problem is as you can see I have a lot of duplicate code, if I for example want to change the table that is being printed out, I have to change it on all of them. I'd like to ask how I could avoid this duplicate code. Can I for example just have the table ONE TIME at a separate place and then insert the REFERENCE _after_ the query in each if statement? Like this: if (($select_category == 'All') || (!isset($select_category)) && (!isset($sort_date_var))) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con"; $data = mysqli_query($dbc, $query); table_here(); } elseif (isset($select_category) && !isset($sort_date_var)) { // Retrieve the chosen category from MySQL $query = "SELECT * FROM con WHERE category = '$select_category'"; $data = mysqli_query($dbc, $query) or die (mysqli_error($dbc)); table_here(); } I'm just coding since 2 month so I don't know how do it, maybe I can do it with functions? I've tried doing it with functions, but I got an error since the function doesn't contain any query statement and only the table because it was trying to fetch. it looked like this: function table_here () { //Loop through the array of data while ($row = mysqli_fetch_array($data)) { echo "<table class='knuffixTable'>"; // Display the score data echo "<tr><td class='knuffix_name'>"; echo "<strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "<tr><td class='knuffix_categoryDate'>" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . " </td></tr>"; echo "</table>"; } mysqli_close($dbc); } Hi. I'm new to PHP and Wordpress, quite the beginner. I thought I finally had it all done on my site and I've stumbled on another issue. Basically I post a link and it spits it out. I sometimes post links that have the same domain ($content['host']) but I don't want these to be duplicated. Here's what I have: Code: [Select] <?php query_posts(''); ?> <?php while (have_posts()) : the_post(); ?> <li> <a href="http://<?php $content = parse_url(strip_tags(get_the_content())); echo $content['host']; ?>"> <?php $content = parse_url(strip_tags(get_the_content())); echo $content['host']; ?></a> </li> <?php endwhile;?> I've Googled around for a while, reading posts about how to prevent duplicate posts in multiple loops but can't adapt it to mine. I'd really appreciate any advice. Cheers, Craig. For some reason, this doesn't work:
<?php $string = 'You have a code CODE code of ethics'; while (preg_match("/code\s+code/",$string)) { $string = preg_replace("/code\s+code/","code",$string); } print $string; ?> I don't want to replace all instances of duplicated words, rather, only when the word "code" is duplicated. Throughout my 100mb text file, the word "code" appears duplicated (with varying whitespace between). For example: From this: You have a code CODE code code of ethics. Code code Code green means everything is okay. What is the CODE code code code for the lock. To this: You have a code of ethics. Code green means everything is okay. What is the code for the lock. But for some reason, I cannot get my preg_replace to work? |