PHP - Compare Rows
Hi everyone!
I've been looking for a solution, but i just can't find it anywhere... Ok, so the problem is: i have a database which looks something like this: user_id product_id score 14 . 235 . 79 23 . 235 . 32 53 . 665 . 21 14 . 235 . 90 5 . 675 . 45 This is step-by-step of what i need to do: 1. Select user - user_id =343 2. For user_id =343 select all products that he gave score to: product_id = 43 - score = 99 product_id = 12 - score = 56 product_id = 68 - score = 32 product_id = 124 - score = 67 3. Find all users that voted for the same products e.g.: for product_id = 43: user_id = 125 voted 93 points, user_id = 23 voted 56 points. 4. Calculate the difference between the score of user, so: for product_id = 43: user_id = 125 voted 93 points (99 - 93 =6 points of diff.) user_id = 23 voted 56 points (99 - 56 =43 points of diff.) return the results.... That's basically what i need to do. I still don't know the number of the users, or product, but it doesn't really matter - i just need to make it work. Ok, hope someone can help! Similar TutorialsHi Everyone, I am working on developing a blog/comment system for my website. I have 3 tables, the first a blog post table with a row/primary key of id that is auto incremented as each new article is created via a form. The second table is a comments table with a row of article_id and the third table is a category table with an article_id row as well. From the main blog page I have links that will take users to each individual blog post using $_GET like so: Code: [Select] http://www.mydomain.com/blog/article/?id={$row['id']} From here I would like to be able to display the comment for that particular article below the article and also have a sidebar with links to blog categories which will then display each post according to whether they are in that category or not. My question is two-fold: First, what is the best way to pull the id field from the blog/post table, form, or url and enter it into the article_id rows of the second two tables? Should I use a hidden field, the URL id via $_GET, using a join, or what? Secondly: What is the best way to compare and display those rows so that the appropriate comments are being shown for the correct article, etc. This is my first time doing this so I am grateful for any help or suggestions. Thanks, kaiman I have a cart script, and I need to display the products the user has added. This is a school assignment and I'm very stuck on this seemingly 'little' error. Right now, I have two tables: For time's sake, I am showing duplicate products with different prod_id's: Table: products prod_id category sub_category thumb_href image_href title desc summary manufacturer price 17 sofa leather red_leather_sofa_small.jpg red_leather_sofa_main.jpg Red Leather Sofa [BLOB - 134B] [BLOB - 59B] Balenty 999.99 18 sofa leather red_leather_sofa_small.jpg red_leather_sofa_main.jpg Red Leather Sofa [BLOB - 134B] [BLOB - 59B] Balenty 999.99 19 sofa leather red_leather_sofa_small.jpg red_leather_sofa_main.jpg Red Leather Sofa [BLOB - 134B] [BLOB - 59B] Balenty 999.99 And this is the cart table that holds temporary cart items (storing the product ID to pull later): Table: cart temp_cart_item cart_id (assigned by session_id() ) prod_id user_id 22 jier11u0e7cl2ghosjodpaark2 17 asdfasdf 23 jier11u0e7cl2ghosjodpaark2 17 asdfasdf 24 jier11u0e7cl2ghosjodpaark2 35 asdfasdf 25 jier11u0e7cl2ghosjodpaark2 5 asdfasdf 26 jier11u0e7cl2ghosjodpaark2 19 asdfasdf SO, user 'asdfasdf' is logged in and has selected 5 items for his cart - two of which are the same (prod_id 17). Basically, I need to compare the prod_id's of each table and output all products (and quantities) matching the temporary cart prod_id. What I have now to loop through and display the cart items are (bear with me): echo "<h1>Cart</h1>"; } // Display welcome and navigation links displayWelcome(); displayNav(); // Getting the prod_id's from the table cart to compare with the product table $cart_id = session_id(); $user_id = ($_SESSION['login_username']); $query = "SELECT prod_id FROM cart WHERE cart_id='$cart_id' AND user_id='$user_id'"; $result = mysqli_query($cxn,$query) or die("<h2 class=\"warning\">Whoa! Problem with the cart script here!</h2>"); $nrows = mysqli_num_rows($result); if($nrows < 1) { echo "<h2>Your cart is empty</h2><p><a href=\"catalog.php\">Go back to the catalog</a></p>"; } else { // Continue to gather products for all the product IDs in the products DB table... echo "<h4>$nrows items in your cart</h4>"; while($row = mysqli_fetch_array( $result )) { $user_id = ($_SESSION['login_username']); $product = $row['prod_id']; // Is the query my problem? $query = "SELECT * FROM products WHERE prod_id='$product'"; $result = mysqli_query($cxn,$query) or die("<h2 class=\"warning\">Whoa! Problem with the cart script here!</h2>"); $nrows = mysqli_num_rows($result); if($nrows < 1) { // If the item doesn't exist, display an error echo "<h2>That is not a valid product, or any of the items you had in your cart are missing or have been deleted.</h2><p><a href=\"catalog.php\">Go back to the catalog</a></p>"; // Protect from continually displaying an error by deleting the invalid cart record $deletequery = "DELETE FROM cart WHERE prod_id='$product'"; $deleteresult = mysqli_query($cxn,$deletequery) or die("<h2 class=\"warning\">Whoa! Problem with the cart script here!</h2>"); exit(); } while($row = mysqli_fetch_array( $result )) { // Then disply them in a table echo "<h2>Items in Your Cart:</h2>"; echo " <table id=\"products\"> <thead> <tr> <th class=\"col1 headercol\" scope=\"col\">Thumbnail</th> <th class=\"col2 headercol\" scope=\"col\">Summary</th> <th class=\"col3 headercol\" scope=\"col\">Manufacturer</th> <th class=\"col4 headercol\" scope=\"col\">Price</th> </tr> </thead> <tbody>\n"; $query = "SELECT SUM(price) FROM products WHERE prod_id='$product' GROUP BY price"; $priceResult = mysqli_query($cxn,$query) or die("<h2 class=\"warning\">Whoa! Problem with the cart script here!</h2>"); // keeps getting the next row until there are no more to get // Print out the contents of each row into a table echo "<tr> <td class=\"col1\">"; echo "<a class=\"imgHref\" href=\"detail.php?prod_id=".$row['prod_id']."\" title=\"".$row['title']."\"><img src=\"../images/".$row['thumb_href']."\" alt=\"".$row['title']."\" /></a>"; echo "</td>\n"; echo " <td class=\"col2\">"; echo "<h3 class=\"title\"><a href=\"detail.php?prod_id=".$row['prod_id']."\" title=\"".$row['title']."\">".$row['title']."</a> <span class=\"inlineh3\">by <a href=\"categories.php?manufacturer=".$row['manufacturer']."\" title=\"View all products by ".$row['manufacturer']."\">".$row['manufacturer']."</a></span></h3>"; echo "<p class=\"summary\">".$row['summary']."</p> <p class=\"descHeading\">&#9758; <em>Full Description:</em></p> <p class=\"desc\">".$row['desc']."</p>"; echo "</td>\n"; echo " <td class=\"col3\">"; echo "<p class=\"manufacturer\"><a href=\"categories.php?manufacturer=".$row['manufacturer']."\" title=\"View all products by ".$row['manufacturer']."\">".$row['manufacturer']."</a></p>"; echo "</td>\n"; echo " <td class=\"col4\">"; echo "<p class=\"price\">$".$row['price']."</p>"; echo "</td> </tr>\n"; } while($priceRow = mysqli_fetch_array( $priceResult )) { echo "<tr class=\"short\"><td class=\"col1\"><h3><a href=\"clear_cart.php\">Empty Cart</a></h3></td><td class=\"col2\"></td><td class=\"col3 nobackground\">Total:</td><td class=\"col4\">$".$priceRow[0]."</td></tr>"; } echo "</tbody> </table>"; echo "<p class=\"submitOrder\"><form action='submit_order.php' method='post' id='form'> <input type='submit' name='pButton' value='Submit Order'> <input name='order_total' type='hidden' id='order_total' value='".$priceRow[0]."' /> </form> </p>"; } } And so the cart.php looks something like this (this example asdfasdf has 6 items in his cart): So you can see that it only displays ONE item, even though asdfasdf DOES have 6 items in his cart (proven by checking database). And the price is not accurate, either. Can anyone help me in where my problem might be? Is it my query? Or my while clause? what Im basically trying to do is just like a phpmyadmin function... you select rows you want to update with a checkbox and then it takes you to a page where the rows that are clicked are shown in forms so that you can view and edit info in them... and then have 1 submit button to update them all at once. I have 2 queries that I want to join together to make one row
Can php be used to get two blog entries and compare them side by side, with a choice one which one to use. A bit like wikipedia has ? Hi, I want to compare the tables from 2 mysql databases in a table. This is what I have: for($i=0;$i<$maxCount;$i++) { echo "<tr>"; // start row //fist data square if ($i < count($db1)) echo "<td>{$db1[$i]}</td>"; else echo "<td></td>"; echo "<td></td>"; // middle //last if ($i < count($db2)) echo "<td>{$db2[$i]}</td>"; else echo "<td></td>"; echo "</tr>"; // end row } that will put make a nice table for me to see. What I'd like to do next is have all identical sql tables lined up. So for e.g I have 2 arrays of table names that will look like this: Databse 1 Database 2 table1 table1 table2 table3 table4 table4 does that make sense? Also is there a more elegant way of scripting what I have? I thought I was able to determine which DateInterval is greater the same as done with DateTime, however, either this is not true or I am doing something wrong. Please advise. Thanks! private function compareDateInterval(\DateInterval $dateInterval1, \DateInterval $dateInterval2):bool { $greaterThan = $dateInterval1 > $dateInterval2?'true':'false'; echo("test1: dateInterval1 > dateInterval2: $greaterThan\n"); $dateTimeNow = new \DateTimeImmutable; $dateTime1 = $dateTimeNow->add($dateInterval1); $dateTime2 = $dateTimeNow->add($dateInterval2); $greaterThan = $dateTime1 > $dateTime2?'true':'false'; echo("test2: dateTime1 > dateTime2: $greaterThan\n"); $timestampNow = $dateTimeNow->getTimestamp(); $timestamp1 = $dateTime1->getTimestamp(); $timestamp2 = $dateTime2->getTimestamp(); $greaterThan = $timestamp1 > $timestamp2?'true':'false'; echo("test3: timestamp1 > timestamp2: $greaterThan\n"); echo('$dateTimeNow => '.json_encode($dateTimeNow).PHP_EOL); echo('$dateInterval1 => '.json_encode($dateInterval1).PHP_EOL); echo('$dateInterval2 => '.json_encode($dateInterval2).PHP_EOL); echo("timestampNow: $timestampNow, timestamp1: $timestamp1, timestamp2: $timestamp2\n"); } <b>Warning</b>: Cannot compare DateInterval objects in <b>/var/www/app/src/Tools/PointTransitionHistory.php</b> on line <b>136</b><br /> test1: dateInterval1 > dateInterval2: false test2: dateTime1 > dateTime2: true test3: timestamp1 > timestamp2: true $dateTimeNow => {"date":"2020-08-23 15:06:24.454702","timezone_type":3,"timezone":"UTC"} $dateInterval1 => {"y":0,"m":0,"d":2,"h":14,"i":0,"s":0,"f":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":1,"days":2,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0} $dateInterval2 => {"y":0,"m":0,"d":11,"h":15,"i":0,"s":0,"f":0,"weekday":0,"weekday_behavior":0,"first_last_day_of":0,"invert":1,"days":11,"special_type":0,"special_amount":0,"have_weekday_relative":0,"have_special_relative":0} timestampNow: 1598195184, timestamp1: 1597971984, timestamp2: 1597190784
I know the forum is supposed to be used to help with any code I have come up with but here's to taking a shot anyway: I am in need of creating a php script that will allow me to input two different XML files and upon pressing "go" will compare these two files and save only the differences to a new xml file. Thing is, I have no idea where to start. Are there any php functions that exist that I can use to do this? If not, cn someone help me create one? Would this be better handled in javascript? If so, how can I do so using a method similar to the above? Any kind of help would be greatly appreciated. Hi, I am trying to write an SQL to XML converter, so so far I have all the records inputted into the db tables, and now I want to append a child, but I don't know how to compare current row's field value with the next row below it, specifically I want to check if a current row is parent of the next row. I have already got the XML to SQL function working (some bugs but for the most part it's working) So for eg: <?php $query=mysql_query("SELECT * FROM edge"); while($row=mysql_fetch_assoc($query) ) { if($row['target'] is parent of the next row), then append the next row as child of current row } ?> Table edge is one of the tables that hold target node/source(aka: parent) nodes. Any help much appreciated! Not sure if there is a better way to do this, but I want to check whether the value in a Sticky Field is the same as what is in the Database. If what is in the Sticky Field is *exactly* what is in the Database, then the User didn't update that field, and so I would NOT do an UPDATE. Seem reasonable? Here is where I grab the value out of the Form... Code: [Select] // **************************** // Process Each Form Field. * // **************************** foreach($_POST['answerArray'] as $questionID => $response){ // Copy trimmed Form array to PHP array. $answerArray[$questionID] = trim($response); And here is where I grab the existing value in the Database... Code: [Select] // ******************** // Check for Answer. * // ******************** // Build query. $q1 = "SELECT response FROM bio_answer WHERE member_id=? AND question_id=?"; // Prepare statement. $stmt1 = mysqli_prepare($dbc, $q1); // Bind variable to query. mysqli_stmt_bind_param($stmt1, 'ii', $memberID, $questionID); // Execute query. mysqli_stmt_execute($stmt1); // Store results. mysqli_stmt_store_result($stmt1); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt1)==1){ // Answer Found. // Bind result-set to variable. mysqli_stmt_bind_result($stmt1, $currResponse); // Fetch record. mysqli_stmt_fetch($stmt1); So I guess I want to compare $answerArray[$questionID] against $currResponse and see if there are any differences?! What is the best way to do that? Any better ideas of how to check to see if the User made any changes to a field so I only do an UPDATE if there was actually a change? Thanks, Debbie Hi! What should the code be if I get an IP address to a postback url and I want to find that member in my database who has that IP-address? The postback comes like this http://yoursite.com/postback.php?ip=xxx Please help how to compare date with current date let say $date="2010-10-08 2:00 PM" how can i compare $date with current date and get the result in days, hours, minutes and seconds thanks I have this code that compares date times but im not sure if its correct. if("2008-08-10 00:00:00.0" > strtotime("now")) { echo "here"; } The code echo's here, but it shouldn't because the time is less than the current time. Any ideas? Hi! I have a table called "Categories" Here is the structu id | Categories | ParentCategories 1 | Rings | Parent Category 2 | Pendants | Parent Category 3 | Ladies Rings | Rings 4 | Ladies Pendants | Rings 5 | Gents Rings | Gents 6 | Necklaces | Parent Category But Necklaces is one of those who is not going to have any subcategories or you can say, it is going to be a category by itself. So how can I construct a php statement to get data out of MySQL to determine that Necklaces is a Category which does not have subcategories. Please help ! Thank you ! - Xeirus. I run an article directory. I was wondering how I could check an article that is currently pending review against published articles in our database. What I am looking to do is to place the content of the body in the pending article into a variable. That much is easy and I know how to do that. Then I would like to use that variable to compare against other content in our database and have it output a percentage of how close it is to any other article already published in our database. Any direction our guidance with this would be so greatly appreciated. Thanks! I need to compare several arrays...to narrow down a bunch of mysql selects. I can't figure out which of the array_diff, array_unique, array_merge options there are. I need to get an array of umpires (baseball), then compare that to the array of umpires that can work a given level, then compare that to the array of umpires that can work at that school, and finally compare that to the array of umpires who have asked for the day off. In the code below, all of the selects work...the echo's that are commented out printed out what I expected them to. I'm having a problem with the array comparisons at the end of this code: Code: [Select] <?php //connect to database $dbc = mysql_pconnect($host, $username, $password); mysql_select_db($db,$dbc); //get info of game $sql = "SELECT sport,home,day FROM games WHERE `game_id` = $_GET[game]"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $game_array = $row['sport']; $home_team_array = $row['home']; $game_day_array = $row['day']; } //list of all umpires in association $sql = "SELECT ump_id FROM ump_names WHERE '$_SESSION[association_id]' = `association_id`"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $name_array[] = $row['ump_id']; // echo "<br /><br />All Ump ID's Array = "; // foreach($name_array as $name_array_final) { // echo $name_array_final . "<br />"; // } } //get bad schools list $sql = "SELECT ump_id FROM bad_school WHERE '$_SESSION[association_id]' = `association_id` AND `school` = '$home_team_array' and `sport` = '$game_array'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $bad_school_array[] = $row['ump_id']; // echo "<br /><br />Bad School Array = "; // foreach($bad_school_array as $bad_school_array_final) { // echo $bad_school_array_final . ", "; // } } //get official list at this game's level $sql = "SELECT ump_id FROM ump_names WHERE `association_id` = '$_SESSION[association_id]' AND `$game_array` = '1'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $official_level_array[] = $row['ump_id']; // echo "<br /><br />Officials that can work this level of game = "; // foreach($official_level_array as $official_level_array_final) { // echo $official_level_array_final . ", "; // } } //get vacation list $sql = "SELECT ump_id FROM days_off WHERE '$_SESSION[association_id]' = `association_id` AND `day` = '$game_day_array'"; $rs = mysql_query($sql,$dbc); while($row = mysql_fetch_array($rs)) { $days_off_array[] = $row['ump_id']; // echo "<br /><br />Officials that are on vacation this day = "; // foreach($days_off_array as $days_off_array_final) { // echo $days_off_array_final . ", "; // } } //$first_step = array_merge($official_level_array, $name_array); $first_step = array_merge($official_level_array, $name_array); $first_step_part_2=array_unique($first_step); //$second_step = array_merge($bad_school_array, $first_step); $second_step = array_merge($bad_school_array, $first_step_part_2); $second_step_part_2=array_unique($second_step); //$third_step = array_merge($days_off_array, $second_step); $third_step = array_merge($days_off_array, $second_step_part_2); $third_step_part_2=array_unique($third_step); echo "These umpires are available for this game:<br />"; foreach ($third_step as $iamavailable) { echo "$iamavailable<br />"; } ?> This prints out: Quote 2 1 2 4 5 6 10 14 15 3 7 8 9 11 12 13 16 17 It should only print out 4, 5, 6, 10, 14, 15. What I want to do is: compare $official_level_array and $name_array...only keep those that are in $official_level_array. Then, compare that result with $bad_school_array...removing those in the $bad_school_array...and keeping the ones that are left. Then, compare that result, with $days_off_array...removing those in the $days_off_array...and keeping the ones that are left. Print out what's left... Where am I going wrong? Best method to for the following? Code: [Select] // The following $str1 and $str2 should say they are identical $str1 = "abcDEF"; $str2 = "EcFabD"; // The following $str1 and $str2 should say they are NOT identical because of the "a" "A" case difference. $str1 = "abcDEF"; $str2 = "EcFAbD"; I'm comparing bitvector strings. "ABC" is different than "abc". "abc" is the same as "cba". What's the best php function or method I should use? Thank you. hi i am am making a leave calendar ...i want to compare dates and if the matches the background will be changed . i am try to do is i got two loops first for 12 months and seconds for numbers of days in that month and i am using $num = cal_days_in_month(CAL_GREGORIAN, $Month, $cYear) this will give be numbers of days in that month... then there is a my sql query which will select that dates and other data from database .. now problem i am have is that numbers of days are not increment it show date like 2011-1-1 ,2011-1-1 and so on instead of 2011-1-1, 2011-1-2.... please help me ..here <<pre lang="xml">table > <?php for($Month=01;$Month <= 12;) { ?> <tr> <td width="18%" colspan="2"><strong><?php echo $monthNames[$Month-1]; ?></strong></td> <td width="12%" colspan="2"><strong>Division</strong></td> <?php $num = cal_days_in_month(CAL_GREGORIAN, $Month, $cYear); // 31 //$dates = date("$cYear-$Month-1"); $sql ="SELECT leave_date,leave_status,leave_comments,leave_type_id FROM `hs_hr_leave` WHERE employee_id = $emplid "; $res = mysql_query($sql); for($i=1;$i<=$num;$i++) { $dates = date("$cYear-$Month-$i"); //echo $dates."<br/>"; while ($row = mysql_fetch_row($res, MYSQL_NUM)) { $time2=date("Y-n-j",strtotime ($row[0])).'<br/>'; echo "<td bgcolor='red'>".$dates."--".$time2."</td>"; //echo "<td>".$row[1]."</td><br/>"; //echo "<td>".$row[1]."</td><br/>"; //echo "<td>".$row[2]."</td><br/>"; } echo "<td width='26' height='20px' align='center' valign='middle' >".$i."</td>"; } //echo "<br/>"; $Month++; } ?> </tr> </tabl Hello dear friends, okay here is the story i've 2 incoming entries Code: [Select] $name = "Manal Nor"; $comment = "Hello lovely world"; and i've stored into database table some bad words to be banned my_table (id,word) My objective Is to compare if $name and/or $comment have any of the banned words in my_table I can apply for $name only , i mean i can compare $name and know if it have any banned words or not using the following code Code: [Select] $name = "Manal Nor"; // Example .. no bad words $sql = "SELECT * FROM my_table"; $result = mysql_query($sql); $nameArray = explode(" ", $name); $countname = count($nameArray); $checkname = 0; while ($row = mysql_fetch_assoc($result)) { for ($i == 0; $i < $countname; $i++) { if (strcasecmp($nameArray[$i], $row['word'])) { $checkname = 1; } } } if ($checkname == 1) { echo "banned"; exit; }else { echo "passed"; } it works perfect but now the question how to apply it like cheese burger i mean for both $name and $comment so that i can use any help please Hello! I've been stuck with this for a while now. First I want to say that this is a school project and not something illegal bet site. The first MySQL table have results from games and the other table contains users bets on different games.. My problem is that I don't know how to make the two tables compare and then by that change some numbers in MySQL table. So I want the code to look if the team1 and team2 on both tables are the same. Then look if the bets (1,X or 2) are the same. If they are, change (in table "Bets") w to 1 and if now change (in table "Bets") l to w. I think my problem might be that i don't know how to make the while loop... This is my code: $tbl_name="Bets"; $tbl_name2="results"; //connect to MySQL and chose database mysql_connect("$host", "$username", "$password")or die("Connection could not be Established"); mysql_select_db("$db_name")or die("Could not select DB"); $loginusername=$_SESSION['loginusername']; $sql="SELECT * FROM $tbl_name WHERE user='$loginusername'"; $r=mysql_query($sql); $i=0; $betarray=array(array()); while($rows=mysql_fetch_array($r)) { $betarray[$i]=$rows; $i++; } foreach($betarray as $insidearray) foreach($betarray2 as $insidearray1) { while($rows=mysql_fetch_array($r)) { $team1 = $insidearray['team1']; $team2 = $insidearray['team2']; if($team1 == $insidearray1['team1'] && $team2 == $insidearray1['team2']) { $team1 = $insidearray['team1']; $team2 = $insidearray['team2']; $x12 = $insidearray['1x2real'] if($x12 == $insidearray1['1x2']) { $update="UPDATE $tbl_name SET w='1' WHERE user='$loginusername' AND team1='$team1' AND team2='$team2'"; mysql_query($update); } else { $update="UPDATE $tbl_name SET l='1' WHERE user='$loginusername' AND team1='$team1' AND team2='$team2'"; mysql_query($update); } } } } } Thanks in Advance! |