mschroeder 251 Bestower of Knowledge Team Colleague

Are these account numbers unique to the whole system, or is it acceptable that in each of those 6 tables the AI will start at 1?

mschroeder 251 Bestower of Knowledge Team Colleague

This has been driving me up the wall all day so I put some code down and have something I like.

This is a class which extends the SplFileObject class and overloads its iterator methods. It also implements the seek method. I did play with this, but there may be some oversights take it for what it is.

- ReverseSplFileObject.php -

<?php
class ReverseSplFileObject extends SplFileObject {
	
	protected $_line = 0;
	protected $_pointer = 0;
	protected $_begin;
	protected $_eol = "\n";
	protected $_trim = TRUE;

    public function __construct($filename, $trim = true) {
		//Setup the SplFileObkect
		parent::__construct($filename);
		
		//Should we trim the output?
		$this->_trim = $trim;
		
		//Set our line position from the end at 0
		//Numbers increment positively but lines go in reverse order
		$this->_line = 0;
		
		//Seek to the first position of the file and record its position
		//Should be 0
		$this->fseek(0);
		$this->_begin = $this->ftell();
		
		//Seek to the last position from the end of the file
		//This varies depending on the file
		$this->fseek($this->_pointer, SEEK_END);
    }

    public function rewind() {		
		//Set the line position to 0 - First Line
		$this->_position = 0;
		
		//Reset the file pointer to the end of the file minus 1 charachter
		$this->fseek(-1, SEEK_END);
		$this->_pointer = $this->ftell();
		
		//Check the last charachter to make sure it is not a new line
		$c = $this->fgetc();
		while($c != $this->_eol){
			--$this->_pointer;
			$this->fseek($this->_pointer);
			if( $this->ftell() < 0 ){
				break;
			}
			$c = $this->fgetc();
		}
		//File pointer is now at the beginning of the last line
    }

    public function current() {
		//Return the …
mschroeder 251 Bestower of Knowledge Team Colleague

- alfred

If you use the file() function to load the file like that, it will load the entire file into memory. For files with only a few hundred lines this won't be an issue, for files with hundreds of thousands of lines, this will become very intensive.

For example, I have a dictionary file that has 135K lines. Only a single word per line. When I load it with file() memory usage goes from 379288 bytes to 15289096 bytes. The original file is only 1.29MB in size.

mschroeder 251 Bestower of Knowledge Team Colleague

Is the file of a variable length, where you do not know the total number of lines, or will the file always have a fixed number of lines?

mschroeder 251 Bestower of Knowledge Team Colleague

PHP would be used to make the database connection and query the database, but the actual calculation can be done at the mysql server. With PHP processing the results and displaying them how you see fit.

There are a lot of examples covering this topic:
http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
http://www.codewalkers.com/c/a/Miscellaneous-Code/Calculate-Distance-Between-Two-Points/
http://stackoverflow.com/questions/407989/calculating-distance-between-zip-codes-in-php
http://go.sparkfire.net/2009/09/search-by-location-miles-from-zipcode-in-php/

There are tons more but these looked like decent examples with explanations. Hope it helps.

mschroeder 251 Bestower of Knowledge Team Colleague

I disagree seeing as how that is not the way a zipcode is structured.

First digit is the state assignment
Second and Third are the regional processing facility (not the region)
Fourth and Fifth represent the town, or area within a large enough city.

Within a 10 mile radius of myself, there are 5 three digit zipcode prefixes.
within 20 miles you cross state lines and that number increases to 10 or more plus additional local zipcode prefixes.

Despite the geographic derivation of most ZIP codes, the codes themselves do not represent geographic regions; they generally correspond to address groups or delivery routes. Consequently, ZIP code "areas" can overlap, be subsets of each other, or be artificial constructs with no geographic area (such as 095 for mail to the Navy, which is not geographically fixed). Similarly, in areas without regular postal routes (rural route areas) or no mail delivery (undeveloped areas), ZIP codes are not assigned or are based on sparse delivery routes, and hence the boundary between ZIP code areas is undefined. For example, some residents in or near Haubstadt, Indiana, which has the zip code 47639, have mailing addresses with 47648, the zip code for neighboring Fort Branch, Indiana while others living in or near Fort Branch have addresses with 47639. Many rural counties have similar logistical inconsistencies caused by the aforementioned sparse delivery routes, often known as Rural Routes or by some other similar designation.

http://en.wikipedia.org/wiki/ZIP_code

mschroeder 251 Bestower of Knowledge Team Colleague

PHP is server-side. It can ONLY work with the directory structure on the server.

This sounds like something for a client-side language like javascript, but I imagine there are security restrictions in place in most/all browsers to prevent or hinder the ability to recurse through the user's harddrive. Can't say for sure off the top of my head.

mschroeder 251 Bestower of Knowledge Team Colleague

The way this is done, is using a database of zipcodes with geographic information attached, latitude and longitude.

Given a user's zipcode, its a matter of finding all zipcodes within a certain distance, say 10 miles, and then any store which has a location within those zipcodes.

Here is a great Scribd doc that explains it and shows the formulas as well as improvements and how to implement it within a mysql query: http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL

There are some free geolocation databases but I can't suggest any of them in particular or speak to their accuracy. Maybe someone else can point you to a really good one. There are a lot of commercial ones available if you have a budget.

mschroeder 251 Bestower of Knowledge Team Colleague

PHP is a server-side language. It could care less what browser you are using.

I'm going to take a total shot in the dark and say if this works in FF and not in IE then it has something to do with how the data is being passed from your form.

I would like to see the generated form HTML and also the php what is being used to set the variable $fileType. I'm assuming $image_array is an array of file types you're checking against as well.

mschroeder 251 Bestower of Knowledge Team Colleague

It will not execute server side files, we can just pass the variable to javascript from php. or we can call a php file from javascript function like window.location="delete.php". Thats it! we can't do more from javascript since it was a client side script functions.

I agree with Krstevski, using AJAX for this is a perfect example of its usage.

Raja's example of the form and php script will redirect the user away from the page and to a php script every time they click a like button. It will work but will require two page loads to effectively get back to where the user already was.

  1. The user's ID is passed to a javscript function
  2. The function takes that value and makes a POST request to a php script
  3. The php script takes that value via $_POST and makes a database request liking the page by the user
  4. The php script can then return data back to the ajax request, usually via JSON or XML.
  5. The javascript function updates the button to a "liked" button instead of "like"

There are a lot of ways to accomplish this. Me personally I like working with jQuery for ajax and dom manipulation (http://api.jquery.com/jQuery.ajax/) but you could also implement this yourself without an external library if you're proficient enough in javascript.

mschroeder 251 Bestower of Knowledge Team Colleague

Put it in place of the 'yyyy-mm-dd' the first parameter of the DateTime object will accept any string that strtotime will accept.

http://www.php.net/manual/en/datetime.formats.php

mschroeder 251 Bestower of Knowledge Team Colleague
<?php

//Set date according to formats accepted by strtotime
//Set timezone to use
$day = new DateTime('yyyy-mm-dd', new DateTimeZone('America/New York'));

//Modify to one month in future
$day->modify('+1 month'); 

//Display updated date
echo $day->format('Y-m-d');

This isn't tested. but the date() function in php does not return an object and in your code, $day would actually be a string. This would cause the non-object error.

This updated code should do what you want, but I haven't tested it.

mschroeder 251 Bestower of Knowledge Team Colleague

I think the information provided by mysql on this topic will be of use:
http://dev.mysql.com/tech-resources/articles/hierarchical-data.html

mschroeder 251 Bestower of Knowledge Team Colleague
SELECT SUM( table.column ) as `downloads`

Without more information that is as specific as I can get

mschroeder 251 Bestower of Knowledge Team Colleague

Bill,

Having little if any biology background, can you tell does your relational tree have multiple parents like a family tree?

[A]   [B]
      |_____|
         | 
   -------------
   |     |     |
  [C]   [D]   [E]

or does a tree only have one parent in your use case?

[A]
       |
  ------------
  |    |     |
 [B]  [C]   [D]
mschroeder 251 Bestower of Knowledge Team Colleague

If you want a truly universally unique identifier (UUID) then check out this post on the php.net site.
http://www.php.net/manual/en/function.uniqid.php#94959

MySQL 5.x also has support for UUID's
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

There is also a UUID pecl extension.
http://pecl.php.net/package/uuid

mschroeder 251 Bestower of Knowledge Team Colleague

-virtual

This is a perfect use of the RecursiveArrayIterator in the PHP5 SPL. You are using PHP5 right?

<?php

$root = array(
		"paa" => array (
			"adi1" => array (
				"cir1" => array (
							"aka",
							"ra", "vinodh","dkido"
							),
															
				"cir2" => array (
						  	"muta",
							"la"
							),
																
				"cir3" => array	(
							"ezut",
							"telAm"
							),
																
				"cir4" => array	(
							"ati"
							)
				),

			"adi2" => array (

				"cir1" => array (
							"paka",
							"vaV"
							),
												
				"cir2" => array (												
							"mutaR",
							"RE"
							),
												
				"cir3" => array	(
							"ula",
							"ku"
							)
				)				
		                )
            );

$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($root), RecursiveIteratorIterator::SELF_FIRST);

foreach($rit as $key=>$value){
	if( $rit->hasChildren() === TRUE ){
		echo 'inside loop of '.$rit->key().'<br />';
	} else {
		echo $key.'==>'.$value.'<br />';
	}
}
inside loop of paa
inside loop of adi1
inside loop of cir1
0==>aka
1==>ra
2==>vinodh
3==>dkido
inside loop of cir2
0==>muta
1==>la
inside loop of cir3
0==>ezut
1==>telAm
inside loop of cir4
0==>ati
inside loop of adi2
inside loop of cir1
0==>paka
1==>vaV
inside loop of cir2
0==>mutaR
1==>RE
inside loop of cir3
0==>ula
1==>ku

First we create a new RecursiveIteratorIterator object and pass it an instance of RecursiveArrayIterator. We pass $root in this case, your array, to the RecursiveArrayIterator. $rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($root), RecursiveIteratorIterator::SELF_FIRST); The second parameter RecursiveIteratorIterator::SELF_FIRST is one of three possibilities. LEAVES_ONLY, SELF_FIRST, CHILD_FIRST.


  • LEAVES_ONLY will only return leaves and not the containers.
  • SELF_FIRST will list the containers first and then each of their proceeding children.
  • CHILD_FIRST will reverse the way the current results look. Processing …
mschroeder 251 Bestower of Knowledge Team Colleague

None of what was explored here is url encoding. URL encoding means encoding characters that not safe to be passed in the url, for example a "/" or a "+". When you url encode a url you encode those in hex or decimal format. "/" => %2F => %47.

For example say you passed a directory path as a variable in the url:
domain.com/?secret=/home/user/secret/folder/

This would cause problems if you didn't encode the url. If you HAD to pass this in the url you could encode the "/"'s as:
domain.com/?secret=%2Fhome%2Fuser%2Fsecret%2Ffolder%2F

When you decoded the incoming url you would have a variable with the slashes restored.
Obviously, there are MAJOR security issues with passing a path in the url like this....but it is just illustrative.
More on url encoding: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

Additionally, if you're using variables from the URL they are accessed from the $_GET array. $_REQUEST should be avoided for this as it works its way down the list of $_GET $_POST etc till it finds an occurrence of what you want.

Being able to access: domain.com/?variable=purple as

<?php
echo $variable; //purple

Relies on a feature of php called "register globals" this was defaulted to OFF in php 4.2.0 DO NOT rely on this being enabled. As of php 5.3.0 this is depreciated. You can read all about it here: http://php.net/manual/en/security.globals.php

mschroeder 251 Bestower of Knowledge Team Colleague

Normally I would suggest building it and learning it and making it work because you'll get the most out of it, but email especially html and attachments are one of the things in PHP I'd suggest referring to a library built specifically for it. In the long run you'll save yourself a lot of headaches and many long nights.

I highly suggest you look at something like PHP Mailer (http://phpmailer.worxware.com/index.php?pg=phpmailer) It is a great standalone library that is actively developed and designed specifically for handling these things.

In my experience, delivery rates for mail() can vary person to person, but in all scenarios I've had very few if any problems using SMTP instead. I would suggest you look into the same, also part of php mailers functionality.

mschroeder 251 Bestower of Knowledge Team Colleague

An ampersand will definitely cause problems in the value of a node in XML. So will < and > etc. modify the script to translate those characters to their character references &amp; &gt; etc etc.

Read this:
http://www.xml.com/pub/a/2001/01/31/qanda.html

mschroeder 251 Bestower of Knowledge Team Colleague

What exactly are you trying to get out of the url? Perhaps there is a more efficient way to obtain it. Can you post and example url?

mschroeder 251 Bestower of Knowledge Team Colleague

I'm going to assume you're using PHP 5...this will not work otherwise.

First off here is the test CSV file I used based on what you provided:
(test.csv)

Example name1;3rd July 2010;21:08;Example of a comment 1
Example name2;4th July 2010;22:08;Example of a comment 2
Example name3;4th July 2010;23:08;Example of a comment 3
Example name4;3rd July 2010;19:08;Example of a comment 4

Now my actual solution.

<?php

class SortingIterator implements IteratorAggregate
{

	private $iterator = null;


	public function __construct(Traversable $iterator, $callback)
	{
			if (!is_callable($callback)) {
					throw new InvalidArgumentException('Given callback is not callable!');
			}

			$array = iterator_to_array($iterator);
			usort($array, $callback);
			$this->iterator = new ArrayIterator($array);
	}


	public function getIterator()
	{
			return $this->iterator;
	}
}

function DateSort($a, $b)
{
	$aDateTime = new DateTime($a[1].' '.$a[2]);
	$bDateTime = new DateTime($b[1].' '.$b[2]);
	
	return $aDateTime->getTimestamp() > $bDateTime->getTimestamp();
}


$file = new SplFileObject('test.csv');
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(';');

$it = new SortingIterator($file, 'DateSort');
foreach($it as $line){
	var_dump($line);
}

There are really three parts to this. I use the SplFileObject class from the SPL library to open the csv file and setup the class so it reads it as a csv and uses a semi-colon as the delimiter. (lines 34 - 36)

SplFileObject is an iterator for the lines of a file, basically it means you can do:

foreach($file as $line){
  var_dump($line);
}

and it will spit out info about each line of the file, in this case each is an array as we've told it to read each line as csv.

Then I created a SortingIterator based on (

mschroeder 251 Bestower of Knowledge Team Colleague

Personally I would use the DirectoryIterator SPL object. http://www.php.net/manual/en/class.directoryiterator.php

mschroeder 251 Bestower of Knowledge Team Colleague

You could also override the default session handler, and set it up to instead use a database table to store sessions. A count of the rows in the table will yield your currently active session list.

This also sets you up to be able to use your sessions across multiple servers and gives you the ability to kill all user's logged in sessions for something like maintenance mode etc.

http://www.php.net/manual/en/function.session-set-save-handler.php

mschroeder 251 Bestower of Knowledge Team Colleague

***I apologize this will ONLY work with php > 5.3.0***

Would not a better solution be to use the tools that PHP already provides for doing just this?

$datetime1 = new DateTime($row["ss_datestart"] . " " . $row["ss_timestart"]);
$datetime2 = new DateTime($row["ss_dateend"] . " " . $row["ss_timeend"]);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y years, %M months, %D days, %I minutes, %S seconds');

Few things to pay attention to.

If you need to convert between timezones, that is provide by the second optional parameter to new DateTime().
DateTime (http://www.php.net/manual/en/class.datetime.php) class is available since php 5.2.0

Formatting information can be found here: http://www.php.net/manual/en/dateinterval.format.php

I DID NOT test this code. I believe the input format should be okay but it may need adjusted depending on how it come from the database.

mschroeder 251 Bestower of Knowledge Team Colleague

Can you post an example of the XML and also what you're currently trying to do with the xml? I have done extensive work with XML perhaps I can answer your question.

mschroeder 251 Bestower of Knowledge Team Colleague

just fyi, ereg is depreciated as of 5.3 and will throw a notice. Use the pcre set of functions. http://www.php.net/manual/en/ref.pcre.php

mschroeder 251 Bestower of Knowledge Team Colleague

Personally I like Zend. It is actively developed, built around the bleeding edge features of the language and has constantly been improving.

My biggest issue with CI is that it was built to support PHP4. To my understanding and from what I have read that means it uses some workarounds to effectively do what php5 is natively capable of.

It really comes down to personal preference there are quite a few big name php frameworks and I've seen really spectacular projects built using them all. Download them, read their manuals, and look at their source.

mschroeder 251 Bestower of Knowledge Team Colleague

There is no comparison between OOP and structural php programming in my mind. OOP is composed of most of the concepts and functionality that is "structural" programming. OOP does not magically make your code more maintainable and it does not make it any more organized. A good understanding of the purpose of the application and a good plan will benefit your application far more than choosing one over the other. Most arguments over which is the best way to code, are open ended. Many times it depends on your environment, your hardware, your usage and needs etc. Use the tool that is best suited to the task at hand.

As far as PHP versions, right now I'd say learn under the assumption that you will have full access to 5.2.13. Look at and learn the 5.3 features because that is the future of PHP but its installation base doesn't justify developing specifically for it yet. Besides 5.2 or 5.3 there is no reason to still be supporting PHP4 as it is dead in terms of development and updates.

For references look at the php manual. It is invaluable. http://php.net/manual/en/language.oop5.php

mschroeder 251 Bestower of Knowledge Team Colleague
if( isset($result) && is_array($result) ){
    foreach($result as $page){
      echo $page;
    }
}

that is doing several things in that IF statement. It is making sure the variable $result exsists. It is also making sure that we actually have an array of results.

Currently there is no statement for it execute in the "else" condition. Add something like:

else {
  echo 'No Results';
}

immediately after the closing } of the if statement.

mschroeder 251 Bestower of Knowledge Team Colleague
<html>
<body>
<?php
$search_text = file("search_text.txt");
$search_string = $_POST['search_string'];
 
foreach($search_text as $key => $val) 
{ 
   $data[$key] = explode("||", $val);
}
 
echo 'Search Results for "'.$search_string.'"';
echo "<br><br>";
 
for($k = 0; $k < sizeof($search_text); $k++){
    if (in_array($search_string,array($data[$k][0],$data[$k][1],$data[$k][2],$data[$k][3]))){
        $result[] = '<a href="'.$data[$k][5].'">'.$data[$k][4].'</a><br><br>';
    }
}

if( isset($result) && is_array($result) ){
    foreach($result as $page){
      echo $page;
    }
}
?>
</body>
</html>
mschroeder 251 Bestower of Knowledge Team Colleague

Again a simple typo. There is a reason my signature says the code may not be tested. Both of these errors were well within your ability to find and correct.

Change $results[] to $result[] on line 17.

mschroeder 251 Bestower of Knowledge Team Colleague

typo on my part. change is_isset($result) to isset($result)

mschroeder 251 Bestower of Knowledge Team Colleague
<?php
//Check if $_GET['p'] is set if not return empty string
$action = (isset($_GET['p']) === TRUE? strtolower($_GET['p']) : '');

switch($action){
	case 'submit':
		//Accessed as form.php?p=submit
		//Process the form, save to db, etc.
	break;
	default:
		//Accessed as form.php
		//Display the form or show a homepage
	break;
}

Set your form action to www.mysite.com/form.php?p=submit.
You can add additional case statements to cover additional scenarios. This is the easiest way to do this. You can probably find information on this forum for doing dynamic includes as well.

The other way you can do this is like such:

<?php
//User has submitted the form 
//Process the submission
if( isset($_POST) === TRUE ){
	//Process your form post data
	//Save to database, file etc.

        echo 'Form Saved';
        return;
} 

//User is just viewing the page
//Show them the form

In this scenario the form posts its data to itself, where it is then processed and saved. Instead of "return;" in the IF statement you could also redirect the user elsewhere.

mschroeder 251 Bestower of Knowledge Team Colleague

Having multiple queries where there is a MySQL syntax for this particular use case is pointless. Use the mysql ON DUPLICATE KEY UPDATE syntax and you don't have to worry about conditionally deciding if the record should be inserted or updated, as MySQL does this for you.

$sql = 'INSERT INTO memberst (id, counter) VALUES ('.$_SESSION['id'].', 1) ON DUPLICATE KEY UPDATE counter = counter+1; SELECT * FROM memberst WHERE id = '.$_SESSION['id'].' LIMIT 1;';
$result = mysql_query($sql);
$rowset = mysql_fetch_assoc($result);

That first inserts or updates the record for the user with $_SESSION and then executes the same select statement as I'm assuming you need the data from that table to display somewhere. If not you can remove the "SELECT * FROM......;" from that query string.

mschroeder 251 Bestower of Knowledge Team Colleague

This can be handled with a single query and without all of the conditionals and select queries to determine the current counter value.

INSERT INTO memberst (id, counter) VALUES ('', 1) ON DUPLICATE KEY UPDATE counter = counter+1

If the record exists increment it by 1, if the record does not exist create the record and set its value to 1

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

mschroeder 251 Bestower of Knowledge Team Colleague

I assume you already have a relatively solid understanding of PHP's basics. e.g. Functions, Variables, Includes etc.

Great place to start is the manual.
http://php.net/manual/en/language.oop5.php

Once you feel you have a good understanding of how OOP works in general, I find the SPL (Standard PHP Library) to be extremely useful
http://us2.php.net/manual/en/book.spl.php

From there I'd recommend looking at some common design patterns and getting a feel for strengths and weaknesses
http://www.fluffycat.com/PHP-Design-Patterns/
http://www.ibm.com/developerworks/library/os-php-designptrns/
http://www.ibm.com/developerworks/opensource/library/os-php-designpatterns/

As far as books, I can recommend these three specifically:
http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_11?ie=UTF8&s=books&qid=1273758471&sr=1-11
http://www.amazon.com/PHP-Object-Oriented-Solutions-David-Powers/dp/1430210117/ref=pd_sim_b_1
http://www.amazon.com/Pro-PHP-Patterns-Frameworks-Testing/dp/1590598199/ref=pd_sim_b_2

The problem I found with books is they're usually outdated in some respect by the time they are published.

mschroeder 251 Bestower of Knowledge Team Colleague

You have the single quote inside double quotes you do not need to escape it. Right now the function it looking for \' to replace with &rsquo;

$data=str_replace("&rsquo;","'",$data);
mschroeder 251 Bestower of Knowledge Team Colleague

For chrome check out the "Stylish" extension. https://chrome.google.com/extensions/detail/fjnbnpbmkenffdnngjfgmeleoegfcffe[/URL

It allows you to specify a domain name and then provide custom css. Then its loaded when the site is loaded. Fast from what I've seen too.

mschroeder 251 Bestower of Knowledge Team Colleague

You can not have more than one auto-increment column in the same table in MySQL.

You could however do something like:

/*
  Table
  +-----------+------------+
  | RowId (AI)| RowCount   |
  +-----------+------------+
  | 1         | 37         |
  +-----------+------------+
  | 2         | 51         |
  +-----------+------------+
  | 3         | 26         |
  +-----------+------------+
*/

UPDATE Table SET RowCount = RowCount + 1 WHERE RowId = 1

That query would increment your rowcount by 1 each run.

mschroeder 251 Bestower of Knowledge Team Colleague

You need to ensure you have the right data structure and data types. For example, if you're storing protein sequences, you may go over the 256 character limit of varchar types. Data entered will be truncated. You then need to use one of the text types.

This is no longer true as of mysql 5.0.3

"Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used."
http://dev.mysql.com/doc/refman/5.0/en/char.html

Looking at some basics on how proteins are diagrammed, I can't even begin to think this is possible without a relational structure.

@stefano
Can you elaborate into some more detail on how you think this would best be accomplished in a database? I'm not an expert or even a novice by any means on proteins but after a quick google search it looks like to describe a protein structure you'd need to able to relate data in a 3 dimensional space?

mschroeder 251 Bestower of Knowledge Team Colleague

I'll give it some time, but agree with about 90% of the criticisms posted above. It looks like the site has taken several steps backwards.

Since no one else mentioned it, unless I missed it, has anyone else had this weird chrome glitch? Quite obnoxious when you instantly lose a chunk of viewable space.5.0.375.29 beta/windows vista if it is of any help in solving it.

On the nice side, it looks good on Android's browser especially without the nagging lower tool bar.

mschroeder 251 Bestower of Knowledge Team Colleague

In general that article looks like it touches on most of the basics however I disagree with some of their basic security methods

  • Handle errors gracefully
    No production environment should ever be running with error_reporting enabled. This being disabled will prevent php from displaying errors or returning query issues. That doesn't mean you shouldn't be handling errors gracefully though.
    As much as possible code should be wrapped in try and catch blocks and instead of letting php functions throw their own errors catch them and handle the output in your own manner. e.g. email a site admin or log it to a database, send the user to a 404 page anything as your design requires.
  • Passwords in the user account table of your database must be encrypted (SHA-1)
    This statement is incorrect. Passwords in your database should always be hashed not encrypted. Hashing is designed to be a one-way change. Encryption however is designed to be reversible. SHA-1 is an example of a hashing function.
    Something this article fails to mention is the usage of a salt to add to the complexity of the original string, mostly to control dictionary attacks.
  • Use the "maxlength" option in your HTML form elements
    This isn't worth the time it would take you to type it in. The only place this may be convenient is when you're entering something where you know it is an exact length. e.g. 5 digit zipcode. If your form is going to be …
mschroeder 251 Bestower of Knowledge Team Colleague

you're missing a [ in $_REQUEST"text"] change it to $_REQUEST["text"]

mschroeder 251 Bestower of Knowledge Team Colleague

** With ardav's suggestion **

if (in_array($search_string,array($data[$k][0],$data[$k][1],$data[$k][2],$data[$k][3])))
{
echo '<a href="'.$data[$k][5].'">'.$data[$k][4].'</a>';
echo '<br><br>';
}
else
{
echo "<br><br><br>";
echo "Your search returned 0 results. Please go back and try again.";
}

Change it to something like this:

if (in_array($search_string,array($data[$k][0],$data[$k][1],$data[$k][2],$data[$k][3])))
{
$results[] = '<a href="'.$data[$k][5].'">'.$data[$k][4].'</a><br><br>';
}

After the for loop:

if( is_isset($result) && is_array($result) ){
  foreach($result as $page){
    echo $page;
  }
}

resulting in:

<html>
<body>
<?php
$search_text = file("search_text.txt");
$search_string = $_POST['search_string'];
 
foreach($search_text as $key => $val) 
{ 
   $data[$key] = explode("||", $val);
}
 
echo 'Search Results for "'.$search_string.'"';
echo "<br><br>";
 
for($k = 0; $k < sizeof($search_text); $k++){
    if (in_array($search_string,array($data[$k][0],$data[$k][1],$data[$k][2],$data[$k][3]))){
        $results[] = '<a href="'.$data[$k][5].'">'.$data[$k][4].'</a><br><br>';
    }
}

if( is_isset($result) && is_array($result) ){
    foreach($result as $page){
      echo $page;
    }
}
?>
</body>
</html>
mschroeder 251 Bestower of Knowledge Team Colleague

Your problem is in the IF/ELSE conditional.

Because it is doing a search for each line in the file, it is generating output for each line in the file. Instead of outputting the result or failure in the for loop, assign the result to an array like: $result[] = 'link and title'; Then eliminate the ELSE part of the conditional all together.

after the for loop add a conditional check like

if(isset($result) && is_array($result)){
  echo implode('<br />', $result);
} else {
  echo 'Search returned 0 results';
}
mschroeder 251 Bestower of Knowledge Team Colleague

Does the server you have uploaded your files to have mod_rewrite enabled for apache?

mschroeder 251 Bestower of Knowledge Team Colleague

1. Are you asking about a tutorial for my code or a tutorial for XSL in general? XSL is a w3 standard. Coupled with XPath and XQuery for navigating and making node/attribute selections. You should be able to find a million examples online. I have several books from Wrox on the topic as well.

2. See your PM. There is also a CMS built entirely using xsl. http://symphony-cms.com/ I have never worked with it so I'm not sure how powerful/flexible their setup is.

3. In my template engine that php is actually part of a class. That is just a really simplified snippet of code.

In the sites i've built using xml/xsl I usually use the DOMDocument to create blocks of xml at a modular level which provides a nice hook for being able to cache the final xml without having to regenerate it every time.

In the last year I've moved on to working with the zend framework primarily and haven't done much with xml/xsl but it still one of my favorite methods for templating. If you're familiar with ZF then this might be of interest (http://www.contentwithstyle.co.uk/content/zend-framework-xsl-and-self-serializing-views) I have been meaning to see how well i can integrate the two but haven't had the time lately.

mschroeder 251 Bestower of Knowledge Team Colleague

XML/XSL example

index.php

<?php
/**
 * This script loads the RSS feed (XML) from DaniWeb's PHP Forum
 * It then performs a an XSL Transformation to display it as formatted HTML
 * 
 * @see http://www.daniweb.com/forums/rss17.xml
 */

$doc = new DOMDocument();
$xsl = new XSLTProcessor();

$doc->load('templates/index.xsl');
$xsl->importStyleSheet($doc);

$doc->load('http://www.daniweb.com/forums/rss17.xml');
$html = $xsl->transformToXML($doc);

echo $html;

templates/index.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
	<xsl:template match="/">
		<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<title><xsl:value-of select="rss/channel/title"/></title>
				<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
			</head>
			<body>
				<xsl:for-each select="/rss/channel/item">
					<h2><a href="{link}" ><xsl:value-of select="title"/></a></h2>
					<p>Date: <xsl:value-of select="pubDate"/> </p >
					<p><xsl:value-of select="description"/> </p>
				</xsl:for-each>
			</body>
		</html>
	</xsl:template>
</xsl:stylesheet>

Thats about as simple as it gets.

XSL is extremely powerful once you learn its syntax.
Your output is not limited to just html either, anything that is composed of an XML structure can be created just by changing the template.

Benefit of using XML/XSL to generate HTML is that it forces your output to be valid XML markup. Correct nesting, end tags etc.

mschroeder 251 Bestower of Knowledge Team Colleague

To my understanding, this is exactly how MyISAM and InnoDB both work with slight differences. MyISAM locks the entire table while InnoDB locks a row during an insert/update.

It appears you can manually lock and unlock a table for a query though if necessary.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

Some info on table locking in mysql
http://dev.mysql.com/doc/refman/5.0/en/table-locking.html
Some info on InnoDB locking
http://dev.mysql.com/doc/refman/5.0/en/innodb-lock-modes.html