PHP - Problem Trimming Variable
I'm more or less a noob. I have used the below code on another webpage, but on a new site that I am working on I attempted to trim the variable and now the page won't load. Can someone show me what I did wrong or a better way to accomplish this?
Code: [Select] <?php # GRAB THE VARIABLES FROM THE URL $x = $_GET['x']; $valid = array('cat:1', 'cat:2', 'cat:3', 'cat:4', 'cat:5', 'cat:6', 'cat:7', 'cat:8', 'cat:9', 'cat:10', 'cat:11'); if(in_array($x, $valid)) $trimmed = trim($x, "cat:"); include_once $trimmed . '.inc'; else include '1.inc'; ?> When I used this before my variables did not have a colon in them, so I did not have to trim the variable, thus the last part of the script was: Code: [Select] if(in_array($x, $valid)) include_once $x . '.inc'; else include('1.inc'); ?> Similar TutorialsHi Guys,
I have a search box on the site I am creating and when a user types their postcode in it the database is searched and members covering that location are shown.
I have the following which works fine ... but:
---------------------------------------------------------------------------------------------------------------
$postcode = mysqli_real_escape_string($myConnect, $_POST['searchbox']); Hi I have a recordset from a database which outputs a value of '% THOBEKA MFEKA::12110235675?' I need to seach the database based on the number between the :: and ? only. So for example '12110235675'. I have tried this with a sql statement using LIKE but its not working. How can I trim the value from the database so I only get the number out. The amount of characters before the :: can vary. Please can someone give me some advice asap. Rob I'm using the following code to attempt to strip white space from my search results: Code: [Select] while($row = mysql_fetch_assoc($rs)) { trim($row['Name']); trim($row['Address']); trim($row['City']); trim($row['State']); trim($row['Zip']); trim($row['Phone']); echo "<td>" . $row['Name'] . "</td>"; echo "<td>" . $row['Address'] . "</td>"; echo "<td>" . $row['City'] . "</td>"; echo "<td>" . $row['State'] . "</td>"; echo "<td>" . $row['Zip'] . "</td>"; echo "<td>" . $row['Phone'] . "</td>"; echo "<td>" . $row['Type'] . "</td>"; Obviously, I'm leaving out a ton of code, but the important part is that it's not stripping the white space. Things like this make me want to pound spikes into my eyes, because there's just no logical way for me to work though this. I'm extremely OCD, and so if code doesn't work the way the documentation states, I freeze. I also tried (as per another tutorial example) setting a second variable trimming it, and using the second variable in the Echo, like so: Code: [Select] $Tname = ($row['Name']); echo "Blah blah blah" . trim($Tname); That didn't work either. It's simply NOT removing the white space, despite the fact that the entire description of what "Trim" does consists of "removes white space." It boggles my mind. Am I supposed to sacrifice a goat first or something? BTW, if I go in and edit the database manually, I can strip out the spaces by hand, and everything works fine. But it seems to me like the Trim command is supposed to exist to make it so that I don't have to do that. The only thing I can guess is that for some reason the contents of the DB aren't being seen as Strings, even though they are, in fact, Strings. I'm able to maniupulate them as Strings everywhere else in the code. Just not here. Does anyone know what I did wrong? Thanks! Kyle This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=351556.0 Heres the code of the line im trying to trim
$r = mysql_query("insert into points values ('','${v[0]}', ${v[1]}, '$At')")or die (mysql_error()); mysql_query("insert ignore into toc values ('','$p1', '$At'),('','$p2', '$At'), ('','$p3', '$At'), ('','$p23', '$At')") or die (mysql_error()); if (!$r) die (mysql_error());the line pertaining to the question is the insert into points . what that part of the code does is takes this preformatted text START POINTS MrsSpacely 1 nanatravels 1 Trust_Me_honey 2 moratala 3 xxBIGDAVExx 3 Spring_Chicken 5 tomrarose 5 sitdownnplay 7 _Antoinette_ 11 Melyn 25 mokan40 30 dj_lia 10 STOP POINTS And inserts it into the points table. Which works fine but if you put a space after Stop points or before any name it comes back with an error about check spaces, and doesnt post the whole thing what i need to do is trim all the spaces from the text before it tries to go into the table Code: [Select] <? $out = preg_replace('/^(.{701}[^.]*).*/i','$1.',$detrsltnewsrow[news_desc]); echo $out; ?> </td></tr><tr><td colspan="2" class="para" style="padding-left:10px;"> <?= substr(stripslashes(trim($detrsltnewsrow[news_desc])),701) ?> </td></tr> I have the above snippet.. The first php statement, basically grasp the first 701 characters with the closet next stop "." character and out puts it. then out puts the HTML tags I have a problem with the second statement. I want to output anything after what has been outputted by: Code: [Select] <? $out = preg_replace('/^(.{701}[^.]*).*/i','$1.',$detrsltnewsrow[news_desc]); echo $out; ?> So need the correct syntax for Code: [Select] <?= substr(stripslashes(trim($detrsltnewsrow[news_desc])),701) ?> Currently it breaks at exactly the 701 character, want it to continue from the sentence the first code ended in. I'm not sure what is going on in this code, but for some reason it is not echoing my variable. I'm probably just having a total brain fart right now. Code: [Select] <?php <?php $opponent_check = isset($_POST['player_username']); $session = isset($_SESSION['user']); if($opponent_check){ include_once('connect.php'); $find_player = "SELECT * FROM stats WHERE Username = '$session'"; $s = mysql_fetch_array(mysql_query($find_player)) or trigger_error(mysql_error()); $player = $s['Username']; $player_HBS = $s['HBS']; $player_level = $s['Level']; $player_level_image = $s['Level_Image']; $player_skill = $s['Skill']; $player_attack = $s['Attack']; $player_defense = $s['Defense']; $player_strength = $s['Strength']; $player_speed = $s['Speed']; $player_accuracy = $s['Accuracy']; $player_range = $s['Range']; echo $player; }else{ echo " You didn't start a battle.<br/><br/> <a href='index.php'>Back to Matchmaking</a> <br/><br/> "; } ?> ?> My error is: Notice: in C:\xampp\htdocs\halobattles\headtohead.php on line 277 which is the fetch array line. Hi guys, I have a bit of a problem, Im using php and mysql and have succeded in storing variables inside of a URL: echo "<a href='report.php?id=$varmemberid&colour=$varcolour'>test</a> "; i retrieve varmemberid and colour from the mysql database: $tbl_name = "members"; mysql_select_db($db_name) or die (mysql_error()); $query="SELECT * FROM $db_name ORDER BY `members`.`the_members` ASC"; $result=mysql_query($query); $num=mysql_numrows($result); $i=0; while ($i < $num) { $varmemberid=mysql_result($result,$i,"member_id"); $varcolour=mysql_result($result,$i,"colour"); that works all fine and dandy for numbers eg: "123" however if i go to insert a member id of "123t" i get this error: Code: [Select] Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 12 in /home/flashx/public_html/login/report-header.php on line 47 im guessing it has something to do with the 'int' in this line: $memberid = (int) $_GET['memberid']; how do i fix this? Cheers So. I wrote this class that redirects a user to a new url: Code: [Select] <?php class PotentGate{ private $endURL, $sourceURL = 'http'; private function Gate_setURL(){ //THE BLOCK BELOW WIL ULTIMATELY REFERECE A DATABASE BACKEND FOR DESTINATION URLS. if ($this->sourceURL=="http://blah.com/blah/misc.php"){$this->endURL="http://blah.com/blah/misc2.php?r=" . $this->Gate_sourceURL;} else {} } public function Gate_getURL(){ $this->Gate_sourceURL(); echo $this->sourceURL . "<br />"; $this->Gate_setURL(); //set our destination URL based on source echo $this->endURL . "<br />"; return header('Location:' . $this->endURL); //redirect } private function Gate_sourceURL() { //TODO: Fix the $_SERVER['HTTPS'] below for https:// support. //if ($_SERVER['HTTPS'] == "on") {$this->sourceURL .= "s";} $this->sourceURL .= "://"; if ($_SERVER['SERVER_PORT'] != "80") { $this->sourceURL .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']; } else { $this->sourceURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; } return $this->sourceURL; } }//end It is implemented as such: Code: [Select] <?php include("PotentGate.php"); $gate = new PotentGate(); $gate->Gate_getURL(); //IGNORE //function below will acquire get variable //echo "You came from:" . $gate->Gate_getReferrer(); ?> This works all well and good, as far as redirection goes, but refuses to add the $Gate_sourceURL to the end url. I am left with a url like: http://blah.com/blah/misc2.php?r= and what I am trying to achieve is that it assign $Gate_sourceURL to r (so I can use the source url as a value later on), as opposed to be being blank. ex. http://blah.com/blah/misc2.php?r=http://blah.com/blah/misc1.php Any Ideas? I set up e-commence system for our company, there is a problem in this project. When I try to add the product in the cart, it can not do the Extended Price over one thousand dollars. If the Extended Price is lower than one thousand dollars, it is working. I do not know how to fix this problem . Please tell me , thank you very much The link is http://www.ptiimaging.ca/po.php?wd=1551 This is the code. <?php include("connection.php"); $sessid=session_id(); $select="select * from carttemp where sess= '$sessid'"; $result2=mysql_query($select, $connection) or die (mysql_error()); $rows=mysql_num_rows($result2); ?> <p align="center"> You currently have <?php echo "$rows "; ?>product(s) in your cart.</p> <br> <div class="tabbanner"><strong>View the Shopping cart </strong></div> <table class="tableinsert"> <tr> <th>Quantity</th> <th>Item Name</th> <th>Price Each</th> <th>Extended Price</th> <th></th> <th></th> <th></th> </tr> <?php while ($row=mysql_fetch_array($result2)) { extract($row); $price; $quan; $extprice=number_format($price*$quan,2); ?> <tr> <td> <form action="change1.php" method="post"> <input type="hidden" name="prodnum" value="<?php echo $row['prodnum']; ?>"/> <input type="hidden" name="sessid" value="<?php echo $row['sess']; ?>" /> <input type="hidden" name="hidden" value="<?php echo $row['hidden']; ?>"/> <input type="text" name="qty" size="5" value="<?php echo $row['quan']; ?>"/> </td> <td><?php echo $row['prodnum']; ?></td> <td><?php echo $row['price']; ?></td> <td><?php echo $extprice ; ?></td> <td> <input type="submit" name="submit" value="change Qty" /> </form> </td> <td> <form action="xid.php" method="post"> <input type="hidden" name="prodnum" value="<?php echo $row['prodnum']; ?>"/> <input type="hidden" name="sessid" value="<?php echo $row['sess']; ?>" /> <input type="hidden" name="hidden" value="<?php echo $row['hidden']; ?>" <input type="hidden" name="qty" size="2" value="<?php echo $row['quan']; ?>" /> <input type="submit" value="Delete Item" name="submit" /> </form> </td> </tr> <?php $total=$extprice+$total; }; ?> I'm coding a google map script in php/javascript, and I'm having a hell of a time with the address. It seems to not like any spaces for what I can tell (and I'm no php programmer). Code: [Select] /* Create an array of address values */ addresses = [ <?php for($i=0; $i < count($dataArray); $i++) { $p = $dataArray[$i]; $p = explode(":", $p); $addr = $p[4]; echo "$addr,\n"; } ?> ]; Here is data file (just one line for testing): 1315414069:41.100908:-81.442699:33:150 North Ave Tallmadge OH:1 Here is "view source" from browser: /* Create an array of address values */ addresses = [ 150 North Ave Tallmadge OH, ]; I'm stumped The map will not display with this. If I change the $addr to another variable in the array, it works fine. Trying to put the address in an info window on the map. TIA, Roots Firstly, here's the code i'm having trouble with: 'products.php': Code: [Select] <?php class product{ public $id,$brand,$partnumber,$price,$per; public function dump(){ echo "dump"; echo "<table><tr><td>$id</td><td>$brand</td><td>$partnumber</td><td>$price</td><td>$per</td></tr></table>"; } public function search($strSearch){ include ("db.php"); $query = "SELECT * FROM products WHERE partnumber=\"$strSearch\";"; $db_conn = mysql_connect($dbserver,$user,$pass); @mysql_select_db($database) or die("unable to connect to database"); $result = mysql_query($query); $num_rows = mysql_num_rows($result); if($num_rows==1){ while ($row = mysql_fetch_assoc($result)) { $id = $row["id"]; $brand = $row["brand"]; $partnumber = $row["partnumber"]; $price = $row["price"]; $per = $row["per"]; //DEBUG #1: echo "<table><tr><td>$id</td><td>$brand</td><td>$partnumber</td><td>$price</td><td>$per</td></tr></table>"; } } if($num_rows>1){ // code selection (disambiguation) here } if($num_rows<1){ // code secondary searchs here } } } ?> findprod.php: Code: [Select] <body> <form action="findprod.php" method="GET"> <input type="text" name="searchstr"> <input type="submit" value="Search"> </form> </body> <?php if(isset($_GET['searchstr'])){ $searchStr = $_GET['searchstr']; include ("products.php"); $np = new product(); $np->search($searchStr); $np->dump(); echo $np->brand; } ?> Here's my problem: after typing in a part-number to search for, I'm initializing a new 'product' class, and searching for that partnumber. I know that the query is returning 1 record just like it should. The 'DEBUG#1' line that echo's the table works just fine. The problem is, when I try to call the 'dump' method (from 'findprod.php') the variables are empty. Same thing if I try to access the variables directly. Am I doing something wrong? Perhaps I don't understand classes in PHP correctly, but it's almost as if the methods in the 'product' class aren't sharing the variables between each other. Can anyone show me what I can do to make this work? BTW: I have google'd everything I could think of for the past few days, but I just can't seem to find anything to solve this problem on my own. I've thought of possibly using SESSION variables to accomplish this task, but I'd rather not. I'm also just really curious to know why this isn't working. I need to see if someone can point out something that I have missed or maybe even point me in the right direction on something. I have a PHP script that I have run into a problem on. The basic idea of the script is that it will send out HTML formatted emails to users of my web site. The problem I am running into is storing the HTML content in memory so I can do a str_replace() looking for certain markers in the HTML and replace them with lets say the users name and custom links that pertain to the particular user that the email is going to. Currently the HTML is being stored in a MySQL database, but I have already tried reading it from a flat file. Each time I only get the first 1024 characters returned. The problem seems to be that I am running into a PHP STRING limitation. From the reading that I have done on the subject, the limit should be 1024 characters PER LINE with the variable able to hold somewhere around 8MB worth of data. I can tell you that it does not matter how many \n I put into the HTML I still only get the first 1024 characters. Is there a way I can get the entire HTML file (about 12k characters) in memory so I can work with it and hand it off to the mail function? Thanks, whit3fir3 hi,
i try to following codes from mysql "id" value to "aitlik" session variable but giving following error .
Notice: Undefined variable: row_kategori_cek in /Library/WebServer/Documents/test/cat_menu.php on line 5
<?php // this sets variables in the session $_SESSION['aitlik'] = $row_kategori_cek['id']; echo $_SESSION['aitlik']; ?> I'm using Session variables for the first time on a site I'm developing. I had it working fine while I was doing some admin and testing in subfolders. But the problem is I'm losing the session variables when I load the page from www.example.com, but it works from www.example.com/index.php. I would be happy to post some code if needed. What im trying to do is have the webpage forward the user to another page after they fill out something for a certain element in the database. But the once I put the variable into a header for forwarding, the variable is thought to be a string instead of outputting its value it holds. Heres my code.... $variable = "nextPage"; header('Location:webpage.php?id=$variable'); But whats its doing is sending the user to the url "webpage.php?id=$variable" instead of "webpage.php?id=nextPage" What can I do to get the header to read the variable value and not the variable name? All help is greatly appreciated!!! I can't get the value of $edit_proj_name and $edit_content fromn the below code. Code: [Select] <?php if(isset($id)) { $edit_proj_id = $_GET['id']; $edit_query = "Select proj_name, content from rec_proj where proj_id = {$edit_proj_id}"; $edit_result = mysql_query($edit_query, $connection); $edit_proj_name = mysql_result($edit_result,$i,"proj_name"); $edit_content = mysql_result($edit_result,$i,"content"); } ?> I wonder what the problem is.. Hi Guys,
Here is the code, once logged in using known credentials it should display the content "welcome..." but it doesn't, instead it is showing "you are not authorized..." as if the session['username']); isn't being taken?
<?php ini_set('display_errors',1); error_reporting(E_ALL); include_once 'includes/db_connect.php'; include_once 'includes/functions.php'; sec_session_start(); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Secure Login: Protected Page</title> <link rel="stylesheet" href="styles/main.css" /> </head> <body> <?php if (login_check($mysqli) == true) : ?> <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p> <p> This is an example protected page. To access this page, users must be logged in. At some stage, we'll also check the role of the user, so pages will be able to determine the type of user authorised to access the page. </p> <p>Return to <a href="index.php">login page</a></p> <?php else : ?> <p> <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login or register</a>. </p> <?php endif; ?> </body> </html>I am using WAMP and have made sure the username and password is in the database correctly, how do i debug this? the error reporting has been switched on but it doesn't help me is the problem with: <?php if (login_check($mysqli) == true) : ?>I am trying to follow this guide: http://www.wikihow.c...n-PHP-and-MySQL Please could i get some help on how to make the login "detect" the username from my MySQL database and display the username Thanks Attached Files login_success.php.jpg 14.31KB 0 downloads page.php <a href="cart.php?action=add&id=38"> cart.php session_start(); $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) $cart =$cart. ','.$_GET['id']; else $cart = $_GET['id']; } $_SESSION['cart'] = $cart; echo $cart; output: Insted of one time it adds the id two times. It prints : 38,38. can pls suggest me what's problem in the code. Thank's in advance. I wonder whether someone can help me please. I've put together the script below, which allows users to view their saved images in the original folder structure that they were saved in. Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['locationid']=$_POST['locationid']; ?> <!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"> <?php $galleryPath = 'UploadedFiles/' . $_SESSION['username'] . '/' . $_SESSION['locationid'] . '/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); $items = array(); for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) { $xmlFile = $descriptions->documentElement->childNodes->item($i); $path = $xmlFile->getAttribute('name'); $path = explode('/', $path); $t = &$items; for ($j = 0; $j < count($path); $j++) { if (empty($t[$path[$j]])) { $t[$path[$j]] = array(); } $t = &$t[$path[$j]]; } $t['/src/'] = $xmlFile->getAttribute('source'); $t['description'] = $xmlFile->getAttribute('description'); $t['size'] = $xmlFile->getAttribute('size'); } $basePath = empty($_GET['path']) ? '' : $_GET['path']; if ($basePath) { $basePath = explode('/', $basePath); for ($j = 0; $j < count($basePath); $j++) { $items = &$items[$basePath[$j]]; } } $files = array(); $dirs = array(); function urlpartencode(&$item, $index) { $item = rawurlencode($item); } foreach ($items as $key => $value) { if (isset($value['/src/'])) { $value['/src/'] = explode('/', $value['/src/']); array_walk($value['/src/'], 'urlpartencode'); $value['/src/'] = implode('/', $value['/src/']); $files[] = array( 'name' => $key, 'src' => $value['/src/'], 'description' => htmlentities($value['description'], ENT_COMPAT, 'UTF-8'), 'size' => htmlentities($value['size'], ENT_COMPAT, 'UTF-8') ); } else { $dirs[] = $key; } } $basePath = empty($_GET['path']) ? '' : $_GET['path']; $up = dirname($basePath); if ($up == '.') { $up = ''; } sort($files); sort($dirs); ?> <head> <title>View Image Folders</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="Styles/style.css" rel="stylesheet" type="text/css" /> <script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script> <style type="text/css"> <!-- .style1 { font-size: 14px; margin-top: 5px; margin-right: -50px; } --> </style> <body style="font-family: Calibri; color: #505050; margin-right: 160px; margin-left: -180px;"> <div align="right" class="style1"> <a href = "index.php" /> Add Images <a/> → <a href = "javascript:document.imagefolders.submit()"> View All Images </a> </div> <form id="imagefolders" name="imagefolders" class="page" action="gallery.php" method="post"> <div id="container"> </div> <div id="center"> <div class="aB"> <div class="aB-B"> <?php if ('Uploaded files' != $current['title']) :?> <?php endif;?> <div class="demo"> <input name="username" type="hidden" id="username" value="IRHM73" /> <input name="locationid" type="hidden" id="locationid" value="1" /> <div class="inner"> <div class="container"> <div class="gallery"> <table class="gallery-link-table" cellpadding="0" cellspacing="0"> <thead> <tr class="head"> <th class="col-name"> Name </th> <th class="col-size"> Size </th> <th class="col-description"> Description </th> </tr> </thead> <tbody> <tr class="directory odd"> <td class="col-name"> <a href="?path=<?php echo rawurlencode($up); ?>">..</a> </td> <td class="col-size"> </td> <td class="col-description"> </td> </tr> <?php $i = 1; ?> <?php foreach ($dirs as $dir) : ?> <tr class="directory <?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>"> <td><a href="?path=<?php echo rawurlencode(($basePath ? $basePath . '/' : '') . $dir); ?>"><?php echo htmlentities($dir, ENT_COMPAT, 'UTF-8'); ?></a></td> <td>Folder</td> <td></td> </tr> <?php endforeach; ?> <?php foreach ($files as $file) : ?> <tr class="<?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>"> <td><a target="_blank" href="<?php echo $galleryPath . $file['src']; ?>"><?php echo htmlentities($file['name'], ENT_COMPAT, 'UTF-8'); ?></a></td> <td><?php echo htmlentities($file['size'], ENT_COMPAT, 'UTF-8'); ?></td> <td><?php echo htmlentities($file['description'], ENT_COMPAT, 'UTF-8'); ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </form> </body> </html> I can create the list of correct folders for the user and location, but when I click the folder name to drill down to the indvidual images I receive the following error: Quote Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "/homepages/2/d333603417/htdocs/development/UploadedFiles/files.xml" in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 17 Warning: Invalid argument supplied for foreach() in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 54 Line 17 is this line: Quote $descriptions->load($absGalleryPath . 'files.xml') and line 54 is: Quote foreach ($items as $key => $value) { I know that in their own right, the piece of code which loads 'files.xml' and the code which loads the folders and images work, but it's combining them that creates the issue. I've done some research online, and I think the issue is to do with 'Session' variables and the 'foreach' array, but I'm not sure how to solve the problem. I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong. Many thanks and regards |