PHP - Simple Recomendation System
Hi i did post this on another forum which i think was the wrong place so ive posted it here aswell hope that's ok
Hi i am trying to implement a simple recomendation system where the user will select an answer usign Check boxes and each box will have a value 1 -4 Those values are then passed onto the next page. I am only trying to do it based on the Price firstly to break it down bit by bit as i am not a expert im realitvely new to PHP. I am having a error with this line while {$row = mysql_fetch_array($results,MYSQL_NUM)} //get the information from the database and store in a array THE FULL CODE SO IT CAN BE SEEN IN CONTEXT WITH THE REST IS : <?php $dbh = mysql_connect("localhost", "root")//THIS CONNECTS TO THE SERVER WITH YOUR DETAILS or die ('I cannot connect to the database because: ' . mysql_error());//IF IT CANNOT CONNECT, THIS ERROR MESSAGE WILL SHOW $results = mysql_select_db ("Computers");//THIS SELECTS THE CORRECT DATABASE FROM YOUR SERVER @$price = $_POST['price']; ?> <?PHP $total_price = 0; $total_ram = 0; $number_of_items = 0; $total_items=$number_of_items + 1 while {$row = mysql_fetch_array($results,MYSQL_NUM)} //get the information from the database and store in a array { $total_price = $row["Computer_price"] + $total_price ; // this should then start with 0 and keep adding the row up $total_items = $number_of_items = $number_of_items + 1; // this should do the same but with the item number }; $av_price = $total_price/$total_items ; //gives an average of the price attribute print $av_price //Price $lowav_price = 0; //sets the low price to 0 $medav_price = 0.75 * $av_price; // sets the next level to 75 % of the avarage $highav_price = 1.25 * $av_price; // sets the next level to 125% of the average <HTML> <BODY> // for the follwing bit the user will select a check box which will have a value and these are the cases for each option. //each option is set ot be either 0 - 75% of the average or 75%- 125 % of the average or 125% and above based ont he average of the Data in the table switch ($price) { case '1' : $price_low = 0; $price_high = >= $lowav_price ; print " (I would like to pay less and get less specifications) < ".$price_low."-".$price_high.">"; break; case '2' : $price_low = >=$lowav_price; $price_high = >=$highav_price; print " (I would like to pay for what I get so what I get is equivalent to the price) < ".$price_low."-".$price_high.">"; break; case '3' : $price_low = >=$highav_price ;$price_high = >=$highav_price; print " (I would prefer to Pay as much as possible to get the best computer) < ".$price_low."-".$price_high.">"; break; case '4' : $price_low = 0; $price_high = >=$highav_price ; " (I have no preference) < ".$price_low."-".$price_high.">"; break; } print ' price option = '.$price; print "<br>"; //gives the different vaules for each selection button on the input form for price ?> <strong> SELECTED CAMCORDERS </strong> <br> <table width="75%" border="1"> <tr> <td>Model</td> <td>Price</td> <td>Stabilization</td> <td>Optical zoom</td> <td>Image</td> </tr> <?PHP while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { if (($row["price"] >= $price_low) && ($row["price"] <= $price_high)) //price // if ($row["stabilization"] == $stabilizer_present) //stabilizer // if (($row["optical_zoom"] >= $zoom_low ) // && ($row["optical_zoom"]<= $zoom_high ) // && ($row_number < 5) ) //price //{ $row_number++; ?> <tr> <td align="center"><?php print $row["price"]; ?> </td> </tr> <?php //mysql_data_seek($result, 0); }//if }//while ?> </table> </body> </html> i AHVE TRIED TO ANNOTATE it so that you can see what i am trying to do wether i am or not is another question thanx for any replies Similar TutorialsHello, I'm in need of assistance trying to get this PHP Script working and I'm hoping you'll be able to find a solution. SQL Table Format: http://pastebin.com/LUuu2pLp Code: [Select] -- -- Table structure for table `hungergames_records` -- CREATE TABLE IF NOT EXISTS `hungergames_records` ( `user_id` int(10) unsigned NOT NULL, `victories` int(32) unsigned NOT NULL DEFAULT '0', `biggest_kill_streak` int(32) unsigned NOT NULL DEFAULT '0', `most_chests_opened` int(32) unsigned NOT NULL DEFAULT '0', `total_chests_opened` int(32) unsigned NOT NULL DEFAULT '0', `lastlogin` int(32) unsigned NOT NULL DEFAULT '0', `longest_lifespan` int(32) unsigned NOT NULL DEFAULT '0', `total_lifespan` int(32) unsigned NOT NULL DEFAULT '0', `total_points` int(32) unsigned NOT NULL DEFAULT '100', `most_points` int(32) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `hungergames_users` -- CREATE TABLE IF NOT EXISTS `hungergames_users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `donor` int(32) unsigned NOT NULL DEFAULT '0', `user` varchar(40) NOT NULL, `donor_cooldown` int(100) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `user` (`user`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12641 ; PHP Code: http://pastebin.com/aQANz0BL Code: [Select] <?php include("config.php"); $getRankQuery = "SELECT hungergames_users.id, hungergames_records.user_id, hungergames_records.victories, hungergames_records.biggest_kill_streak, hungergames_records.most_chests_opened, hungergames_records.total_chests_opened, hungergames_records.lastlogin, hungergames_records.longest_lifespan, hungergames_records.total_lifespan, hungergames_records.total_points, hungergames_records.most_points, hungergames_users.donor, hungergames_users.user FROM hungergames_records, hungergames_users WHERE hungergames_records.user_id = hungergames_users.id ORDER BY hungergames_records.total_points DESC"; $getRankResult = mysql_query($getRankQuery); //Source From: http://stackoverflow.com/questions/7704311/calculate-rank-with-points function getUserRank($searchedUserID) { $userArray = getAllUsersOrderedByPoints(); $rank = 0; $lastPoints = -1; // Never happens foreach ( $userArray as $user) { if ($user['total_points'] != $lastPoints) $rank++; if ($user['user_id'] == $searchedUserID) break; } return $rank; } while ($data = mysql_fetch_array($result)) { echo getUserRank($data["user_id"]); } ?> What am I trying to accomplish? Simple Ranking System... Basically, The total points is stored into total_points field for each user and whoever has the highest score will be Ranked #1 and count down to a the full database (Currently at 12,641 users) Now the above function getUserRank is the code I pulled from the above source listed, I think my issue relies in the function of getAllUsersOrderedByPoints(); - I've tried doing something like. Code: [Select] $row = mysql_fetch_array($getRankResult); Then adding: $userArray = $row["user_id"]; Didn't work - So if you can help me correct this than I'll be greatly appertiated. Lastly, I've tried doing: Code: [Select] $index = 1; while ($data = mysql_fetch_array($getRankQuery)) { echo $index++ . " " . $data["id"] . " ".$data["user"]." <br>\n"; } This solution works, but this solution would not work for when a "User is Search" it would count them as the highest rank 1,2,3 and wouldn't work, so either the function up there needs to be corrected or please help get a working solution, I've been googleing this issue and seems too be a common code issue with a lot people are having and not many solutions. The application that records data (Not PHP) doesn't store any data with a "Rank" table otherwise this would be a simple echo'ed out data. For a better understanding of what I'm trying to do - You may take a look at: http://justonemoreblock.com/lb/leaderboards.php Regards, Cory I have an Job, which i need some help with.
Its an ordering system.
its probably really simple to do, and i even know how i want it set up.
all databases are setup.
i cant pay much but my payment will be : 178.59 dollar
which in this point of time is calculated from 1000 dkk
the task:
an ordering system which contains:
selection menu - to select an activity, stored in an database an starting time textfield. just a normal textfield i guess a selection menu - for package selection- wich will find the packages in the package database with the matching target id for the selected Activity a textfield for amount of people participating, as a multiplier for the price. a selection menu - for additions selecting. same as the Package selector. and an price field this is in one row, where there should be a way to add these, so that its possible to get more acticity orderes + an Total amount field all this data should then be viewable in a table, which ill create, and after that be able to be send through an email that is setup in html, which ill make:) Why i need help: i took my hands full with this project, and im leaving soon for thailand, and that is why im a bit screwed;/ hope to hear from somone fast many thanks Joachim Gerber Hello, I have a simple dice system script I am using in a chat program for a website and I was wondering if someone could simply tell me how to limit the number of dice being rolled. Here are the two chunks of script that make it work: if($irc_cmd == '/d') { if($irc_cmd == $txt) { // this can only happen with a no dice - '/d' - a help request // return an explanation of the correct format $text = "dice command is /d [[n]D]s[Xm|+a|-d|/q]*"; $this->sendToUser(null, new Message($type, $this->userid, null, $text, $this->color)); return 'ok'; } // create standard failure message $invalid_msg = new Message($type, $this->userid, null, 'ERROR: invalid dice command - '.$txt.' - enter /d for help', $this->color); // remove the original command from the dice string $dicestring = str_replace($irc_cmd,'', $txt); // use lowercase versions of D and X to make parsing simpler $dicestring = strtolower($dicestring); // remove any user entered spaces $dicestring = str_replace(' ', '', $dicestring); // note that all modifiers will follow the dice spec 'nDs' // number of dice is optional e.g. 1d4 d4 and 4 all represent a single 4-sided die // if the first token is blank, then the user intended for one die e.g. /d d20 means /d 1d20 // if the is no 'd' then the user intended one die e.g. /d 20 means /d 1d20 $parts = explode('d', $dicestring); if(count($parts)>2) { // only one 'd' is allowed $this->sendToUser(null, $invalid_msg); return 'ok'; } elseif(count($parts)==1) { // if no 'D' assume '1' die $number = 1; } else { $number = (int)$parts[0]; if ($parts[0] == "") { // if $number == 0 // if no number assume '1' die $number=1; } elseif ("$number" != "$parts[0]") { // only integers allowed $this->sendToUser(null, $invalid_msg); return 'ok'; } $dicestring = $parts[1]; } if($number < 1) { // can't allow a negative number of dice $this->sendToUser(null, $invalid_msg); return 'ok'; } // check for sides and modifiers // expand the string to put spaces around all the tokens we want $dicestring = str_replace('+', ' + ', $dicestring); $dicestring = str_replace('-', ' - ', $dicestring); $dicestring = str_replace('x', ' x ', $dicestring); $dicestring = str_replace('/', ' / ', $dicestring); // explode the whole thing to create tokens $parts = explode(' ', $dicestring); // the only other tokens should be integers // allowed formats from here are s[Xm][+a][-d][/q] // we should allow any series of these in any order, applying them left to right // the first part must be the sides $sides = (int)$parts[0]; if ("$sides" != "$parts[0]") { $this->sendToUser(null, $invalid_msg); return 'ok'; } if($sides < 1) { // can't allow a negative number of sides $this->sendToUser(null, $invalid_msg); return 'ok'; } // get the user's name //$user = ChatServer::getUser($this->userid); //$name= $user['login']; // start writing the reply string $text = '*rolls* '.$number.'d'.$sides.': '; // seed the randomizer srand(time()); // with number and sides, roll the dice, adding them up $total = 0; for($i = 0; $i < $number; $i++) { $roll = (rand()%$sides)+1; if($i != 0) $text .= '+'; $text .= $roll; $total += $roll; } // now apply all the modifiers to the roll, in the order the user specified them for ($i = 1; $i < count($parts); $i+=2) { // the value needs to be an integer $value = (int)$parts[$i+1]; $v = $parts[$i+1]; if ("$value" != "$v") { $this->sendToUser(null, $invalid_msg); return 'ok'; } // the token needs to be one of the operators - otherwise abort $token = $parts[$i]; switch ($token) { case '+': // add $total += $value; break; case '-': // subtract $total -= $value; // make minimum 1 - remove this like to allow 0 and lower if ($total<1) $total=1; break; case 'x': // multiply $total *= $value; break; case '/': // divide - round up so 1d6/3 will be the same as 1d2 $total = ceil($total/$value); break; default: $this->sendToUser(null, $invalid_msg); return 'ok'; } // add the modifier to the display string $text .= $token.$value; } // and display the final result $text .= ': '.$total; // gets sent to particular room, but with users name tacked on, so a user could spoof it // at least 'msgu' looks different $this->sendToRoom(null, new Message('rpg', $this->userid, $this->roomid, $text)); return 'ok'; } and function Message($command, $userid = null, $roomid = null, $txt = null, $color = null) { $this->command = $command; if ($command == 'rpg') $this->command = 'msgu'; $this->userid = $userid; $this->roomid = $roomid; $this->color = htmlColor($color); if($command != 'rpg') { $txt = str_replace('*rolls*', 'rolls', $txt); } if(isset($txt)) { $this->txt = $this->parse($txt); } } So again all I want it to do is limit the number of dice being rolled because right now someone can do a /d 1000000d100000 and completely crash the chat for everyone. I am thinking 100 on either variable would be plenty. Thanks for your help! Hey guys first of all I got 3 files - index.php require_once('/libs/template.class.php'); $template = new Template; $template->assign("title","test"); template.php <?php echo $title; ?> template.class.php function assign($var, $val) { $var = $val; } I'm trying to assign a variable in index.php, then recall it in the template.php, how would I go about this? Thank you! I'm attempting to implement a simple social networking system but at the moment am confused about how to create a multiple query which will display a certain user's friends list. The database contains four tables, the two tables that I'm using at the moment at 'usersTable' and 'friendshipsTable' are detailed below. usersTable | Table that stores all the user data UserID | Default primary key Forename | Surname | Username | Password | Email Address | friendshipTable | Table that stores information about friendships between users FriendshipID | Default primary key userID_1 | UserID userID_2 | UserID Status | Either Pending or Confirmed. The user's id is parsed into the url, and then saved into a variable. blah.com/userprofile.php?id=6 $id = $_GET['id']; I am familiar with creating simple queries, but can't quite work out how to set up multiple table queries. What the query needs to do is to check the userID that is parsed with the url, and then check the friendshipsTable by checking if either the userID_1 or userID_2 field matches the userID to grab the records from the table where there is a match. The next step is to check to see if the friendship is 'Confirmed' or 'Pending' and if it is 'Pending' to ignore it. Once the records have then been chosen I need the query to then check the value in either userID_1 or userID_2 that doesn't match userID and then pull the user's username and name from the usersTable so it can be displayed on a webpage. I've no idea hoe much I may or may not be overcomplicating this, an example of the code that I've got so far for this query can be found below, but that's as far as I've got at the moment. $displayFriends = mysql_query("SELECT * FROM friendshipTable, usersTable WHERE friendshipTable.userID_1='$id' OR friendshipTable.userID_2='$id' "); Cheers for any help. hello dear PHP-Fans - greetings to you - and a happy new year!! i set up a WAMP-System on my openSuse 11.4 system. In order to learn as much as i can bout PHP i want to do some tests and write some scripts. Well the WAMP is allready up and running. Now i try to give the writing access to the folder mkdir /srv/www/ where the php-scripts should go in... i want to give write permission to all to all files in /srv/www As root I generally: mkdir /srv/www/ chown <webmaster usrername> /srv/www/ /srv/www/ should be readable and traversable by all, but only writeable by it's owner (the user designated as the webmaster.) can i do this like mentioned above,... Love to hear from you greetings db1 Hi everyone, I'm trying to select either a class or an id using PHP Simple HTML DOM Parser with absolutely no luck. My example is very simple and seems to comply to the examples given in the manual(http://simplehtmldom.sourceforge.net/manual.htm) but it just wont work, it's driving me up the wall. Here is my example: http://schulnetz.nibis.de/db/schulen/schule.php?schulnr=94468&lschb= I think the HTML is invalid: i cannot parse it. Well i need more examples - probly i have overseen something! If anybody has a working example of Simple-html-dom-parser...i would be happy. The examples on the developersite are not very helpful. your dilbertone Hello, im very green to php and I am having trouble creating a simple log in script. Not sure why this is not working, maybe a mysql_query mistake? I am not receiving any errors but nothing gets updated in the members table and my error message to the user displays. any help is appreciated! here is my php: <?php session_start(); $errorMsg = ''; $email = ''; $pass = ''; if (isset($_POST['email'])) { $email = ($_POST['email']); $pass = ($_POST['password']); $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); if ((!$email) || (!$pass)) { $errorMsg = '<font color="#FF0000">Please fill in both fields</font>'; }else { include 'scripts/connect_db.php'; $email = mysql_real_escape_string ($email); $pass = md5($pass); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$pass'"); $log_check = mysql_num_rows($sql); if ($log_check > 0) { while($row = mysql_fetch_array($sql)) { $id = $row["id"]; $_SESSION['id']; $email = $row["email"]; $_SESSION['email']; $username = $row["username"]; $_session['username']; mysql_query("UPDATE members SET last_logged=now() WHERE id='$id' LIMIT 1"); }//Close while loop echo "You are logged in"; exit(); } else { $errorMsg = '<font color="#FF0000">Incorrect login data, please try again</font>'; } } } ?> and the form: <?php echo $errorMsg; ?> <form action="log_in.php" method="post"> Email:<br /> <input name="email" type="text" /><br /><br /> Password:<br /> <input name="password" type="password" /><br /><br /> <input name="myBtn" type="submit" value="Log In" /> </form> Hi can someone pls help, im tryin a tutorial but keep getting errors, this is the first one i get after registering. You Are Registered And Can Now Login Warning: Cannot modify header information - headers already sent by (output started at /home/aretheyh/public_html/nealeweb.com/regcheck.php:43) in /home/aretheyh/public_html/nealeweb.com/regcheck.php on line 46 i am trying to add a like system to my forum similar to facebook where it shows how many people like a post. this is my code so far: $like_list = ""; $likes = explode("|", $post_info['post_likes']); $amount_likes = count($likes); $ac_likes = ($amount_likes / 2); $slice = array_slice($likes, 0, 4, true); $remain = array_slice($likes, 4, $ac_likes, true); $remain_num = count($remain); if ($ac_likes >= 4) { for($i=0; $i<$ac_likes; $i+=2) { $like_list .= $likes[$i].", "; } $like_list .= " and $remain_num others like this"; } elseif ($amount_likes == 1 ) { $like_list .= "0 people like this"; } elseif ($ac_likes == 1) { $like_list = implode(", ", $likes); $like_list .= " likes this"; } else { $like_list = implode(", ", $likes); $like_list .= " like this"; } $post_info['post_likes'] contains data like: Code: [Select] user1|123456789|user2|123456789 where the number is the timestamp. unfortunatly $like_list prints the username and the timestamp when i would like it to only display the username. This means printing every 2nd element in the array starting from 0. I have seen this done with for loops but i am not using one therefore i am stuck. Any ideas? and is this the best database setup for likes? the post_likes column is added on to the end of the post table.
Hi this is my login script i do have the html if you need to see it please ask & i was wondering if anyone would be kind enough to tell me how i can get my ban system to work Thanks
<?php require 'connect.php'; if(isset($_POST['submit'])) { $username = $_POST['username']; $password = $_POST['password']; //Prevent hackers from using SQL Injection $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); $user_level = $_GET['user_level']; $_SESSION['user_level'] = $user_level; if($count == 1) { $_SESSION['username']; $_SESSION['password']; header("Location: index.php"); } else { echo "Please check the username and password you entered is correct."; } if($_SESSION['user_level'] == 0) { $_SESSION['username']; $_SESSION['password']; header("Location: index.php"); } else if($_SESSION['user_level'] == -1) { die(); header("Location: banned.php"); } else if($_SESSION['user_level'] < -1) { die(); echo "An error has occurred please contact your administrator."; } else if($_SESSION['user_level'] == 1) { $_SESSION['username']; $_SESSION['password']; header("Location: admin.php"); } } ?> Edited by Tom8001, 23 November 2014 - 12:18 PM. Hi all I have been looking though loads of tutorials regarding log in method for websites (not APIs), and cant help find that they are outdated. So I am asking what is the correct way to create a log in system using php? Modern websites use JavaScript for asynchronous web requests so this requirement should also be catered for. APIs and mobile apps use access tokens which is very secure if implemented correctly. Can we use the token principle for websites? As the way I see it that most php log in systems use php sessions and they create a session and save some data in this session when the user successfully authenticates, however the session id is held in a cookie so if the cookie is stolen then they have access to your account. API access tokens are expired and refreshed periodically so is there such a implementation method for web sites too? is there any available for me to enhanced on /etc? How would I go about starting 1 i want 1 with 32 numbers and i need to have to run a query every 1hour how would i go about this? I already have a web based RPG game I am developing. Here is a small video to showcase the loot animation.
My problem is, I want to add combat. I will be using html 5 websockets. I already have a websockets server up so multiplayer isn't the issue.
A good combat system I found is on this game:
http://treasurearena.clay.io/
I'm not going to dig out the source code, and try to extract the combat system from this game. Just trying to find something similar that I can use, does anyone have any recommendations?
Thanks!
Edit: It can be as simple as swinging a freaking sword and moving. That's all I really want, I just don't want the boring 'click', 'click', and 'click' bullshit.
I have 2 referring url.
USERNAME
http://testsite.com/...gister&ref=test
USER ID
http://testsite.com/...gister&ref_id=1
1. Code to remember ref and ref_id
2. Code to allow user to insert own referrer if no ref link detected?
3. Store ref and ref_id into same column Like db referrer = username/user_id or referrer = username / referrer_id = user_id ?
PHP
$ref_id = isset($_GET['ref_id']) ? filter_input(INPUT_GET, 'ref_id', FILTER_SANITIZE_STRING) : ''); $ref = isset($_GET['ref']) ? filter_input(INPUT_GET, 'ref', FILTER_SANITIZE_STRING) : '');FORM if(!empty($_GET['ref_id'])){ print ' <tr> <td style="font-weight:bold">Referred by user id #</td> <td><input type="text" name="ref_id" maxlength="255" style="width:200px" value="'.cleanOutput($ref_id).'"></td> </tr>'; }else{ print ' <tr> <td style="font-weight:bold">Referred by</td> <td><input type="text" name="ref" maxlength="255" style="width:200px" value="'.cleanOutput($ref).'"></td> </tr>'; }2. $ref = isset($_GET['ref']) ? filter_input(INPUT_GET, 'ref', FILTER_SANITIZE_STRING) : (isset($_POST['ref']) ? filter_input(INPUT_POST, 'ref', FILTER_SANITIZE_STRING) : ''); |