mschroeder 251 Bestower of Knowledge Team Colleague

It looks like someone created a function that essentially does what mkdir (http://php.net/manual/en/function.mkdir.php) already does with its recursive flag.

mschroeder 251 Bestower of Knowledge Team Colleague

Depends on your definition of a "module" judging by what you've outlined and what ardav also outlined, I would say those are more like the objects that belong in the service level of your application.

Either way, there is no defined list of "must have" functionality. Design your application and decide what should or should not be part of the application. Or provide more of the concept of what you're trying to achieve and I'll be happy to provide you more insight.

PoisonedHeart commented: Thank you for your help! :) +2
mschroeder 251 Bestower of Knowledge Team Colleague

There is nothing php related that can just push files to a user's computer without the user's interaction. The same goes for anything built around javascript and php.

The user would need some kind of client on their pc that could interact with your server and handle the transfer.

mschroeder 251 Bestower of Knowledge Team Colleague

But what about the simplicity of:

<?php foreach( $users as $user): ?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>

There is shorthand syntax for almost, if not, all control structures in php.
If you were to use short php tags, which I will never, advocate you'd get <?=$value?> instead.

But it really is just semantics, if it works for your needs and it is a simple solution than it is a good solution.

As far as xml/xslt/xpath/xquery goes, it is a really powerful set of tools because they are not just relevant to php. In fact most browsers have very good support natively.

The following is simplified from a w3school example.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<catalog>
	<cd>
		<title>Empire Burlesque</title>
		<artist>Bob Dylan</artist>
		<country>USA</country>
		<company>Columbia</company>
		<price>10.90</price>
		<year>1985</year>
	</cd>
</catalog>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <tr>
        <td><xsl:value-of select="catalog/cd/title" /></td>
        <td><xsl:value-of select="catalog/cd/artist" /></td>
      </tr>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

The general idea is that you supply an xml document to an xslt template and the template then pulls its data from the xml.

In PHP the transformation would work something like:

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

$doc->load('/path/to/xsl/template.xsl');
$xsl->importStyleSheet($doc);

//Load XML from string		
$doc->loadXML('xml string...');
$html = $xsl->transformToXML($doc);
		
echo $html;
mschroeder 251 Bestower of Knowledge Team Colleague

This is really the wrong place for a thread like this...

But, since I'm already here, domain names are a dime a dozen in my experience. Prices are usually within a couple bucks of one another. Personally most of my domains are registered through 1and1.com these days. Godaddy has a nice interface but to each their own.

As far as hosting goes, you get what you pay for and anyone who tells you differently is full of it. Stay away from unlimited plans as they tend to be a way for hosts to bring in lots of low budget low resource sites and pack them onto a very oversold server. There is a reason HostGator charges $175/m for a dedicated server with hard limited bandwidth and disk space but only charges $5/m for unlimited hosting...

There are good low-budget hosts though. But use your best judgement. No one is going to sell you terabytes of bandwidth and hundreds of gigabytes of space for a few dollars a month.

I recommend checking out www.webhostingtalk.com if you're looking for a very active community built specifically around the very topic of hosting. It is also a great place to find good deals at very reputable hosting companies.

From personal experience one of the best companies I have ever worked with, both shared and dedicated hosting has to be LiquidWeb (www.liquidweb.com) Their support is absolutely top notch and I've sent them some pretty …

Nick Evan commented: Thank you for helping us fight spam! I also really like your avatar :) +16
mschroeder 251 Bestower of Knowledge Team Colleague

In my opinion the best way to do this would be to name your fields using an array index.

<input name="field[]" type="text" size="20" maxlength="40" />
<input name="field[]" type="text" size="20" maxlength="40" />
<input name="field[]" type="text" size="20" maxlength="40" />

Then when you process the fields with PHP it is as simple as:

<?php
foreach( $_POST['field'] as $field ){
  //Do something with the value of $field.
}

No counter needed, will scale to an infinite size, and $_POST will be a numerically indexed array of values that were submitted so you can iterate over it with any of the array functions etc.

epicrevolt commented: Defninitely a new method. I need to look more into arrays for my projects. +1
mschroeder 251 Bestower of Knowledge Team Colleague

Performance wise, you should avoid loading an entire file into memory when possible.
The following code relies on the SPL (standard php library) which is mostly > php 5.1
Although this can also be done using the file functions in php.

<?php
$email = 'user@domain.com';

$file = new SplFileObject('filename.txt');
$file->setFlags(SplFileObject::DROP_NEW_LINES);

$match = false;
foreach($file as $line){
	if( false !== stripos( $line, $email ) ){
		$match = true;
		break;
	}
}

if( true === $match ){
	//we found a match
} else {
	//No Match
}

This reads through a file while only having a single line in memory at a time.
If/when it finds a match, it sets $match = true, you could implement this however you would like, but then breaks out of the foreach loop to stop from having to check the rest of the file.

If you're using a version of php that supports the SplFileObject you should really check it out. http://php.net/manual/en/class.splfileobject.php

Shankye commented: Thank you for help +1
mschroeder 251 Bestower of Knowledge Team Colleague

[rant]

use sessions to do login and logout pages.. and contact display page only for logged in members..

How does something like this get upvoted?!

-OP you should use PHP to handle your login and logout. <- I expect this to be upvoted as well.
[/rant]

Now in all seriousness, ardav is the only here who has posted anything of any real value.
I agree with both of his suggestions for structuring this, with the exception of:

For contacts = members only:

id [PK, int]
user_id [int]
contact_id [int]

I would drop the id column as a user (user_id) would never be joined to the same contact (contact_id) more than once. So user_id, contact_id would form a composite primary key making the id superfluous.

mschroeder 251 Bestower of Knowledge Team Colleague

I have to agree with richieking here. There are numerous open source e-commerce packages that will probably offer more than you will possibly need. Pick one, learn it, install modules/plugins/etc and/or customize it where necessary.

If you are just learning php and starting out with web development, this is not the kind of project to tackle if you intend to release it to a production environment. Not only is the scope enormous but the amount of technical and security hurdles to overcome will not lend itself well to learning.

mschroeder 251 Bestower of Knowledge Team Colleague

If you had the xdebug php extension installed, which is what I use on my development machine, hence why I use var_dump a lot more than print, you would see that those headers are actually a series of lines separated by newline chars. If you view source on your output you will probably see that the output has newlines in there.

string 'HTTP/1.1 200 OK

Date: Wed, 22 Dec 2010 13:43:24 GMT

Server: Apache/2.2

X-Powered-By: PHP/5.1.6

Set-Cookie: bblastvisit=1293025404; expires=Thu, 22-Dec-2011 13:43:24 GMT; path=/; domain=.daniweb.com

Set-Cookie: bblastactivity=0; expires=Thu, 22-Dec-2011 13:43:24 GMT; path=/; domain=.daniweb.com

Cache-Control: private

Pragma: private

X-UA-Compatible: IE=7

Vary: Accept-Encoding

Content-Type: text/html; charset=utf-8



' (length=430)

So knowing that, you essentially want to get the first line of the request. This can be done with explode, or a substring etc, whatever way you prefer. But you want to parse out the first line "HTTP/1.1 200 OK" for the response code, 200 in this case. Here is a good breakdown of the common ones: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

How you choose to get the response code from that string is up to you, consider regular expressions, exploding it via the spaces, using strpos to find the first space and then taking a substr of that through the next three characters etc.

If you need more help post up what you're attempting and we'll go from there.

mschroeder 251 Bestower of Knowledge Team Colleague

The OP is not generating a pdf...the OP is creating an FDF document and specifying a form fillable pdf that loads with the populated data.

-dangerousdayton
When I have generated xFDF the xml version of fdf, the checkboxes have all been setup as unique fields, e.g. Payment_Visa, Payment_Mastercard, Payment_Amex etc. Then to fill a particular checkbox I would pass it the value of Yes.

When I look at the fillable form, the checkboxes, under the options tab, have the Export Value of 'Yes' without the quotes.

Hope this helps.

mschroeder 251 Bestower of Knowledge Team Colleague

I'm glad my suggestions made sense.

Your current errors are because your are referencing the $_POST superglobal array using lowercase. PHP is case sensitive $_post and $_POST are two different things.

The problem I see, is this is very very basic php. Without an understanding of the basics, you will not know where to look. I think developing a better understanding of that will greatly help you.

For myself, if I were to get an error like that, knowing the basics, I would realize that $_POST, $_GET etc are special variables within php. If I did not know that one of the first things I would do is google for "post, php" and look through and results from php.net first and foremost.

This page comes up as my second result: http://php.net/manual/en/reserved.variables.post.php upon looking at this page you will see that $_POST is ALWAYS referenced in capital letters. If you knew that post was a superglobal in php you might find the manual page for superglobals in php: http://php.net/manual/en/language.variables.superglobals.php

You would also notice that there is NEVER a space between a variable and its array key, again basic php. If you don't know about php arrays refer again to the manual: http://php.net/manual/en/language.types.array.php

Using the information I have provided, what do you think the necessary corrections should be?

imti321 commented: I HAD BEEN A NEW COMMER TO PHP .CAME ACROSS THIS WEBSITE AND FIRST OF ALL THIS PERSON HELPED PROMPTLY AND ACCURATELY .HE IS REALLY A MASTER.I APPRITITATE HIS PROMPT AND ACCURATE HELP +0
mschroeder 251 Bestower of Knowledge Team Colleague

The php parser almost always points you right to the problem. In this case it has directed you to line 7.

I took a quick glimpse and immediately realized the left parenthesis was typo'd with a left curly brace: $connect = mysql_connect {"localhost","root","webdesigning1") or die ("couldnt connect to mysql data base "); This error exists in the original code you posted. If you don't make an effort to understand the problem or in this case, don't even look at the error message you're going to quickly find no one here wants to make an effort either.

Rule of thumb, when you get parse errors, look for mismatched/missing parenthesis, mismatched/missing quotes and missing semi-colons at the end of your lines. These are the most common I see on these forums.

kvprajapati commented: :) { +11
mschroeder 251 Bestower of Knowledge Team Colleague

If your input is always going to be HTML/XML this would be ridiculously easy using SimpleXML and an xpath query:

<?php

$string = <<<XML
<body>  
<img src="page.jpg" border="0" usemap="#fghf"  />
<map name="fghf" id="fghf">
<area shape="rect" coords="10,71,258,236" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="258,72,506,237" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="155,79,150,200" href="#" alt="some_alt" title="some_title" />
<area shape="rect" coords="88,22,400,217" href="#" alt="some_alt" title="some_title" />
</map> 
</body>
XML;

$xml = new SimpleXMLElement( $string );
$results = $xml->xpath('//area/@coords');

foreach($results as $coords){
	echo $coords.PHP_EOL;
}

You can supply the html/xml as a string any way you wish. Then using an xpath query, we find the coords attribute (@coords) of all area elements in the document.

diafol commented: ridiculously easy! +7
mschroeder 251 Bestower of Knowledge Team Colleague

Your use of quotes is incorrect. In php anything wrapped in quotes is a string. If you put a number in quotes single or double it is considered a string. If you specifically want something to be a number, do not wrap it in quotes.

<?php
$a = 5;
$b = '5';

var_dump($a); //integer
var_dump($b); //string

When working with php you have two options for quoting strings, single and double quotes.
With double quotes, php will parse any variables included within the string.

<?php
$color = "blue";
echo "The sky is $color."; //The sky is blue.

With single quotes, php will not parse any variables included within the string.

<?php
$color = 'blue';
echo 'The sky is $color.'; //The sky is $color.
echo 'The sky is '.$color.'.'; //The sky is blue.

There is a slight performance gain, at a very micro level, to using single quotes over double quotes because the interpreter does not have to look for variables. But, the trade-off is you have to use concatenation to handle variables.

Also just a pet peeve, php does not require you to close your php tags. In fact with files that only contain php it is suggested you omit the closing tag to prevent any issues with blank lines following the closing tag.

Zagga commented: Brief, clear examples. Great answer explaining the use of quotes. +1
mschroeder 251 Bestower of Knowledge Team Colleague

http://www.php.net/manual/en/language.operators.comparison.php

Manual page breaks down just about anything you could possibly want to know.

mschroeder 251 Bestower of Knowledge Team Colleague

Using php 5.2.2+ this is a piece of cake.

<?php
$date1 = new DateTime('2010-12-07');
$date2 = new DateTime('2010-12-07');

if( $date1 == $date2 ){
  echo 'Dates are equal.';
}

http://www.php.net/manual/en/datetime.diff.php scroll down to example #2 for some examples.

mschroeder 251 Bestower of Knowledge Team Colleague

If you're using php 5.3+ there are some new classes that make this easier to accomplish.

<?php

//Define out start and end dates
$start = new DateTime('2011-01-01');
$end = new DateTime('2011-02-01');

//Define our holidays
//New Years Day
//Martin Luther King Day
$holidays = array(
	'2011-01-01',
	'2011-01-17',
);

//Create a DatePeriod with date intervals of 1 day between start and end dates
$period = new DatePeriod( $start, new DateInterval( 'P1D' ), $end );

//Holds valid DateTime objects of valid dates
$days = array();

//iterate over the period by day
foreach( $period as $day )
{
        //If the day of the week is not a weekend
	$dayOfWeek = $day->format( 'N' );
	if( $dayOfWeek < 6 ){
                //If the day of the week is not a pre-defined holiday
		$format = $day->format( 'Y-m-d' );
		if( false === in_array( $format, $holidays ) ){
                        //Add the valid day to our days array
                        //This could also just be a counter if that is all that is necessary
			$days[] = $day;
		}
	}
}

var_dump( count( $days ) );

The hardest thing to accomplish outside of php 5.3 will be creating the dates 1 at a time and dealing with month wraps etc. But, it is not impossible. The more advanced and useful solution to this would be to use two Filter Iterators on the the DatePeriod class. http://www.php.net/manual/en/class.filteriterator.php or to extend the DatePeriod class and implement the filters within itself.

PHP > 5.2 Version

Replace

//Create a DatePeriod object using a 1 day …
cereal commented: Great suggestion! +4
mschroeder 251 Bestower of Knowledge Team Colleague

Just a general observation, feel free to ignore the following.

In your table you're using a surrogate primary key, the auto-incrementing column. When you clearly have a natural and practical composite primary key in (book, chapter, verse) as they are always provided and the combination of three digits may not ever repeat.

The glaring issue I see with using a surrogate key in this scenario is that a record can be mistakenly added with duplicate information.

e.g.
ID, Book, Chapter, Verse, Scripture
1, 1, 1, 1, ...
2, 1, 1, 2, ...
3, 1, 1, 1, ...

By eliminating the ID column it becomes impossible to insert the third record with the duplicate information as the composite pk fails.

Book, Chapter, Verse, Scripture
1, 1, 1, ...
1, 1, 2, ...
1, 1, 1, ...

mschroeder 251 Bestower of Knowledge Team Colleague

I agree with everything ardav said.

If you really desire to build a social engine from scratch, define your requirements. Then you will need to spend a lot of time with domain modeling and data storage design before you even start writing code. You could hack and patch it together as you go, but updating it or making changes once you have deployed it will become a nightmare or impossible.

Model the interactions that occur and the objects that exist in your system. Based around those models design a database/datastore that best suites your current design. Don't just think about databases as SQL there are a lot of NoSQL engines that will make your life easier in certain aspects, Couch and Mongo being two popular ones,(http://en.wikipedia.org/wiki/NoSQL). Use existing systems, these don't have to be social networks, to gather ideas about how the system should be structured and how the pieces interact with one another.

Once you have a domain model that fulfills your requirements start building the system around your individual models. Domain Modeling and OOP Design go very hand in hand. If done correctly and to a good degree of detail your end result will be essentially a map that guides your development.

If you are building from scratch, use version control and develop good unit testing habits. The more you test the easier it will be to expand or refactor things as new requirements develop.

This is the 60K foot view, …

diafol commented: Phew! That's some mean analysis MS. Like it. +7
mschroeder 251 Bestower of Knowledge Team Colleague

@Full Spectrum
Its not an untyped language it is a loosely typed language. You can cast values to a particular type and do type comparisons if you want/need too.

@benjaminFowl87
Unit testing is a very powerful mechanism for development, but in my experience it is a different mindset than just sitting down and writing code. Generally you see unit testing talked about with TDD (Test Driven Development). In other words, you design your functionality, write a failing test, write code to pass the test and finally refactor the code to a certain standard level.

Unit testing really shines when you have a system that is heavily tested and then you are tasked with making changes to already existing classes/functions throughout the existing system. Because your tests all pass to start, you write new failing tests and then implement the code necessary to pass those tests. As long as your original tests still pass and your new tests pass, then you have added your additional functionality without breaking any existing code.

Where as without testing, its next to impossible to know for sure that everywhere that piece of code is used is still functional until a bug or issue is found.

Just my $0.02 hope it helps.

mschroeder 251 Bestower of Knowledge Team Colleague

This to me sounds like something best handled by the database using a trigger.

Questions (Table):

QuestionId   int
  Question     varchar
  Answer       varchar
  DateActive   datetime
  Value        tinyint    default 100

QuestionUserAnswers (Table):

QuestionId   int
  UserId       int
  Answer       varchar
  Score        tinyint  (min 50, max 100)

With your trigger being something like this:

CREATE TRIGGER Trig_QuestionScore AFTER INSERT ON Questions
  FOR EACH ROW BEGIN
	IF Questions.`Value` > 50 THEN 
		UPDATE Questions SET Questions.`Value` = Questions.`Value` - 5;
	END IF
  END;

**This is NOT tested so use it just for the general concept.
But what you would do is when the user gets the question right, you would insert a record into the QuestionUserAnswers table. AFTER that insert occurs the trigger would fire automatically and look at the Questions table and subtract 5 from the Questions value unless the value was already at 50.

This only works on mysql > 5.0.2
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html
http://dev.mysql.com/doc/refman/5.0/en/stored-program-restrictions.html

diafol commented: show off! +7
mschroeder 251 Bestower of Knowledge Team Colleague

It sounds like you're trying to read through a file line by line and then use the value of that line to perform a query.

Personally I prefer the SplFileObject assuming you're using php > 5.1.0

<?php
//Create SplFileObject instance of $filename
$file = new SplFileObject($filename);

//Set the drop new line flag so returned line value does not include \n etc.
$file->setFlags(SplFileObject::DROP_NEW_LINE);

//Foreach line in the file execute a query
foreach ($file as $line) {
    mysql_query($line);
}
mschroeder 251 Bestower of Knowledge Team Colleague

Can you please describe your use case a little more so we have a better idea of what you are trying to accomplish?

You can read through a file line by line using fgets, but if you are trying to detect if a character is an end of line character, which varies (\n \r\n etc.), you would use something like fseek to progress the file pointer 1 character at a time and fread to capture the next byte and test it for being an EOL character.

vedro-compota commented: +++++++++++ +1
mschroeder 251 Bestower of Knowledge Team Colleague

In my opinion there are several reasons to use thumbnails over full sized images.

For starters the web is fast and your connection might be fast but there are still plenty of people who do not have fast connections.

Second, since in a default state browsers only allow you to load a few requests in parallel. So unless you're serving your images from multiple sub-domains one long loading image can holdup the entire page load.

Third, if you're loading a bunch of large images you're consuming bandwidth for each page load. Potentially a lot of bandwidth for each page load when a user may only look at a page of thumbnails and close it.

Fourth, even for thousands of images it takes minutes to create thumbnails, there are desktop apps, command line tools, and even php that can automate the process.

Just my $0.02

mschroeder 251 Bestower of Knowledge Team Colleague

Edit: The problem is that you don't have the img tag wrapped with an a tag.

echo '<td><a class="mylink" href="http://',$row['website'],'">',$row['website'],'</a></td>';
echo '<td><a class="mylink" href="http://',$row['website'],'"><img width="75" src="',$row['url'],'"/></a></td>';
Kniggles commented: thanks. +1
mschroeder 251 Bestower of Knowledge Team Colleague
echo "<td><a class=\"mylink\" 'http://' href=\"http://" . $row['website'] . "\">" . $row['website'] . "</a></td>";
 
echo "<td><img width = '75' src=". $row['url'] . " /></td>";

For starters if you're going to be echoing HTML, single quotes will make your life much easier. You also have an unnecessary 'http://' in between your class and href attributes.

echo '<td><a class="mylink" href="http://',$row['website'],'">',$row['website'],'</a></td>';
echo '<td><img width="75" src="',$row['url'],'"/></td>';

Also unless you absolutely NEED to append the strings together, passing multiple strings and delimiting them with a comma will speed things up. This only works with echo and not print.

diafol commented: I didn't know the comma trick. Thanks +7
mschroeder 251 Bestower of Knowledge Team Colleague

with the exception that http:// could be repeated multiple times within the url. in which case that would fail. It all depends on the use case. $url = 'http://www.site.com/url.php?url=http://www.google.com'; You would also probably want to use str_ireplace as the user supplied url could very well be Http:// HTTP:// hTtP:// etc.

diafol commented: good points +7
mschroeder 251 Bestower of Knowledge Team Colleague

There are a lot of different ways to attack this: http://refactormycode.com/codes/598-remove-http-from-url-string has a whole variety of them. Some are good some are bad, my suggestion is to avoid regular expressions unless they're absolutely necessary.

<?php
/*
E.g:
$s = 'http://google.com';
echo remove_http($s);
output: google.com
*/

function remove_http($url = '')
{
    array('http://', 'https://');
    foreach ($list as $word)
        if (strncasecmp($url, $word, strlen($word)) == 0)
            return substr($url, strlen($word));
    return $url;
}

Would probably be my choice from that link for how to do this accurately.
Your images are not clickable because there are no links around them.
They would need to be something like:

echo "<td><a href="someurl.com"><img width = '75' src='http://". $row['url'] . "' /></a></td>";
Kniggles commented: wow nice link :) thanks. +1
mschroeder 251 Bestower of Knowledge Team Colleague
<?php

<form action="ScoreCardAlpha.php" method="post">

A: <input type="text" name="$X" />

B: <input type="text" name="$Z" />

C: <input type="text" name="$W" />

// read input data on $W , $X or $Z has http// if so save after //

if(!filter_has_var(INPUT_post, "$X"))
 {
// if true
	**** deleate all char upto and including // then post to "$X"  ****
 echo("Input has been adapted and saved");
 }
else
 {
// if false
	**** post to "$X" ****
 echo("Input did not need adapting and has been saved");
 }

<input type="submit" />
?>

Maybe I am missing something, but I don't see how the code you provided can even execute. You should get a parse error as soon as it gets to the "<" in <form action="ScoreCardAlpha.php" method="post">

mschroeder 251 Bestower of Knowledge Team Colleague

just add another condition to the query then.

UPDATE table SET column = 'finish' WHERE STR_TO_DATE( date, '%m/%d/%Y' )= CUR_DATE() AND column = 'approve'
aizel commented: nicely done +1
mschroeder 251 Bestower of Knowledge Team Colleague

If I follow correctly, when the user selects a month from the drop down, a two digit representation of the month is passed to the script. 01, 02, 03, etc. and you wish to then pull anything departing in that month.

You can do this relatively easily in SQL using something like this:

SELECT * FROM table WHERE MONTH( STR_TO_DATE(departure, '%m/%d/%Y') ) = 10

Where 10 is the integer value of the month supplied but the form. Beware that this is going to pull anything with month = 10 for ANY year.

***I assume you're departure column is stored as a string and is not using the DATE column type. Since it is not a supported MySQL date representation.

mschroeder 251 Bestower of Knowledge Team Colleague

You have another option if you want to still use heredoc:

<?php
$author = "Anon";
echo 
$str = <<<_END
First Lines
Second Line.
Third Line.
- Written by $author.
_END;

echo nl2br($str);
?>

nl2br inserts <br /> tags before any new line characters in the string.

mschroeder 251 Bestower of Knowledge Team Colleague

Thats because newline characters are not the same as <br />. They are also not displayed on the output of the browser.

If you view the source of that output you will see that the text is actually on multiple lines.

mschroeder 251 Bestower of Knowledge Team Colleague

Short tags can definitely be disabled, however they are enabled by default.

If they are disabled, there are ways to use a stream wrapper to replace <?= to <?php echo on the the fly, but its merely a workaround.

RTM

mschroeder 251 Bestower of Knowledge Team Colleague

Unless you're familiar with configuring php and apache skip all of the trouble and download WAMP or XAMPP

There are others like this as well. They will install everything you need to get a fully functional php, apache and mysql environment in windows.

WAMP seems to have gone stale lately, but there is a community released version with all the latest and greatest link from their forums: http://sourceforge.net/projects/unofficialwamp2/files/

CAUTION: These installers are not designed to be used for live websites. They are really intended to speedup the setup of a development environment.

qazplm114477 commented: very nice and detailed explaination +1
mschroeder 251 Bestower of Knowledge Team Colleague

-Marais

Personally I like PDO because the code is portable across all databases that PDO supports. There is more info on PDO prepared statements: http://www.php.net/manual/en/pdo.prepare.php

<?php

/**
 * Takes a user's credentials and queries the database to ensure the user is
 * a valid user and is allowed to access our system.
 *
 * @param PDO $dbh
 * @param string $usr
 * @param string $pass
 */
function login( PDO $dbh, $usr, $pass) {
	$sql = "SELECT * FROM users WHERE usrNAME = :user AND usrPASS = :pass";
	$sth = $dbh->prepare( $sql );
	$sth->execute( array(':user' => $usr, ':pass' => $pass));
	
	$rowset = $sth->fetchAll();
	if( count($rowset) == 1 ){
		// Logged in
	} else {
		// Not logged in
	}
}

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

login($dbh, $_POST['username'], $_POST['password']);

If you don't have PDO available to you, you can also use MySQLi which also supports prepared statements: http://www.php.net/manual/en/mysqli.prepare.php It uses a very similar syntax too.

I hope this helps, I'm more than happy to expand on it as necessary.

mschroeder 251 Bestower of Knowledge Team Colleague

I know this has been solved but I see some misconceptions that need to be clarified. I have developed with Zend for the last 2+ years. I develop almost purely on Zend these days and have several relatively large applications running on it.

------

I'm sort of messing around with frameworks myself. In fact, because of that, it's led me to a whole slew of new things I'd not done before. Firstoff, you should be comfortable with object oriented programming, because frameworks are almost all OOP.
Agreed

Secondly, I've messed with Zend and Code Igniter so far. If you aren't familiar with a command line or do not have access to one from whatever server you are using - I would stay away from Zend.
If you're referencing Zend_Tool then you're quite mistaken that you MUST use a command line. I create my code from scratch usually. The structures are well defined and you create everything as you would any other php file.

I got zend installed and working ok, but it's really, really deep. I googled good frameworks for beginners and Code Igniter kept popping up, so I tried my luck at that. It's far smaller and no command line is needed to use it. It's also far more portable than Zend seems to be.
To get either working and configured is a breeze. As for being portable, I fail to see why you came to the conclusion it is not portable. …

qazplm114477 commented: great advice +1
mschroeder 251 Bestower of Knowledge Team Colleague

For new code, strtotime really should be avoided. While we are a considerable amount of time away from Y2k38 and I really don't think you would run into an issue, if your script would ever need to process a date after 2038, maybe like the end date of a 30yr mortgage or something, strtotime will fail. This has been addressed in the DateTime object built into PHP since 5.2.

Now I hope you're working on a version of php > 5.2 as there really is no reason to be on anything less.

$date = new DateTime("{$startdate} {$starthour}:{$startmin}");
$date->modify("+{$hour} hours +{$minute} minutes");
echo $date->format('Y-m-d H:i:s');
pietpiraat commented: good explanation, great code +1
mschroeder 251 Bestower of Knowledge Team Colleague

PDFTK (http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/) could solve most if not all of your difficulty. The only caveat being its a command line utility so you have to interact with it in that fashion. Which would also require server access to install it.

it sounds like your solution would be rather simple though, start with a single pdf file that represents each section of the order form. User selects which sections they need and that in turn is passed to pdftk which takes the files for only those sections, merges them down into a single temporary pdf and then pushes that pdf to the user's browser with a header, or even takes the user to a page that has an embedded pdf control and they can save the pdf or print it from there.

raphie commented: Is a good solution, if you have access to the server! +1
mschroeder 251 Bestower of Knowledge Team Colleague

There are a lot of very informative threads on this topic on this very forum. But I'll elaborate on my previous statement.

Hashing is not encryption. SHA1 and MD5 are hashing algorithms. You pass them data and they generate a unique hash from that data. There is no magic function that turns the hashed value back into your data. However, MD5 has proven to be an ineffective hashing algorithm for quite some time, due to collisions e.g. two unique strings that generate the same hash. There have also been breakdowns in the SHA1 algorithm to my understanding. Both of those algorithms should be avoided in my opinion in lieu of better algorithms such as sha-256, sha-512, whirlpool etc.

Salting a hash means to append or prepend (or both) some form of trivial data to make the hash more complex. So lets say our salt is 'a1b2c3d4f5' and our user chooses the password of 'test'. When you hash just the password of 'test' => (a94a8fe5ccb19ba61c4c0873d391e987982fbbd3), you've created a hash that probably exists in a rainbow table (a database of strings and their hashes) because the hashed string is so common. If you append or prepend the salt to it. The string that gets hashed is now: 'a1b2c3d4f5testa1b2c3d4f5' => (c297373704eebdd3154872d23a7eb1a27f751e99). So our 4 character string is now a 24 character string of mostly gibberish. Essentially if your database was compromised the theory is by salting your hash with nonsense you've created a more secure hash that an attacker won't be …

andydeans commented: brilliant +2
mschroeder 251 Bestower of Knowledge Team Colleague
$row = mysql_fetch_array( $result );

after that line, add:

print_r($row);

this will probably make a mess out of the table layout, but paste the output from that function here. That should indicate whether the problem is in the row array or not.

Output should be something like:

Array
(
    [tradeID] => xxxx
    [Date] => xxxxx
    [teamA] => xxxx
    ....
)
ceeandcee commented: Thank you! +1
mschroeder 251 Bestower of Knowledge Team Colleague

how could it display php tags? its a scripting language and when you echo it it automatically executed.
Post your exact output if issue is still not solved.

-vib
That is not true. When you use something like file_get_content() it does not parse/execute what it reads in. If you included the file then yes it would execute any php in that file.

-Gigs
This appears to me like you're trying to use it for some kind of template system? Where your output has a series of echo statements and you've already set some variables that should be replaced.

ob_start();
include ('lol.php');
$content = ob_get_contents();
ob_end_clean();

echo $content;

That code will include lol.php which will execute any php statements within it and then capture the content to a variable which you can then use at a later time. Is this more what you're trying to accomplish?

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
<?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

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

I believe what you're looking for is something like the following

RewriteRule !\.(js|ico|gif|jpg|png|css)$ /index.php

Where any request which is not for a file of those types is routed to index.php (You would need to add pdf to that)

But I think a better solution would be to use something like the Zend Framework does:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Which basically says if the requested file is not a directory, file (with size) or symbolic link, rewrite it to index.php.

mschroeder 251 Bestower of Knowledge Team Colleague

This is not an IE issue.
Get yourself Firebug for Firefox and the IE Developer Toolbar for IE7 -- maybe 6 and 8?

When I run through the example on firefox it is not removing the li tags from the list when i deselect a tag, just the input and the label.

Firefox is leaving the empty li tags and not displaying them or hiding them or something I assume it is your css. On IE7 the EXACT same behavior is occurring except IE7 is leaving the li's in their default state (expanded/not hidden?).

Both browsers show like this once i have removed items that i previously selected.

<ul class="selected">
<li> </li>
<li> </li>
</ul>
pritaeas commented: Useful comment, confirms my suspicion +4
mschroeder 251 Bestower of Knowledge Team Colleague

if you're making the form submit to itself then you need to make the index action in the index controller look for post data so it knows it needs to validate the form.

<?php

class IndexController extends Zend_Controller_Action
{
  public function indexAction()
  {
    $form = new Default_Form_Index();
    $request = $this->getRequest();

    //Check if we have post data
    if( $request->isPost() )
    {
      //If the form is NOT valid redisplay it with errors
      if( !$form->isValid($request->getPost() ) )
      {
        $this->view->form = $form;				           		
        return;
      }

      //Form passes validation and filtering
      //Do something with the data.
      $data = $form->getValues();

      //Maybe a redirect or change what view is getting rendered?

      //Just to stop execution after processing the form return;
      //return; 
    }

    //If no post data assume we're just displaying the form to the user
    $this->view->form = $form;
  }
}
mschroeder 251 Bestower of Knowledge Team Colleague

I'm not sure if there will be a reliable alternative for the time being.
This is due to the Y2K38 problem. http://en.wikipedia.org/wiki/Year_2038_problem

nav33n commented: Wow! I never knew about Y2K38 problem! Thanks for the link. +10