PHP - Logic/reality Check Before Writing Query
I am fairly new to PHP and want to someone to check my reasoning and logic for a php query. I have a mySQL table that includes a field called authors. This field has 1+ authors names in it. If there is more than one author in the field, it has been concatenated in the following format: lastname1, firstinitial1., lastname2, first initial2., & lastname3, firstinitial3
Let's say I have three fields: lastname1, first initial1. lastname1, firstinitial1., lastname2, first initial2., & lastname3, firstinitial3. lastname3, firstinitial3. If I do a php count query on the author field I will get 1 count for the multiple field, 1 count for the lastname1 author, 1 count for the lastname3 author and 0 for the lastname2 author even though lastname1 author should be counted twice, correct? Is there anyway to write a query that will count each specific instance in the field as a hit? Am I logically tracking or off the bubble? Thanks! Similar TutorialsI'm building a query that searches by database and returns matching (or almost matching) terms. That part isn't the problem- I have it up and working. The problem is that I'm trying to narrow down the search results, and it's not working. Here's the query that works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); Here's the query that DOESN'T works: Code: [Select] $result = mysql_query("SELECT * FROM auctions WHERE type='Cars' AND name LIKE '%".$searchterm."%' OR Address LIKE '%".$searchterm."%' OR state like '%".$searchterm."%'"); What I'm trying to do is say "give me all the results from type:Cars. Instead, it ignores the WHERE type='Cars' statement, and returns results for all types. It frustrates me because I use the same exact query in a thousand other places, and it works everywhere else. For example: Code: [Select] $sql = "SELECT * FROM auctions WHERE type='Boats' AND state='$v4' ORDER BY $v1 $v2"; works just fine. I'm not exactly an expert on any of this, but I can see no logical reason why this works, but the Search code doesn't. They appear in all ways identical, at least as far as query structure goes. Can anyone spot where I screwed up? Thanks! Kyle I am adding new entries into a MySQL table via a php script. The script works fine, but I want to prevent duplicate entries. How can I check if an entry already exists on the table before initiating the query to write to the table. It is for a user registration type of system. The php script rights "AccountName" and "PassWord" to the table called "Accounts". This was my attempt to check if it exists: $query = "INSERT INTO Accounts(AccountName, Password)VALUES ('".$Accn."','".$Pwwd."')"; $Check = mysql_query("SELECT * FROM Accounts"); while($row = mysql_fetch_array($Check)) { $Account = $row['AccountName']; } if($accn != Account) { mysql_query($query); } Where $accn = the new accountname entered. I am trying to compare the new AccountName(accn) that was entered with the array of all AccountNames already in the database, and if does not already exists, then add it. I have a function to writes data I want to make sure it was successful. my function: Code: [Select] function save_ini_file($filename,$content) { $File = "ini_files/". $filename . ".ini"; echo $File; $Handle = fopen($File, 'w'); $info = $content; fwrite($Handle, $info); fclose($Handle); return true; } the if statement that calls the function. Code: [Select] if(!save_ini_file($serial,$data)) { echo "did not write"; }else{ echo "did write"; } the file is being created but I am getting the "did not write" echoed Hi, I'm trying to write a query that retrieves the comments from one table where "touser=$username" and retrieve statuses from another table where byuser=$username, and I want to sort it all by date posted. How would I go about doing that? I'm used to writing normal single table queries, but retrieving from multiple tables is new to me. Thank you for your help in advance. Hi. I have wrote a simple login script. Works perfectly. Now as my users can only register one email address at the minute if you register two the same you get the default sql error pop up. I want my own error so at the beginning of my script i wrote the following code. however. It does not seem to be running. It does not create an error but still allows duplicate emails in the database. can anyone see the error of my ways? <?php session_start(); if(isset($_POST['create'])){ //script for checking if the email account already exists $qCheckEmail = "SELECT * FROM members WHERE email='".$_POST['email']."'"; $rCheckEmail = mysql_query($qCheckEmail); $Email = mysql_fetch_array($rCheckEmail); if($_POST['email'] == $Email['email']) {$emailDup = "This email account has already been registered";} else { //Process data for validation $forename = trim($_POST['forename']); $surname = trim($_POST['surname']); $email = trim($_POST['email']); $password = trim($_POST['password']); $gender = trim($_POST['gender']); $birthday = $_POST['birthday']; $creationdate = $_POST['creationdate']; $validationID = $_POST['validationID']; $accesslevel = trim($_POST['accesslevel']); $accountType = trim($_POST['accountType']); // then the rest of the login script here How can I check to see if a query has failed, be it INSERT, UPDATE, DELETE or SELECT? I want to return one value if the query fails, but a different one if it works. For example, if I have a query to delete a row, but somehow this query fails because the row doesn't exist, then I want to check that it's failed and then output a result Hey Guys, I need some assistance, hopefully there is just a simple command that I am not aware of or an easy answer to this. Suppose I have an array with x amount of values... $arr = array("111111" => 10, "222222" => 20); And i have a query.. mysql_query("SELECT * FROM table WHERE table.zip = "111111" "); Suppose I want to modify the query, so it can check if table.zip exists anywhere in $arr, regardless of length of array. And Select the value that the array location refers to. So I need it to check if "111111" is anywhere in the array, and then take the value 10. The example I am applying this to is that I have a database full of business addresses/zip codes and a database full of every zip code in country. So I have a script to get every zip within x miles, and the distance from it, but need to be able to apply it when I query my business addresses to see if it exists within x miles. Thanks! Greg I'm trying to get a nickname system working for a little project, but I've run into a problem. This code that I wrote here gets the users nickname from their username: Code: (php) [Select] $user = $_GET['user']; @mysql_select_db("db") or die( "Unable to select database"); $query = mysql_query("SELECT `nickname` FROM `info` WHERE `username`='$user'"); WHILE($rows = mysql_fetch_array($query)): $nickname = $rows['nickname']; echo $nickname; endwhile; ?> But the problem is, if the user doesn't have a nickname then it just turns up blank. How can I check if the output of $nickname is blank and if it is then just return their normal name ($user) Thanks Oh, and how to you format php code to look like php code on these forums? 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? Hello there, I'm new to this site/forum so i dont know if this is the right forum to post a code review / commentary request .... I have a function that handels the sql code... Know i would like to know what you think off it ? can I do something different or better ?.. Code: [Select] <?PHP /* * Private function db_query($sql) | handle.... * whit checking en extendid error reporting.... * Runs a query but does not return a result array.... * @String $sql | this is the sql query you whant to run..... */ private function db_query($sql) { $this->sql = $sql; switch ( DEBUG_QUERY ) { // check debug mode... case true: try { // probeer query uit te voeren... $handle = $this->query($this->sql); if(!$handle) // if error whit the query... { $this->rollback(); throw new Exception('MySQLi Query went wrong error ==> ' . mysqli::$error); } } catch (Exception $e) { // error afhandeling and reporting.. echo '<hr />'; echo '<span style="color:red"><b>A MySQLi Query went wrong:</b></span><br />'; echo var_dump($e->getMessage()); echo '<br />'; echo nl2br($e->getTraceAsString()); echo '<br />'; echo 'Error in File: ' . $e->getFile(); echo '<br />'; echo 'Thrown Exception on line: ' . $e->getLine(); echo '<br /><hr />'; exit(); } // end error afhandeling and reporting... break; case false: $handle = $this->query($this->sql); break; } // end switch... return $handle; } /* * Public function db_Do | handels the insert, update, select and delete query's * A lot off optional options for the different query's * @String $type | Choose between the four type's | select, insert, update or delete | Default is Select * @String $table | Select witch table you whant to use | give a vailid tablename you whant to use in the query * @String $values | Input the values uw whant to select from the table | * for all - row1, row2, row3 | id, username, password * @String $where | The where operator for the query | Where $where = | give a vailid row name | if used you must fill in the other two where operators | default = empty (optional) * @String $opparator | The operator for the where operator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | where 2 | default = empty (optional) * @String / Int $where_val | The where value for the where operator | WHERE $where{id} $opparator{=} $where_val{1} | where 3 | default = empty (optional) * @Bool $use_and | if TRUE you can use the AND operator | linked to the other three and operators | if you use 1 you must fill in all 4 of them | default = false (optional) * @String $and_key | Value for the AND operator | same as $order_by | AND $and_key{username} | and 2 | default = empty (optional) * @String $and_oparetor | The operator for the and section | same as $opparator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | and 3 | default = '=' (optional) * @String $and_value | The value for by the and_key | same as $where_val | AND $and_key{username} $and_oparetor{=} $and_value{'jhon'} | and 4 | default = empty (optional) * @String $order_by | value for the Order by operator only used if hase a value | ORDER BY $order_by{id} | if used you must alsow fill in the second order by operator | default = empty (optional) * @String $order_key | Value for the Order key by the order value | ORDER BY $order_by{id} $order_key{asc, desc} | check in_array | default = asc (optional) * Error msg and checks includid, Failsafe... * Runs the query and returns a row.... * Uses the db_query function... * Version 1.0.0 */ public function db_Do($type = 'select', $table, $values, $where = NULL, $opparator = NULL, $where_val = NULL, $use_and = FALSE, $and_key = NULL, $and_oparetor = '=', $and_value = NULL, $order_by = NULL, $order_key = 'ASC') { switch ( DEBUG_QUERY ) { // check debug mode... case true: if(in_array($type, $this->SQL_TYPE, TRUE)) { // check for correct $type... if(in_array($order_key, $this->ORDER_KEY, TRUE)) { // check if order key is allowd $order_key.... if(in_array($opparator, $this->OPARATORS, TRUE)) { // check for vallid oparetors... if(empty($table) or strlen($table) >= 4) { // check if $table correct is.... if(empty($values) or strlen($values) >= 4) { // check if the $values are given correctly.... if(in_array($and_oparetor, $this->OPARATORS, TRUE)) { // check if and oparetor is allowd..... switch( $type ) { // witch type... case 'select': // Build the SQL Query.... $query = 'SELECT '. $this->real_escape_string($values) .' FROM '. $table .' '; if(!empty($where) and (empty($where_val) or empty($opparator))) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } elseif(!empty($where) || !empty($where_val) || !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } if(!empty($order_by)) { $query .= ' ORDER BY '. $order_by .' '. $order_key .''; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = $handle->fetch_assoc(); mysqli_free_result($handle); break; case 'insert': // Build the SQL Query...... $query = 'INSERT INTO '. $table .' ('. $this->real_escape_string($values) .') '; $query .= 'VALUES ('. $this->real_escape_string($where) .')'; $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle... break; case 'update': // Build the SQL Query...... $query = 'UPDATE '. $table .' '; $query .= 'SET '. $this->real_escape_string($values) .' '; if(!empty($where) and !empty($where_val) and !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } elseif(empty($where) or empty($where_val) or empty($opparator)) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; case 'delete': //Construct the delete query..... $query = 'DELETE FROM '. $table .' '; $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; } // end switch( $type )..... } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the AND section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // Correct VALUES..... $row = 'Sorry you have to fill in the values parameter correctly and it hase to be bigger then 3 chars.'; } } else { // Correct TABLE.... $row = 'Sorry you have to fill in the table parameter correctly and it hase to be bigger than 3 chars.'; } } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the WHERE section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // if order_key is NOT allowd.... $row = 'Incorrect Order by opparator: <b>'. $order_key .'</b> choos between (asc or desc)'; } } else { // if not correct type return error msg.... $row = 'Incorrect type: <b>'. $type . '</b> choose between (select, insert, update or delete)'; } break; // end case true... case false: break; // end case false... } // end switch( debug_query )... return $row; } // end public function db_Do()..... ?> It's still a work in process so it's not done yet... 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 :/ 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 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? 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 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 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? Hey guys, I am not really asking for pure php code, as I know alot of if's and switches could do this, but I am thinking of a easier method, of using for each or something to make it alot more better (performance wise) here it goes. I have 70 images, 1.png to 70.png, they are STARS. People on my forum software can upgrade there account via paypal to become a "Site Donor" I use the paypal's IPN to update the "amount" field value in mysql for each member. So if a user donates 10$, and then he donates 10$ tomorrow, the "amount" field will have a total of "20$" in it. Now I need to show a page where it list's all 1-70.png STARS, and it will have a radio button next to each star for them to select (Based on the amount they donate) So if a person has only dated 5$ dollars, they will have access to starts 1 through 10.png. If a person donated 20$ they will have access to 1-20.png Stars to chose from, (and so on) What would be the easiest way to check the input so people can't tamper with my form value to get a let's say 50.png star when they only donated like 10 dollars? Should I use just a simple switch function with 70 Cases? Or is there a easier method? and how would I go about storing a value in a field when they make a payment so then I can just simply check that field with the users input so they can't tamper the data and try to get a higher star? So I have this killer script I wrote for article management across multiple sites. I am trying to make a drip feed so you can set up a bunch of articles for one site to drip out over x amount of days. Then you could do that for your next site etc... so you do not need to manage all of your 20 blogs/sites a day. So, I am thinking I have all these variables in a table: Code: [Select] Table 1 Article - URL for article - Title - Keywords - Anchor Text - URL link - Category - Site to post to ID Code: [Select] Table 2... URL - Date Posted - Drip Feed (maybe include category here because in table 1 it will repeat category for every row of the same url) Then I make a script that runs on a cron job every 2-4 hrs... Not sure the best way to make the script and also not sure the best way to post this info to different sites... ideally id like to be able to post to joomla, wordpress, blogspots, etc... basically many different kinds of sites. Any suggestions would be appreciated... no need for you to write the code I can do that, just need a plan. |