Mixing php and html

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

Pavilion wrote:The following code snippet was included to redirect users if they are not logged in:

Code: Select all

ob_start(); // output buffering starts here.
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
}
I found this approach with some research. But I'm not quite sure what "output buffering " is and why it is necessary. In my mind the code snippet should check to see if $_SESSION has user_id. If there is no user_id the user should be redirected to login.php. It does work, but is ob_start() necessary?
From the PHP manual:
While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
So there's what it does. Certainly doesn't seem necessary in this case.
Pavilion wrote:

Code: Select all

if (isset($_POST['formsubmitted']))
{ // This tests to make sure form is submitted before error handling. Without this check, error messages will appear on simply opening the page because defaults don't fill in BEFORE script runs.
paired with

Code: Select all

<input type="hidden" name="formsubmitted" value="TRUE" />
I only used this combination because it prevents error messages from displaying BEFORE the input control default values fill in. Is there a better way to stop error messages from prematurely filling in?[
I typically just check if $_POST contains anything.

Code: Select all

if (isset($_POST))
Pavilion wrote:Is it necessary to start a session on every php page? Once a session is started at the login page, is it necessary to start a session on every page afterward?
Yes.
Pavilion wrote:Overall, is there anything you would change with this script?
On the whole it looks good. I would replace the mysql_ functions with their MySQLi equivalents and there's some pretty similar code for parsing desk phone and cell phone that I'd consider wrapping in a function depending how frequently it's going to be used. Definitely a solid first effort, though.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

Pavilion wrote:When I'm successfully logged in and using the profile.php page php is not tracking this as effectively as it should. If I open a new window and put in the profile.php url I am directed to login.php (as if I'm not logged in).

Typically when using a website, the site can tell you're logged in - even if you use a new window. What do I need to do to assure this capability with my site?
That's odd. Sessions should handle that. Try commenting out the redirect code and inserting a var_dump($_SESSION) to help you debug it.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

I typically just check if $_POST contains anything.

Code: Select all

if (isset($_POST))
I just finished trying this. All the error messages filled in when the page opened. So... I put the code back.
On the whole it looks good. I would replace the mysql_ functions with their MySQLi equivalents and there's some pretty similar code for parsing desk phone and cell phone that I'd consider wrapping in a function depending how frequently it's going to be used. Definitely a solid first effort, though.
Firstly, thank you for all of your help and advice. I'm not very good at learning "theory". I need to get in and "do". Just simply working on these files with you has really helped me learn the basics.

About replacing the mysql functions with MySQLi ... because there are multiple affected files - I will have to take the time to figure out the process of converting. Can I just use the same syntax and replace mysql with MySQLi? Or does the syntax of mySQL statements change as well?

Thanks Again:

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

I must have been tired when I wrote that; $_POST is always set. What I actually do is

Code: Select all

if (!empty($_POST))
Sadly, PHP is well-known for its inconsistent syntax, so simply doing a find/replace of mysql_ for mysqli_ won't work. Still, it's worth taking the time to learn mysqli and/or PDO. Both are well documented.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

I must have been tired when I wrote that; $_POST is always set. What I actually do is

Code: Select all

if (!empty($_POST))
OK - that works. Thank you.
Sadly, PHP is well-known for its inconsistent syntax, so simply doing a find/replace of mysql_ for mysqli_ won't work. Still, it's worth taking the time to learn mysqli and/or PDO. Both are well documented
Sigh... one more thing to learn. :|
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

Just use filter_var to check email addresses. Also, please don't hijack threads.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Sadly, PHP is well-known for its inconsistent syntax, so simply doing a find/replace of mysql_ for mysqli_ won't work. Still, it's worth taking the time to learn mysqli and/or PDO. Both are well documented.
Celauran - I got to thinking last night. There are two clients I am learning php for. Both clients want certain capabilities already in their classical database to be available on their websites. Both projects are basic and something I can learn on. And ... both projects will (at some point) become part of a larger, existing website.

It is a pretty good bet that both these websites are NOT using MySQLi. In fact one website in particular is probably drawing its data through MS SQL Server (I'd have to check with their IT folks about this). But my classical databases all have a MS SQL Server foundation. I may use MySQL for the website php application and port data back/forth. But - there is a strong possibility that I will simply be using MS SQL Server views as well. Given this reality, can one mix MS SQL SERVER, MySQL and MySQLi?

Can one mix MySQL and MySQLi?

Thanks Much - Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

If you're going to be using MSSQL and/or other non-MySQL databases, I strongly recommend you familiarize yourself with PDO. The whole point of PDO is to be portable; all you'll really need to change is your DSN. All other code remains the same.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

If you're going to be using MSSQL and/or other non-MySQL databases, I strongly recommend you familiarize yourself with PDO. The whole point of PDO is to be portable; all you'll really need to change is your DSN. All other code remains the same.
OK... I did some quick research. You're right (as always). So... I suppose my next step in this learning process should be to rewrite my php files in PDO?

I think - to do things efficiently - I'll just create a new folder in my FTP directory and start fresh. I can copy/paste appropriate portions of code and rewrite in new files, instead of mucking up existing php files that already work. (Just mussing in my head here). If you've a better approach to rewriting these files, please jump in.

Thanks much:

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

No, I think that's probably the best approach. The PDO manual on php.net is quite good, but mistakes are inevitable. Best to have a working copy around for reference and/or in case you need it.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

No, I think that's probably the best approach. The PDO manual on php.net is quite good, but mistakes are inevitable. Best to have a working copy around for reference and/or in case you need it.
OK - starting from scratch (sigh)...

I created a new directory. My first task is to create the database connection using PDO. Following are links to a few tutorials I found:
Following is my attempt at a connection:

Code: Select all

<?php
//Define Database
$hostname = '#######';
$username = '######';
$password = '#####';
$dbname= '######';

try {
$DBH = // Database Handle
new PDO("mysql:host=$hostname,dbname=$dbname",$username,$password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

And here is the error message I receive
SQLSTATE[HY000] [2005] Unknown MySQL server host '#######,dbname=######' (1)
I copied and pasted the "Define Database" block from my original, WORKING, file.

So... what am I doing wrong with the PDO?

One side note, the PHP Manual has a lot of documentation. But... it is documentation without sufficient explanation for a newbie like myself. I really do try and figure this stuff out with documentation first. But - this PDO turn has me back to the "baby steps" again.

Thank you so much for all your advice and help.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

You're using a comma instead of a semicolon.

Code: Select all

$sql = new PDO('mysql:host=localhost;dbname=foo', 'user', 'password');
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Thanks Celauran:

The connection is now working. After I linked to the database file, I wanted to build a basic query and test different PDO syntax for echoing data. I was successful in getting a foreach{} statement to execute and not so successful in getting a while{} statement to execute. I think the problem with the while{} statement is my attempt at using setFetchMode. Following is my script:

Code: Select all

<?php
// PDO (PHP Data Objects) Syntax used to create link to database and basic queries. Find more syntax help at:
	### http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
	### http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.3

//Define Database
$hostname = '#####';
$username = '#####';
$password = '#####';
$dbname= '######';

// Create PDO link to the database with the following "try" block
try 
{
$link = // Database link
new PDO("mysql:host=$hostname;dbname=$dbname", $dbname, $password);
    /*** echo a message saying we have connected ***/
    echo "Connected to database <br />";
	
	// Now that the connection is established, build some basic queries to test connection

	$user_query = 'select user_id, FName FROM UserTbl';
	$user_data = $link->query($user_query);
    foreach ($user_data as $row)
	{
        echo $row['user_id'] . "\t";
        echo $row['FName'] . "\t";
    }
	// foreach block runs and returns data
	// _____________________________________________________________
	
	echo "<br />";
	echo "<br />";
	echo "Now run fetch and while. <br />";
	
	# setting the fetch mode  
	$user_data->setFetchMode(PDO::FETCH_INTO);	
	while($row = $user_data->fetch())
	{
    echo $row['user_id'] . "\n";
    echo $row['FName'] . "\n";
	}
	// while block runs without error, but does not return data
	// ___________________________________________________________
}
	// This block throws an error message if there is no connection. PDO uses "exceoptions" to handle errors.
	catch(PDOException $e) {
	echo "There is an error somewhere. I have no idea where, but there is an error.";
	
	// The following echo will return php generated message. Use for stepping through an error.
	// echo $e->getMessage();
}	
?>
Any help you can give in directing me is appreciated.

Thanks Much - Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Mixing php and html

Post by Celauran »

Not what you posted about (I'll get to that) but this jumped out at me

Code: Select all

new PDO("mysql:host=$hostname;dbname=$dbname", $dbname, $password);
You've got $dbname where I'd expect to see $username. Could be working if they happen to be the same, but you probably want to correct that.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Good catch Celauran. You are right DB Name and user name are the same. I did correct the mistake though. Thank you for catching it.

Still ... my foreach{} statement is returning results.

And.. my while{} statement is returning null - with now reported errors.

I assume there is something wrong with the way I am using setFetchMode and fetch()??? But can't figure it out.

Pavilion
Post Reply