PHP - Randomizing Encounters & Data Delivery Help Please.
I'm currently working on a browser based mmorpg. First things first, here is an example of my battle.php
<?php include_once 'connect.php'; session_start(); include_once 'logo.php'; ?> <link href="style.css" rel="stylesheet" type="text/css" /> <div id="login2" div align="center"> <?php if (isset($_SESSION['player'])) { $player=$_SESSION['player']; } else { echo "Not Logged in <br><br> <A href='login.php'>Login</a>"; exit; } ?> </div> <?php $playerinfo="SELECT * from players where name='$player'"; $playerinfo2=mysql_query($playerinfo) or die("could not get player stats!"); $playerinfo3=mysql_fetch_array($playerinfo2); include_once 'statpanel.php'; $pid = $playerinfo3['id']; $name = $playerinfo3['name']; $playerhp = $playerinfo3['hpoints']; $playerattack = $playerinfo3['attack']; $playerdefense = $playerinfo3['defense']; if ($playerhp < 1) { echo "You are dead!" ; echo "<br><a href='inn.php>Heal at the lake"; exit; } ?> <div id="table"> <?php if (isset($_GET['randid'])) { $randid=$_GET['randid']; $iteminfo="SELECT * from inventory where randid='$randid' AND id ='$pid'"; $iteminfo2=mysql_query($iteminfo) or die("could not get item stats!"); $iteminfo3=mysql_fetch_array($iteminfo2); if (!$iteminfo3['name']) { } else { $iname = $iteminfo3['name']; $stats = $iteminfo3['stats']; $statadd = $iteminfo3['statadd']; $type = $iteminfo3['type']; if ($type == "healing") { $newhp = $statadd + $playerhp; if ($newhp > $playerinfo3['maxhp']) { $newhp = $playerinfo3['maxhp']; } $updateplayer="update players set hpoints='$newhp' where id='$pid'"; mysql_query($updateplayer) or die("Could not update player"); $updateitem="DELETE from inventory where id='$pid' AND randid='$randid' limit 1"; mysql_query($updateitem) or die("Could not delete item"); $playerhp = $newhp; echo "Used " . $iname . " and recovered " . $statadd . ".<br>"; } }} $creature = $playerinfo3['creature']; if ($creature != 0) { $creatureinfo="SELECT * from creatures where id='$creature'"; $creatureinfo2=mysql_query($creatureinfo) or die("could not get the creature you were fighting!"); $creatureinfo3=mysql_fetch_array($creatureinfo2); } else { $creatureinfo="SELECT * from creatures order by rand() limit 1"; $creatureinfo2=mysql_query($creatureinfo) or die("could get a creature!"); $creatureinfo3=mysql_fetch_array($creatureinfo2); $cid = $creatureinfo3['id']; $updateplayer="update players set creature='$cid' where name='$name'"; mysql_query($updateplayer) or die("Could not update player"); } $creature = $creatureinfo3['name']; $creaturehp = $creatureinfo3['hpoints']; $creatureattack = $creatureinfo3['attack']; $creaturedefense = $creatureinfo3['defense']; ?> </div> <div id="player"> <?php /////player info echo "<u> " . $playerinfo3['name'] . "</u><br>"; echo "Hit points = " . $playerhp . "<br>"; echo "Attack = " . $playerattack . "<br>"; echo "Defense = " . $playerdefense . "<br><br><br>"; ?> </div> <div id="creature"> <img src="images/<?php echo $creatureinfo3['imgurl'];?>" <br> <?php ///////creature info echo "<u> " . $creatureinfo3['name'] . "</u><br>"; echo "Hit points = " . $creaturehp . "<br>"; echo "Attack = " . $creatureattack . "<br>"; echo "Defense = " . $creaturedefense . "<br><br><br>"; ?> </div> <div id="options"> <?php echo "<a href='attack.php'>Attack</a>"; echo "<br><a href='usemagic.php'>Use Magic</a>"; echo "<br><a href='useitem.php'>Use Item</a>"; echo "<br><a href='index.php'>Exit Arena</a>"; ?> </div> <div id="logout"> <?php echo "<br><a href='logout.php'><img src='images/logout.gif'>"; ?> </div> Particular functions I'm interested in for zone creation. -Pay to get in & have the initial icon switch to a now usable adventure zone. (done) -When 'adventuring' in this link. Battle php randomizes encounters between 'combat encounters' and 'non-combat' encounters. (can't get this right, and removed my utter failures from the code above as to not clutter it. Pulls randomly from the Creature DB just fine but when I try to add in the 2nd,non-combat,db..it pulls nothing.) -NonCombat encounters dish our reward. (currently my non combats do not give reward. Unlike a standard creature encounter where a players gold and exper get updated on a victory...I dont know how to immediately trigger the change on encounter & I'm epically unsure how to craft the $updateplayer= to be so broad as to include all possibilities of improvement but only to utilize the one being called upon in the encounter) -I'm also interested in updating my battle.php to include a dropdown list of usable spells/items instead of the current method of Attacking/going back/selecting magic or items/going back/...repeat. It works, sure, but its nasty..Any ideas on how to call on the database for user specific data to fill in a drop down menu? Similar TutorialsHi there. I have a javascript code that packages an array as a string and sends it to a php mailer, which then separates the string into an array for mailing using a preg_split regular expression that searches for a comma followed by an html tag.
$myWrongArray = preg_split("/,(?=<)/",$myVar); // lookahead splits the string when the comma is before a tag (the opening bracket < ) Everything works great EXCEPT when the string contains a degree sign or an &, in which case the array is returned up to the degree or & and then stops. I can’t for the life of me understand it. Any ideas? I keep getting errors that are associated with one-off and one-time occurrences. I want to tell the script to just restart itself from the beginning if it encounters any type of error, whether it by a fatal error, or any other kind. is there a way to do this? Hi guys,
Can someone help me with this if statement please. I'm trying to create two delivery amounts, so I'm trying to use an if statement instead of $delivery = "3.50";. All items should have a rate of £3.50 except item id 22 which should be 0.50p.
When I use this if statement below it just takes the price of £3.50 and ignores the else the part of the formula..
Thanks in advance.
$delivery = "3.50"; Although I found a way around it, I want to know, logically, why the behavior is so. // words.txt is a text file with dictionary words on each line $lines = file('words.txt'); // The goal is to pick two random words, 10 times. for($i = 0; $i < 10; $i++) { #shuffle($lines); <--- un-commenting this is the fix i found. $words = array_rand($lines, 2); echo "Words: " . $lines[$words[0]] . ", " . $lines[$words[1]] . "<br>"; } If i don't have shuffle() in there, I get two different set of words, not 10. ie (result from code above) Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Why is this? Day
I'm using Codeigniter and inside the framework I create a file with PHP code If I try to point to it, the web-server doesn't deliver due to permission issues.
All this is done in a 'register function' where I create some fields in a SQL
If I put the user credentials into the database 'by hand' and likewise when I
I'm pretty sure this issue has been existed before and I'd appreciate any help.
Thanks for your help in forward. Gee Edited August 17, 2020 by bogusHi All, Long long long time lurker here!
A little background to understand how this fits in So I am building a local directory for my local area as part of a community project. Part of this there is the ability for local stores to sell online locally for people to have delivered or collect. So in the UK we have postcodes in the formats: AB12 3CD, A1 2BC A12 3CD, A1B 2CD
Most delivery pricing solutions only care about the full postcode as they are all about national delivery or at best only care about the first half. Due to the local nature we need more granularity to it so we have some rules: Delivery Available EH => Price EH3 => Price EH3 1 => Price EH3 1-4 => Price
Exceptions - No Delivery allowed EH => null EH3 => null EH3 1 => null EH3 1-4 => null
Can mix and match for example:
EH3 = £2.00 EH3 2 => £2.25 EH3 5 => null
This means that ALL EH3 address the delivery cost is £2 BUT If they are in EH3 2 then its £2.25 or if the are in EH3 5 then no delivery is possible.
I have came up with this monstrosity of code that for the most part works but also can throw the wrong delivery prices out due to bugs and issues that I can't seem to work out!
Main Function: function isDeliverable($postcode, $rules){ $canDeliver = false; $deliveryValue = 0.00; $found = false; list($outward, $inward) = explode(' ', $postcode); $area = substr($outward, 0, 2); $district = substr($outward, 2); $sector = substr($inward, 0, 1); $unit = substr($inward, 1,1); $rulez = json_decode($rules, true); //RULE START - EH10 9RJ $pcFound = inRule($rulez, $postcode); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9RJ //RULE START - EH10 9R $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9R //RULE START - EH10 9A-F $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit, 1); if($pcFound){ $postArray = postcodeExploder($pcFound, 1); $pcFound = inRule($postArray, $area.$district.' '.$sector.$unit); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 9A-F //RULE START - EH10 9 $pcFound = inRule($rulez, $area.$district.' '.$sector); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9 //RULE START - EH10 1-4 $pcFound = inRule($rulez, $area.$district.' '.$sector, 2); if($pcFound){ $postArray = postcodeExploder($pcFound, 2); $pcFound = inRule($postArray, $area.$district.' '.$sector); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 1-4 //RULE START - EH10 $pcFound = inRule($rulez, $area.$district); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH20 //RULE START - EH1-20 $pcFound = inRule($rulez, $area.$district, 3); if($pcFound){ $postArray = postcodeExploder($pcFound, 3); $pcFound = inRule($postArray, $area.$district); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH1-20 //RULE START - EH $pcFound = inRule($rulez, $area); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH return ['canDeliver' => $canDeliver, 'deliveryValue' => $deliveryValue]; }
Helper Functions: function inRule($rules, $postcode, $type = null){ foreach($rules as $key => $rule){ if(substr_count($rule['postcode'], '-') !== 0 && strlen($postcode) > 2){ $pEX = postcodeExploder($rule, $type); foreach($pEX as $r){ if($r['postcode'] == $postcode){ return $rules[$key]; } //$rule['postcode'] = trim(substr($rule['postcode'], 0, strpos($rule['postcode'], "-")-1)); } } if ( $rule['postcode'] == $postcode ) return $rules[$key]; } return false; } function postcodeExploder($rule, $type){ $out = []; $r = explode(' ', $rule['postcode']); $count = count($r); //It must be in the form AB1 1C //$first = AB1 //$last = 1C-G if($count == 2){ list($first, $last) = $r; } else { $last = $r[0]; } list($left, $right) = explode('-', $last); $sec = $left[0]; $leftInward = substr($last, strpos($last, '-')-1,1); $rightInward = substr($last, strpos($last, '-')+1,1); $range = range($leftInward, $rightInward); foreach($range as $key => $ra){ if($type == 1){ $out['a'.$key] = [ 'postcode' => $first.' '.$sec.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else if($type == 2){ $out['a'.$key] = [ 'postcode' => $first.' '.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else { $out['a'.$key] = [ 'postcode' => preg_replace('/\PL/u', '', $left).$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } } return $out; } Stores Rules: $rules = '{"a1":{"postcode":"EH9","deliverable":true,"price":"1.50"},"a2":{"postcode":"EH9 7","deliverable":true,"price":"1.60"},"a3":{"postcode":"EH9 7A","deliverable":true,"price":"1.70"},"a4":{"postcode":"EH9 7AY","deliverable":true,"price":"1.80"},"a5":{"postcode":"EH1-2","deliverable":true,"price":"1.90"},"a6":{"postcode":"EH1 2-3","deliverable":true,"price":"2.00"},"a7":{"postcode":"EH4 5A-N","deliverable":true,"price":"2.10"},"a8":{"postcode":"EH","deliverable":true,"price":"1.40"},"a9":{"postcode":"TD14","deliverable":true,"price":"2.00"},"a10":{"postcode":"TD14 5DC","deliverable":false,"price":null}}';
Hi Guys I was just wondering if their is a function to randomize an array pulled from database is it possible i know their is array_rand() but it doesnt seem to work for me can someone show me where i am going wrong or do i have to do it from the actual SELECT statemant i.e ORDER_RAND(); ? Here is what my array prints out. $user_list = get_users_by_specialism($specialism); print_r($user_list); outputs. Array ( [0] => 129 [1] => 46 [2] => 57 [3] => 109 [4] => 92 [5] => 137 [6] => 238 [7] => 101 [8] => 60 [9] => 90 [10] => 112 [11] => 133 [12] => 121 [13] => 220 [14] => 275 [15] => 278 ) I basically need to make this array output in a random order everytime not by ID incrementing. Any help Please Cheers. I've used this before and it worked fine but the mt_rand is not working properly. It keeps producing the same number. I've tested it on with the $_GET to the next page and it produces a unique code but it doesn't want to insert that number into the table, just the other same, repetitive number. $transaction_id = mt_rand() . mt_rand(); $item_email = mysql_real_escape_string($_POST[email]); $item_first_name = mysql_real_escape_string($_POST[first_name]); $item_last_name = mysql_real_escape_string($_POST[last_name]); $item_street = mysql_real_escape_string($_POST[street]); $item_street2 = mysql_real_escape_string($_POST[street_2]); $item_city = mysql_real_escape_string($_POST[city]); $item_state = mysql_real_escape_string($_POST[state]); $item_zip_code = mysql_real_escape_string($_POST[zip_code]); $item_country = mysql_real_escape_string($_POST[country]); $username = $_SESSION['username']; $item_id = $_GET['id']; $item_title = mysql_real_escape_string($_POST[title]); $item_price = mysql_real_escape_string($_POST[price]); $item_shipping_cost = mysql_real_escape_string($_POST[shipping_cost]); $item_in_shipping = mysql_real_escape_string($_POST[in_shipping]); $okay = TRUE; if ($item_country == 'United States'){ $shipping = "$item_shipping_cost"; } else { $shipping = "$item_in_shipping - <span class=\"submissionfont\">International Rate</span>"; } $sql="INSERT INTO buyer (username, email, first_name, last_name, street, street_2, city, state, zip_code, country, transaction_id, date) VALUES ('$username', '$item_email', '$item_first_name', '$item_last_name', '$item_street', '$item_street2', '$item_city', '$item_state', '$item_zip_code', '$item_country', '$transaction_id', CURDATE())"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } $sql2="UPDATE product SET transaction_id='$transaction_id', sold='1', sold_date=CURDATE() WHERE id = '$item_id'"; if (!mysql_query($sql2)) { die('Error: ' . mysql_error()); } I have a form that passes multiple images and I wanted them to have a substring of a md5 encrypted time for generating unique codes so I don't delete or overwrite an older file. I keep the actual images in a folder and the path in mysql. The folder is working perfectly and there are no problems generating unique codes but I have been trying all night and I can't figure out why mysql won't update. I can actually get it to update but then I loose the functionallity of the code and if I don't upload a 4 images and leave one blank, the blank one deletes the previously uploaded field in the table row. Here is the md5 encrypted time for generating unique codes: Code: [Select] $unique = strtolower(substr(md5(time()), 0, 4)); This is how it works with the folder: Code: [Select] $filePath = $uploadDir . $unique . $fileName; This is how I get it to update mysql but then loose functionality: Code: [Select] $values[$i] = $unique . mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); Here is the entire code: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $unique = strtolower(substr(md5(time()), 0, 4)); $uploadDir = 'upload/'; if(isset($_POST['upload' . $config])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if($fileName==""){ $filePath = 'upload/'; } else{ $filePath = $uploadDir . $unique . $fileName; } $filePath = str_replace(" ", "_", $filePath); $result = move_uploaded_file($tmpName, $filePath); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[]=$filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i=1; $i<=4; $i++) { $fields[$i] = 'name'.$i; $values[$i] = mysql_real_escape_string(basename(trim($_FILES[$fields[$i]]['name']))); if($values[$i] != '') { $updateVals[] = "{$fields[$i]} = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[1]', '$values[2]', '$values[3]', '$values[4]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); $id = mysql_insert_id(); ?> <p style="font-size:35px; font-family:Arial, Helvetica, sans-serif; color:#255E67; margin-left:25px;">Your Item Has Been Uploaded!</p> <script type="text/javascript"> setTimeout('ourRedirect()', 2000) function ourRedirect() { location.href='protator_php.php?mid=<?php echo $id ?>' } </script> Am new here - looks like a great foru! I would sincerely appreciate any help anyone can give me. I have been trying to solve my problem for hours and I am not having any luck, so I thought I would post and see if anyone can help. I am very stuck and am not making much progress on this project, and I am certain the answer is very simple. I am constructing a form to collect data for a specialized purpose. The form and program actually work for its intended function, but I am trying to enhance the user experience by preventing customers from having to reenter all of their data should there be a problem with any of the data submitted. I have been able to do that with the contact form portion, but what I am having trouble with is the portion which has as many as 400 possible entries. So, in a nutshell, if the customers contact data is incomplete or in error, the form will ask them to return to the page and correct things. The previous data entered has been saved in the session and the input value will equal the previous entry. i.e. <tr> <td align="right" class="infoBox"><?php echo ENTRY_EMAIL_ADDRESS; ?></td> <td align=left><?php echo "<input type=text name='cemail' value=\"$cemail\" size=35 maxlength=35>" ?></td> </tr> Works perfectly, all well and good there. On the other 400 more or less entries, I am having a difficult time tweaking the string concatenation to work to achieve similar results. There are 4 columns each with $points entries asking for a dimension in either feet or inches. The <input name=> is one of ptaf,ptai,ptbf,ptbi, appended programatically with the corresponding row number or data point. i.e. "ptaf1", "ptai1", etc... This is produced by the example below and works perfectly also. <?php { $points=100; $i=1; while ($i <= $points) {echo ' <tr><td align="center" width="6"><b> ' .$i . '</b></td> <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" name="ptaf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>A' .$i . ' (in) <input type="text" name="ptai'.$i.'" size=4 maxlength=4> </td> <td align="right" NOWRAP>B' .$i . ' (ft) <input type="text" name="ptbf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>B' .$i . ' (in) <input type="text" name="ptbi'.$i.'" size=4 maxlength=4> </td> '; $i++; } } ?> I am trying to add <input value=$ptai.$i> for each field but as I mentioned I am not having any luck. It seems as if I have tried every combination imagineable, but still no luck. My head is spinning! The closest I seem to have gotten was with this: <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" size=6 maxlength=3 name="ptaf'.$i.'" value="' . "$ptaf" . $i . '" ></td> But line 17 for example returns this: <input type="text" value="17" name="ptaf17" maxlength="3" size="6"> To recap, I am trying to have the value set to whatever the customer may have entered previously. Again, I would most appreciate any help anyone can give me. If you need clarification on anything please let me know. Thanks AJ Hello to all, I have problem figuring out how to properly display data fetched from MySQL database in a HTML table. In the below example I am using two while loops, where the second one is nested inside first one, that check two different expressions fetching data from tables found in a MySQL database. The second expression compares the two tables IDs and after their match it displays the email of the account holder in each column in the HTML table. The main problem is that the 'email' row is displayed properly while its while expression is not nested and alone(meaning the other data is omitted or commented out), but either nested or neighbored to the first while loop, it is displayed horizontally and the other data ('validity', 'valid_from', 'valid_to') is not displayed.'
Can someone help me on this, I guess the problem lies in the while loop? <thead> <tr> <th data-column-id="id" data-type="numeric">ID</th> <th data-column-id="email">Subscriber's Email</th> <th data-column-id="validity">Validity</th> <th data-column-id="valid_from">Valid From</th> <th data-column-id="valid_to">Valid To</th> </tr> </thead> Here is part of the PHP code:
<?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo ' <tr> <td>'.$row["id"].'</td> '; while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) { echo ' <td>'.$row1["email"].'</td> '; } if($row["validity"] == 1) { echo '<td>'.$row["validity"].' month</td>'; }else{ echo '<td>'.$row["validity"].' months</td>'; } echo ' <td>'.$row["valid_from"].'</td> <td>'.$row["valid_to"].'</td> </tr>'; } ?>
Thank you. I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. <?php session_start(); if (!$_SESSION["user_name"]) { // User not logged in, redirect to login page Header("Location: login.php"); } $con = mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("login", $con); $user_name = $_POST['user_name']; $refid = $_POST['refid']; $query = "SELECT * from reference,users WHERE reference.username=users.user_name AND reference.refid='$refid' AND "; $result = mysql_query($query) or trigger_error('MySQL encountered a problem<br />Error: ' . mysql_error() . '<br />Query: ' . $query); while($row = mysql_fetch_array($result)) { echo $row['refid']; echo $row['origin']; echo $row['dest']; echo $row['date']; echo $row['exdate']; echo $row['username']; } echo "<p><a href=\"logout.php\">Click here to logout!</a></p>"; ?> <html> <form method="post" action="final.php"> Ref Id:<input type="text" name="refid"> <input type="submit" value="submit" name="submit"> </html> Here's the code that deals with the client side:
<?php session_start(); if(!isset($_SESSION['Logged_in'])){ header("Location: /page.php?page=login"); } ?> <!DOCTYPE Html> <html> <head> <!--Connections made and head included--> <?php require_once("../INC/head.php"); ?> <?php require_once("../Scripts/DB/connect.php"); ?> <!--Asynchronously Return User Names--> <script> $(document).ready(function(){ function search(){ var textboxvalue = $('input[name=search]').val(); $.ajax( { type: "GET", url: 'search.php', data: {Search: textboxvalue}, success: function(result) { $("#results").html(result); } }); }; </script> </head> <body> <div id="header-wrapper"> <?php include_once("../INC/nav2.php"); ?> </div> <div id="content"> <h1 style="color: red; text-align: center;">Member Directory</h1> <form onsubmit="search()"> <label for="search">Search for User:</label> <input type="text" size="70px" id="search" name="search"> </form> <a href="index.php?do=">Show All Users</a>|<a href="index.php?do=ONLINE">Show All Online Users</a> <div id="results"> <!--Results will be returned HERE!--> </div>search.php <?php //testing if data is sent ok echo "<h1>Hello</h1><br>" . $_GET['search']; ?>This is the link I get after sending foo. http://www.family-li...php?&search=foo Is that mean it was sent, but I'm not processing it correctly? I'm new to the whole AJAX thing. Hi, after banging my head against the wall for a while thinking this would be a simple task, I'm discovering that this is more complicated than I thought. Basically what I have is a link table linking together source_id and subject_id. For each subject there are multiple sources associated with each. I had created a basic listing of sources by subject... no problem. I now need a way of having a form to create an ordered list in a user-specified way. In other words, I can currently order by id or alphabetically (subject name lives on a different table), but I need the option of choosing the order in which they display. I added another row to this table called order_by. No problem again, and I can manage all of this in the database, however I want to create a basic form where I can view sources by subject and then enter a number that I can use for sorting. I started off looping through each of the entries and the database (with a where), and creating a foreach like so (with the subject_id being grabbed via GET from the URL on a previous script) Code: [Select] while($row = mysqli_fetch_array($rs)) { //update row order if (isset($_POST['submit'])) { //get variables, and assign order $subject_id = $_GET['subject_id']; $order_by = $_POST['order_by']; $source_id = $row['source_id']; //echo 'Order by entered as ' . $order_by . '<br />'; foreach ($_POST['order_by'] as $order_by) { $qorder = "UPDATE source_subject set order_by = '$order_by' WHERE source_id = '$source_id' AND subject_id = '$subject_id'"; mysqli_query($dbc, $qorder) or die ('could not insert order'); // echo $subject_id . ', ' . $order_by . ', ' . $source_id; // echo '<br />'; } } else { $subject_id = $_GET['subject_id']; $order_by = $row['order_by']; $source_id = $row['source_id']; } And have the line in the form like so: Code: [Select] echo '<input type="text" id="order_by" name="order_by[]" size="1" value="'. $order_by .'"/> (yes I know I didn't escape the input field... it's all stored in an htaccess protected directory; I will clean it up later once I get it to work) This, of course, results in every source_id getting the same "order_by" no matter what I put into each field. I'm thinking that I need to do some sort of foreach where I go through foreach source_id and have it update the "order_by" field for each one, but I must admit I'm not sure how to go about this (the flaws of being self-taught I suppose; I don't have anyone to go to on this). I'm hoping someone here can help? Thanks a ton in advance Say there is a complex opt in process where people start to enter their data but certain questions stop them where they close out of the page. They already entered their data and I feel there is a way to grab it and post it to mysql even though they do not click submit.
How would this be done?
A super simple example (proof of concept) or a link to a tutorial would be very useful.
Edited by brentman, 23 September 2014 - 10:42 AM. This could be PHP or MySql so putting it in PHP forum for now... I have code below (last code listed) which processes a dynamically created Form which could have anywhere from 0 to 6 fields. So I clean all fields whether they were posted or not and then I update the mySQL table. The problem with this code below is that if, say, $cextra was not posted (i.e. it wasnt on the dynamically created form), then this code would enter a blank into the table for $cextra (i.e. if there was already a value in the table for $cextra, it gets overwritten, which is bad). What is the best way to handle this? I'm thinking i have to break my SQL query into a bunch of if/else statements like this... Code: [Select] $sql = "UPDATE cluesanswers SET "; if (isset($_POST['ctext'])){ echo "ctext='$ctext',"; } else { //do nothing } and so on 5 more times.... That seems horribly hackish/inefficient. Is there a better way? Code: [Select] if (isset($_POST['hidden']) && $_POST['hidden'] == "edit") { $cimage=trim(mysql_prep($_POST['cimage'])); $ctext=trim(mysql_prep($_POST['ctext'])); $cextra=trim(mysql_prep($_POST['cextra'])); $atext=trim(mysql_prep($_POST['atext'])); $aextra=trim(mysql_prep($_POST['aextra'])); $aimage=trim(mysql_prep($_POST['aimage'])); //update the answer edits $sql = "UPDATE cluesanswers SET ctext='$ctext', cextra='$cextra', cimage='$cimage', atext='$atext', aextra='$aextra', aimage='$aimage'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } Hi, I've currently started to modify a chat script of mine to output a moderation panel but the moderation page seems empty(blank) every time I load it. What im trying to do is to take the ID part in my URL via the $_GET and look it up in my database table in the column named id, then select that specific row to be able to retrieve the StringyChat_ip and place it into another table to ban the IP and the second thing im trying to do is to be able to delete the specific row from my table.
My Http link look something like
http://imagecrab.fre.../ban.php?id=159
and my ban.php page where I want to lookup the 159 part and do the banning etc looks like
<? include("admin_code_header.php"); if ($_POST["DeletePost"]) { $id = $_POST['id']; $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; mysql_query($query); echo "ID removed from system: ".$id; } if ($_POST["BanIP"]) { $IP_To_Add = $_POST["ip"]; $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")"; $result = mysql_query($sql); } $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'",$db); while ($myrow = mysql_fetch_array($result)) { $msg = $myrow["StringyChat_message"]; $idm = $myrow["id"]; ?> <html> <form name="form<? echo $myrow["id"];?>" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input name="DeletePost" type="submit" id="DeletePost" value="Delete"> <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>"> </form> </html> <? } ?> I'm pulling data from an xml file and I'm getting a lot of duplicates. How can I remove the duplicates from the query? Code: [Select] foreach($xml->category->subcategory as $category){ echo $category[id]; }//end foreach Hi, I want to pull data from db, where sometimes all rows and sometimes rows matching given "username". Here is my code:
//Grab Username of who's Browsing History needs to be searched. if (isset($_GET['followee_username']) && !empty($_GET['followee_username'])) { $followee_username = $_GET['followee_username']; if($followee_username != "followee_all" OR "Followee_All") { $query = "SELECT * FROM browsing_histories WHERE username = \"$followee_username\""; $query_type = "followee_username"; $followed_word = "$followee_username"; $follower_username = "$user"; echo "$followee_username"; } else { $query = "SELECT * FROM browsing_histories"; $query_type = "followee_all"; $followed_word = "followee_all"; $follower_username = "$user"; echo "all"; } }
When I specify a "username" in the query via the url: browsing_histories_v1.php?followee_username=requinix&page_number=1 I see result as I should. So far so good.
Now, when I specify "all" as username then I see no results. Why ? All records from the tbl should be pulled! browsing_histories_v1.php?followee_username=all&page_number=1 This query shouldv'e worked:
$query = "SELECT * FROM browsing_histories";
I can add and delete data from my table. Now I need to be able to change one or more fields in an entry. So I want to retrieve a row from the db, display that data on a form where the user can change any field and then pass the changed data to an update.php program. I know how to go from form to php. But how do I pass the data from retrieve.php to a form so it will display? Do I use a URL and Get? Can I put the retrieve and form in the same program? |