PHP - My Blog, Finally Started It, Would Appreciate Any Opinions On My Logic
I am finally getting my blog started.
Actually having allot of fun with it to be honest, so far what I have been thinking about is actually working for a change lol. This is more in some ways to show you what I can do actually aswell, all of the below code is obviously in procedural, but would you change anything at all? I mean I know all of the below code is going to be a matter of preference, it works though so far, but I have been reading a few books and sort of memorised allot of it, all of the code below is my own perceptions of course, what do you think? Here's my logic (I have excluded my 'inc.database.php' file, as that's got my mysql database login details), here it is anyways: Code: [Select] <?php ini_set('display_errors', 1); // include the database connection! require_once 'inc.database.php'; function get_category($category_id) { $sql = 'SELECT category FROM blog_categories WHERE category_id = '.$category_id; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); extract($row); return $category; } // function get_responses($category_id, $post_id){ function get_responses($post_id){ $post_id = mysql_real_escape_string($post_id); $sql = 'SELECT post_title, post_text, date FROM blog_posts WHERE isreply = 1 AND parent = '.$post_id; $result = mysql_query($sql); return mysql_num_rows($result); } require_once 'header.html'; // if user has not selected a category in the URL then display the category links! if(!isset($_GET['category'])) { printf("<p>Please select a blog category</p>\n"); $sql = 'SELECT category_id, category FROM blog_categories WHERE avail = \'Y\' ORDER BY category'; $result = mysql_query($sql); // weird but if there's an error show the user firstly! if(!$result) { printf("<p class=\"error\">Could not contact server, please try again later.</p>"); } else { if(mysql_num_rows($result) > 0) { // else loop and output the category as links, so get can be retrieved the find all the posts: while($row = mysql_fetch_assoc($result)) { extract($row); // turns headings of column names into variables, so dont have to use $row['colname'] in database, like so: printf("<p><a href=\"index.php?category=%d\">%s</a><br /></p>\n", $category_id, $category); } } else { printf("<p>No categories available</p>"); } } } else { // trim the category, so someone isnt being stupid and tries to create like a DOS with empty spaces in the category URL trim($_GET['category']); // removes any blank spaces // if category ident is not empty: if($_GET['category'] != ''){ // make input safe: $category_id = mysql_real_escape_string($_GET['category']); // now need to select from which category it is! $sql = "SELECT post_id, post_title, post_text, date, username, category FROM blog_posts LEFT JOIN blog_users ON blog_posts.user_id = blog_users.user_id INNER JOIN blog_categories ON blog_posts.category_id = blog_categories.category_id WHERE blog_posts.category_id = $category_id AND approved = 1 AND isreply != 1"; $result = mysql_query($sql); printf("\n<h2>%s</h2>\n", get_category($category_id)); // calls a function to get the category name! if(mysql_num_rows($result) > 0) { // display the rows of posts: while($row = mysql_fetch_assoc($result)) { extract($row); printf("<h3>%s</h3>\n %s<br />\n By %s %s \n<br />", $post_title, $post_text, $username, $date); // get the no of replies and maybe even at some point show the oldest replies first: // get_responses($category_id, $post_id); printf("No of comments %d</p>",get_responses($post_id)); } } else { printf("<p>No posts exist in this category</p>\n"); } } else { printf("<p class=\"error\">You did not select a blog category, please try again.</p>"); } } require_once 'footer.html'; ?> Of course with the init_set('display_errors', 1) is set to true just for debugging though, when I am happy with it going live I will make this 0, so no errors appear to the user, but what do you think? It is of course entirely reading from the database, no input on this page, as that will be on other scripts. Thanks and I look forward to any replies, Jez. Similar TutorialsCode: [Select] $middle=array( "aboutme" => $aboutme, "signature" => $signature, "friends" => $f, ); foreach ($middle as $val =>$n) { $middlesection .= $middle[$val]; var_dump($middle[$val]); } Okay now How do I make this so my users can choose the ORDER of there profile sections? I: have a field in my db called "profile" varchar 255!I am so excited I am actually learning Foreach with arrays this is awesome! I am echoing out my $middlesection to display my 3sections: here is a screenshot: Now I just want my users to beable to change the order of the Array? how is this possible? :O I am so close, eventually I want them to beable to move the sections to the left or right (I would need a 3d array though) im not that smart yet Ok I am into sports games for the PS3 and I help run a baseball league for MLB 12 The Show. We currently use a website for stat tracking called LeagueDaddy (http://www.leaguedaddy.com). I created this site (http://www.stlbleague.com) and I am pulling player stats from the LeagueDaddy site and exporting them into my databases. What I would like to do is set up a database structure so we can enter stats on our server and they will be updated in real time. Now I have figured out how to use the .php?id feature (as you can see here http://www.stlbleague.com/tm.php?tid=10). Now I have an idea for a database structure and here it is: Players Table - ID, Name, Photo, Age, other personal info Stats Table - Player ID, and then all the player's stats Teams Table - Team ID, and all the general Team Info Schedules Table - Game ID, Team IDs as the home and away team Those are the 4 major tables that I would need. I already have the players and teams tables set up properly. My question is, how could I get stats to store for each individual game so I could pull standings and many other things? Is this a reasonable idea given what I already have set up? What would you recommend that I look at as for a tutorial on how to do this? There is a site www.nnlcentral.com that already achieves what I want but for a different game; I welcome all tips and suggestions Hi I am looking for opinions on the best way to secure user passwords. I am currently using crypt() with a 32 bit salt string... now my main question here would be: Should I store a randomly generated md5 hashed salt in the database for each user, or maybe a single salt string in a config file? I am looking for the most secure option here. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=323879.0 hey, i need some help if possible. I basicly have 2 tables, one has the blog posts and one has the blog comments. I'm trying to display the latest 5 blog posts (which works) but underneath each of the blog posts i need to display about 3 of the latest comments for that post but it isn't showing any. any ideas? here's my code: Code: [Select] <? session_start(); $myusername = $_SESSION['myusername']; $db_host = 'localhost'; $db_user = 'HIDDEN'; $db_pwd = 'HIDDEN'; $database = 'tjwebsol_dev'; $table = 'posts'; $table2 = 'blog_comments'; $tab = '&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;&#38;#160;'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // sending query $result = mysql_query("SELECT * FROM {$table} ORDER BY blog_id DESC LIMIT 5"); if (!$result) { die("Query to show fields from table failed"); } $sql = mysql_query("SELECT * FROM {$table2} ORDER BY comment_id ASC LIMIT 5 "); $fields_num = mysql_num_fields($result); $fields_num2 = mysql_num_fields($sql); while($row2 = mysql_fetch_assoc($sql)) { $blog_comments = $row2['comment_content']; $date_commented = $row2['date_commented']; $time_commented = $row2['time_commented']; $blog_username2 = $row2['username']; $blogid = $row2['blogid']; $comment_id = $row2['comment_id']; } while($row = mysql_fetch_assoc($result)) { $blog_title = $row['title']; $blog_content = $row['content']; $blog_username = $row['username']; $blog_date = $row['date_posted']; $blog_time = $row['time_posted']; $blog_id = $row['blog_id']; echo "<hr>"; echo "<div class='post'>"; echo "<h2 class='title'><a href='#'>$blog_title</h2></a>"; echo "<p class='byline'>posted by <b>$blog_username</b> on <b>$blog_date</b> ($blog_time)</p>"; echo "<br>"; echo "<div class='entry'>$blog_content</div><br>"; if ($blogid == $blog_id) { echo "<b>User Posted Comments:</b><br><br>"; echo "$tab<b>$comment_id</b>. $blog_comments"; echo "<br><br>"; echo "Commented posted by <b>$blog_username2</b> on <b>$date_commented ($time_commented)</b>"; echo "<br><br><br>"; } if (!isset($_SESSION['logged']) || $_SESSION['logged'] !== true) { // not logged in, move to login page echo "<b><a href='login.php'>Login</a></b> to post your comments!"; } echo "<br><br><br>"; include('blognewcomment.php'); echo ""; echo "</div>"; } mysql_free_result($result); ?> Hi guys, I am new to php and mySQL. I am trying to just learn how to input and output data to a mySQL database. What I want to do is have a single page with a text area and button where a user can enter some text and then press a submit button. When the button is pressed I want the text that the user typed to be entered in my database and then displayed below the text area. If you have any questions about what I am trying to do please ask. Thank you for your help in advance! Hello, I've just begun learning PHP and I've gotten a bit into it, but I'm nowhere near a pro. Now, I've decided to start a project that will, in my opinion, help me learn a lot. I'm just having a bit of trouble understanding exactly how to do a few things. My goal is to take the PHP forum base found here and turn it into something similar to this. I've made changes of my own to this forum base and have already finished the news posting section of it on the front page. (almost, one issue with that, more on that in a sec). I've also removed this portion: if(!$action || !in_array($action,$actions_array)){ $sql1 = "SELECT * FROM `forum_cats` WHERE `admin` < ".$row['admin']."+1"; $res1 = mysql_query($sql1) or die(mysql_error()); $i=1; while($row2 = mysql_fetch_assoc($res1)){ echo "<div id=\"fcontent\">\n"; echo " <div class=\"header\" id=\"header_".$i."\" onMouseOver=\"this.className='headerb'\" onMouseOut=\"this.className='header'\">".$row2['name']."</div>\n"; $sql2 = "SELECT * FROM `forum_sub_cats` WHERE `cid`='".$row2['id']."' AND `admin` < ".$row['admin']."+1"; $res2 = mysql_query($sql2) or die(mysql_error()); while($row3 = mysql_fetch_assoc($res2)){ echo " <div id=\"content\">\n"; echo " <a href=\"./index.php?act=forum&id=".$row3['id']."\">".$row3['name']."</a><br>\n"; echo " " . $row3['desc'] . "\n"; echo " </div>\n"; } echo "</div>\n"; $i++; } }else { from index.php so that instead of the links displayed as they would be on a forum, they can be displayed in a navbar off to the side as on the example site (this). That point leads me to my next point: the navigation bar. I'm looking to create the same sort of look (in terms of layout, not the whole.. dark design harry potter thing) as the example site, but I don't really understand how to make navbars on the sides of the whole.. news section. I just need a basic explanation of how these things can be done, but please do not give things away. After all, it is a learning experience. All help is appreciated, though! Also, let me know if you need any more information or if I was unclear. Thanks, Fae I'm going to go for broke here as this is the last thing I can think of that is going to help me learn anything... First things first. I have been reading tutorials and guides and all other things about PHP and playing around with all the codes from these tutorials and guides on my localhost. All work well. Yet, they haven't really taught me a great deal since all the code is already written and it's extremely hard to customize with the limited knowledge I currently have. I do not learn very well from sitting down and reading something that someone else has already written and then trying to work out what all the parts are. When I look at some code - I can usually figure out what is happening and what the code is doing. But it doesn't really help me understand how to write the code myself... So I thought if I made a topic where I get people to help ME write out a complete code.. I would actually learn something as I go along.. asking questions where I need to and building it exactly the way I want it. Note the 'ME' is capitalized. I don't expect everyone else to write it all down for me. I want to write it - have you guys give it the ok and we'll move on to the next bit. I know there will be parts where I am completely lost and I will need people to write down something to keep the whole thing moving. I would then ask questions untill I understood what you have provided. The whole idea of this is to build a User Login/Management system. If anyone is up for supporting this idea and helping me start from scratch let me know. Otherwise I'm not sure what else I'm going to have to do. I'm trying to learn how to create a simple API, possibly using REST. I found a lot of online tutorials on how to implement API's but how do I create my own for my own website? The API I want to make is just for querying simple data and inserting data in the DB. From what I learned, REST does HTTP requests from a XML or JSON file but is REST a script I have to download, I can't find a REST site. I'm confused.. Hi guys, Just starting to play with PHP Domdocument, only to fail at the very first step: <?php $html = 'test/php/somefile.html' ; if(!empty($html)){ $dom_1 = new domDocument ; $dom_1->loadHTML($html) ; $links = $dom_1->getElementsByTagName('li') ; foreach ( $links as $link) { // echo $link ; echo $link->nodeValue, PHP_EOL; } } ?> When I visit it in a browser I get a WSOD, what am I missing? Hey Guys, Im having a really frustrating problem with this set of PHP: writeConversationFunctions.php <?php session_start(); the function writeMessage($message){ $_SESSION['messagetest'] = $message; $chatLogFile = "log.txt"; $openChatLog = fopen($chatLogFile, 'w') or die("Failed to open Log File."); if($message == "resetnow"){ $message = ""; fwrite($openChatLog, $message); fclose($openChatLog); $_SESSION['lastMessageSize'] = 0; } elseif($message == ""){ } else{ $timestamp = date("h:i"); if(isset($_SESSION['username'])){ $username = $_SESSION['username']; } else{ $username = "Anonymous"; } if($message[0] == "/"){ $commandString = stripslashes($commandString); $commandString = htmlentities($commandString, ENT_QUOTES, 'UTF-8'); $commandString = substr($commandString, 1); $command = explode(" ",$commandString); switch ($command[0]){ case "slap": $name = command[1]; $commandResponse = '<p class="commandText">' ."You slap " . $name . "across the face.</p>"; fwrite($openChatLog, $commandResponse); fclose($openChatLog); break; } } else{ $message = stripslashes($message); $message = htmlentities($message, ENT_QUOTES, 'UTF-8'); $message = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $message); $messageString = ' <p class="message"> <span class="timestamp">' .$timestamp . '</span> <span class="username">' . $username . ': </span>' . $message . '</p>'; fwrite($openChatLog, $messageString); fclose($openChatLog); } } } writeMessage($_POST['message']); ?> Simply, the session at the top will not be created for some reason. The post data is sent from: index.php Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="styles.css" /> <title>Chatulo.us</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <script> var n = 0; $(document).ready(function () { var focused = true; $(window).focus(function () { focused = true; f(); }); $(window).blur(function () { focused = false; f(); }); var title = document.title; var f = function () { if (focused) { n = 0; document.title = "Chatulo.us / Home"; } else { // none of that else if needed here, you're only checking is focused or not. if (n == 0) { // now you're checking if its zero, so ... document.title = "Chatulo.us / Home"; } else { // you need ELSE here, otherweise you'll always use this next clause document.title = "(" + n + ") " + "Chatulo.us / Home"; } } }; function playSound(soundfile) { document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; } $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "checkSession" }, success: function (response) { $('#usernameBox').html(response); } }); $("form#sendMessageForm").submit(function () { var message = $('#messageInputField').attr('value'); $('#messageInputField').val(''); $.ajax({ type: "POST", url: "writeConversationFunctions.php", data: { message: message }, success: function () { update(); } }); return false; }); function update() { $.ajax({ type: "POST", dataType: "json", url: "readConversationFunctions.php", data: { required_function: "readConvo" }, success: function (message) { if (message.newmessage == true) { $('#messageBox').html(message.message); playSound('sounds/pop.mp3'); n = n + 1; f(); } else if (message.newmessage === false) { $('#messageBox').html(message.message); } }, complete: function () { setTimeout(update, 1000) $("#messageBox").attr({ scrollTop: $("#messageBox").attr("scrollHeight") }); } }); } $("form#getUsernameForm").live('submit', function () { var username = $('#usernameInputField').attr('value'); $.ajax({ type: "POST", url: "loginHandlers.php", data: { username: username, required_function: "usernameHandler" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); $("span#logoutText").live('click', function () { $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "removeSession" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); update(); }); </script> </head> <body> <form method="post" name="messageInput" id="sendMessageForm"> <input name="message" id="messageInputField" type="text" autocomplete="off"/> <input name="submit" type="submit" value="Send"/> </form> <div id="messageBox"> </div> <div id="usernameBox"> </div> <span id="dummy"></span> <img src="images/logo.png" width="175" height="50" alt="Logo" id="chatulouslogo"/> </body> </html> Any help with this issue would be GREATLY appreciated! Regards, Cody hey guys i'am newb in php and i'am doing some algorithm in php, in some codes i need to use session but in that particular page the code does not know if session_start() has been called or not. wonder to if there is anyway that i can get if session is started or not in my code? thanks in advance This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=332465.0 I have a file sharing script, where each file has a certain number of points. I need to subtract a set number of points from the total. I'm unsure about the logic of it. This is how I total the number of points: Code: [Select] <?php $fq = "SELECT * FROM `files` WHERE owner='$username' AND active=1"; $fw = $sql->query($fq); $reward = 0; while($fr = $fw->fetch_assoc()){ $reward = $fr['points'] + $reward; }?> I'm thinking I should use a loop, while a the number to subtract is greater than or equal than 0. Can anyone help? Logic problem: Current directory listing at: http://www.nmlta.org...member_list.php shows the format I need. The only way I have previously been able to accomplish that format is by running four separate queries in a loop, which I understand is not good. Trying to simplify this, I need to explain my data. There are companies, and contact people at those companies, and some companies have branches, and most branches have contact people at them.
There are four tables: company, co_contact, branch, br_contact. The company, co_contact and branch tables all have a field called “company_id” to match the ones that go together, and the branch table also has a “branch_id” field to match with the people in the br_contact table.
I am successful with running separate JOIN queries for company/co_contact matching on “company_id”, and for branch/br_contact matching on “branch_id”, and have successful processes for listing the data properly.
My problem is I can’t find the logic to run them all in one query or loop that will produce the desired output I’m getting with my current four-query mess. The process should go like this:
List company1 info
List all contacts at company1
List branch1 connected to company1 (if applicable)
List all contacts at branch1 of company1
List branch2 connected to company1 (if applicable)
List all contacts at branch2 of company1
Etc. until all branches are listed for company1
Start over with company2…
Here is the code for my first attempt:
<?php function listCompany($row) { echo $row['comp_name'],"<br />"; if (!empty($row['comp_uw'])) { echo $row['comp_uw'],"<br />";} echo "</b>",$row['comp_street'],"<br />"; if (!empty($row['comp_pobox'])) { echo $row['comp_pobox'],"<br />";} echo $row['comp_csz'],"<br />"; echo $row['comp_ph'],"   Fax: ",$row['comp_fx'],"<br />"; if (!empty($row['comp_tfree'])) { echo "Toll Free: ",$row['comp_tfree'],"<br />";} if (!empty($row['comp_email'])) { echo "Email: <a href='mailto:",$row['comp_email'],"'>",$row['comp_email'],"</a><br />";} if (!empty($row['comp_web'])) { echo "<a href='http://",$row['comp_web'],"' target='_blank'>",$row['comp_web'],"</a><br />";} echo "</p>"; } function listBranch($row2) { if (!empty($row2['br_name'])) { echo "<p>     <b>",$row2['br_name'],"</b><br />";} echo "     ",$row2['br_street'],"<br />"; echo "     ",$row2['br_csz'],"<br />"; echo "     ",$row2['br_ph'],"   ",$row2['br_fx'],"<br /></p>"; } function listContact($row) { if (!empty($row['cont_name'])) { echo "<p>     <b>",$row['cont_name'],"</b>, ",$row['cont_title'],"<br />";} if (!empty($row['cont_email'])) { echo "     Email: <a href='mailto:",$row['cont_email'],"'>",$row['cont_email'],"</a><br />";} echo "</p>"; } function listBranchContact($row2) { if (!empty($row2['cont_name'])) { echo "<p>          <b>",$row2['cont_name'],"</b>, ",$row2['cont_title'],"<br />";} if (!empty($row2['cont_email'])) { echo "          Email: <a href='mailto:",$row2['cont_email'],"'>",$row2['cont_email'],"</a><br />";} echo "</p>"; } // Connection to DB $mysqli = new mysqli("localhost", "nmlta_admin", "trooper", "nmlta_agents"); if($mysqli->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } // Retrieve all the data from the "company" table for County and join matching people from the "co_contact" table $query = "SELECT * FROM company LEFT JOIN co_contact ON company.company_id = co_contact.company_id WHERE comp_county = 'BERNALILLO' ORDER BY company.comp_name, co_contact.cont_rank"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); // Initialize variable $lastCompany = ''; // Start building the table to show results echo "<table border='1' cellpadding='10' cellspacing='0' bgcolor='#f0f0f0' style='margin-left:100px; margin-bottom:20px'>"; // Begin the Company "while" loop for rows in the $result while($row = $result->fetch_assoc()) { // Company - Loop 1 // Check if this is a different company than the last one if ($lastCompany != $row['company_id']) { // New Company Check - Loop 2 // If this is a different company - change the $lastCompany variable $lastCompany = $row['company_id']; echo "<tr><td><p><b>"; // List the company info only if it is not the $lastCompany listCompany($row); } // End New Company Check - Loop 2 // List all Contacts in the Company listContact($row); if ($row[next($row['company_id'] != $lastCompany)]) { // Start Branch // Retrieve all the data from the "branch" table for County and join matching people from the "br_contact" table $query2 = "SELECT * FROM branch LEFT JOIN br_contact ON branch.branch_id = br_contact.branch_id WHERE company_id = '".$row['company_id']."' ORDER BY branch.comp_name, branch.br_street, br_contact.cont_rank"; $result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__); // Initialize variable $lastBranch = 'xxx'; //Initialize $lastBranch variable // Begin the Branch "while" loop for rows in the $result2 while($row2 = $result2->fetch_assoc()) { // Branch - Loop 1 // Check if this is a different branch than the last one if ($lastBranch != $row2['branch_id']) { // New Branch Check - Loop 2 // If this is a different branch - change the $lastBranch variable $lastBranch = $row2['branch_id']; echo "<tr><td>"; // List the branch info only if it is not the $lastBranch listBranch($row2); } // End New Branch Check - Loop 2 // List all Contacts in the Branch listBranchContact($row2); } // End Branch - Loop 1 } } // End Company - Loop 1 echo "</td></tr>"; // Free result set mysqli_free_result($result); echo "</table>"; mysqli_close($mysqli); ?>My first thought was to insert the "if ($row[next($row['company_id'] != $lastCompany)]) {" qualifier after listing the contact for the company being processed, that way when I know a new company is on the next row, I can pause and run my second query to find any applicable branches that match the current company_id. The syntax must be wrong the way I have it, because I get an error with this, saying: "Fatal error: Only variables can be passed by reference in..." referencing that call in my code. I don't know if there is a syntax change that would make this work, or not. I have thought about, and tried different ways to run a query using JOIN on all four of my tables, but the resulting rows do not correspond with the order in which I need to process them, if that makes sense. I am not opposed to any suggestions that will make this work - I just can't seem to think it through and find the correct solution, if there is one. The difficulty seems to me to be that the process of listing company/contact info needs to know when it has reached the last row containing a contact tied to the company, so that the branch routine can be processed for the same company. Any help or suggestions would be appreciated. Thanks! i have two multi-dimensional arrays that i'd like to manipulate to check a few things. Their structures are different and i'm giving myself headaches trying to think through this. I have a $sums array which has information on a product in a purchase order. The second array consists of items(products) that are going to update the purchase order. So the first array key of $sums correlates with the "order" of the $items array. I'd like to write a function that: 1. Makes sure the first array key of $sums exists as an "order" value in the $items array. 2. Makes sure the $items price is greater than the $sums price Code: [Select] <?php $sums['23']['collected']['price'] = 30; $sums['73']['collected']['price'] = 60; $sums['89']['collected']['price'] = 90; $items['abc123']['order'] = '23'; $items['abc123']['price'] = 14; $items['321cba']['order'] = '73'; $items['321cba']['price'] = 79; function check_items($sums,$items) { $error = ""; //Makes sure the first array key of $sums exists as "order" value in the $items array. //If not -> $error = "Item #".$key." is not found in the items array."; //where $key is either the first array key of $sums or the "order" value in $items because they are the same thing //if found in $sums if($items[$hash]['price'] < $sums[$items[$hash]['collected']['price'] ) { $error = "Item #".$items[$hash]['order']."'s price must not be lower than ".$sums[$items[$hash]['order']]['collected']['price']; } return $error; } // $sums['23'] would cause an error because its price of 14 is less than 30 // $sums['73'] would pass because it exists in $items and its price of 79 is greater than the $sums price of 60. // $sums['89'] would cause an error because there is no $item corresponding to it ?> I just don't know where to put the foreach loops or where to even start really :/ Hi all, Its been a while since I looked at PHP and I have forgotten some basics What I am trying to achieve is display category names, sub categories and results into a list Code: [Select] <ul id="nav"> <li><a href="#">Main Cat</a> <ul> <li><a href="#">Sub Cat 1</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </li> <li><a href="#">Sub Cat 2</a> <ul> <li><a href="#">result</a></li> <li><a href="#">result</a></li> </ul> </ul> </li> What would be the best way to organise my database? Have everything in one entry like: main_id / sub_id / listing_id / listing_name or separate them into a table for cats, one for sub cats and what parent it belongs to, then a table for the listings linking to the sub cat it belongs to? I have confused myself no end on how then to display the results, so any help with would be gratefully received! Thanks Dave I am trying to understand PHP While Loops. For example. $info=mysql_fetch_array($query); will create an array of a mysql query. how does while($info=mysql_fetch_array($query) { echo $info['1']; } ensure that each element of the array is echoed. It seems that $info is a one time statement that grabs an array, how does adding While make it capable of being extended into rows? To me this says While this is true, do this. But if it is true once, how does PHP know when to stop? I want to ask the user questions by using a form. I have a text field where the user inputs either 1 or 2 and then they press submit. I can get this to work but I need to keep asking them questions based off there last answer to the previus question.
I am making a game where you start with a number ex 5 and then you either choose to take away 1 or two from that number. so we take away 2 now the number is 3 and then the computer has his go using the same number. He chooses to take away 1 which makes the number 2. Now we take away 2 and win the game for being the first one to get the number down to 0. Its a very simple game that im trying to do just to brush up on my php skills.
my code so far....
<p> please enter a number to begin the subtraction game</p> <form name="submit1" method="post"> <input type="text" name="startingNumber"> <input type="submit" name='submit1'> </form> <?php if (!empty($_POST['startingNumber'])) {?> <p>your starting number is: <?php echo $_POST['startingNumber']?></p> <?php while(!$_POST['startingNumber'] == 0){?> <p> Would you like to minus one or two from <?php echo $_POST['startingNumber']; ?></p> <form name="submit2" method="post"> <input type="text" name="oneOrTwo"> <input type="submit" name='submit2'> </form> <?php } }?>As you can see i am no where near close to getting this right. Im thinking i have to use a while loop to keep asking the question minus 1 or 2 until they reach 0. Inside this while loop im thinking i need something like a waituntil user has clicked submit. In fact i have written the same game in c++ so if it helps here is that. (it works just how i want it too) the problem im having is that in c++ you can use cin to get a input from the user and it waits until the user types in a value but im struggling to find anything like that in php. Any help would be greatly appreciated thank you. #include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int number, oneOrTwo, remainder; cout << "please enter a number to begin the subtraction game"; cin >> number; while (number != 0){ cout <<"your turn, subtract 1 or 2 from " << number << endl; cin >> oneOrTwo; if (oneOrTwo == 1 || oneOrTwo == 2){ number = number - oneOrTwo; }else{ cout << "sorry you have entered a incorrect number. Please enter either 1 or 2" << endl; continue; } if (number == 0){ cout << "congratulations! you won the game"; break; } remainder = number % 3; if (remainder % 3 == 0){ remainder = 2; } cout << "now my turn im going to subtract " << remainder << " from " << number << endl; number = number - remainder; if (number == 0){ cout << "sorry the computer won this time"; } } system("PAUSE"); return EXIT_SUCCESS; } Edited by yacobm8, 16 May 2014 - 12:14 AM. I'm trying to get code to work along the following logic (or something similar if this logic isn't PHP-friendly). If a user inputs a URL with the http, I want the url left alone. If the user inputs the URL starting with www, I want http:// added to the beginning. If the user does anything else (in other words uses a relative link), I want the beginning of my url to be added on (because then I later check for it to open the website in a new window or not). Code: [Select] if (strpos($url, "http") == 0) { $url = $url; } else if (strpos($url, "www") == 0) { $url = "http://".$url; } else { $url = "http://www.mywebsite.com/".$url; }; Any suggestions? |