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 »

When you're setting fetch mode to PDO::FETCH_INTO, a second parameter containing the object you want to fetch into is required.

Also, your foreach loop already iterated over the entire result set, so your while statement will evaluate to false on the first pass. If you want to iterate over the same result set more than once, consider using fetchAll().
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Thanks Celauran:

In effort to separate my foreach{} and while{} blocks, I created two separate files. Now both the foreach{} and while{} blocks are functioning. With the while{} I am using PDO::FETCH_ASSOC, instead of FETCH_INTO. To be honest I could not figure out how to create the needed object. We can come back to that later. Right now I'm just trying to get the basics down. Following are my two php files.

foreach.php

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", $username, $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);
	
	echo "<table border='1'>
	<tr>
	<th>User ID</th>
	<th>First Name</th>
	</tr>";
	
    foreach ($user_data as $row)
	{
        $userid = $row['user_id'] . "\t";
        $fname = $row['FName'] . "\t";
		echo "<tr>";
		echo "<td>" . $userid . "</td>";
		echo "<td>" . $fname . "</td>";
		echo "</tr>";
    }
	
	echo "</table>";
	// foreach block runs and returns 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();
}
?>
while.php

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
	### http://www.ilia.ws/files/quebec_PDO.pdf

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

// Create PDO link to the database with the following "try" block
try 
{
// database link
$link = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $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);
		while($row = $user_data->fetch(PDO::FETCH_ASSOC))
		{
		echo $row['user_id'] . " - " . $row['FName'] . "<br />" ;
		}
}
	
	// 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();
}	
?>
Both files work and return data. But... here is my immediate problem. What is the syntax for an include statement in PDO? When I separated the files for more efficiency, I figured I'd simply "include" the db_connect.php file for the database connection. But... all I got was error messages.

So... I'm assuming PDO has a different syntax for including one php file within another?

Thanks - 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 »

Include has nothing to do with PDO and should work fine. How have you separated out the files?
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Celauran wrote:Include has nothing to do with PDO and should work fine. How have you separated out the files?
Yes - my files are separate.
.....

OK ... I've got it working now... I just needed to restructure the path. I'm going to take a break and work on moving the example queries and while statements into actual files later. Thanks so much for your help.

Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

And onto register.php...

My thought process was to copy register.php MySQL statements to a new file and get them working first. Once I was sure the PDO script was working, I'd copy it back into register.php - and all should run smoothly. At least that was my thinking.... :wink:

But things rarely go as planned.

The isolated PDO sql statements are in the PDO_reg.php file. This file operates. It both returns a message when there is a duplicate email address, and inserts proper data when the email address is not a duplicate. The script follows:

Code: Select all

<?php
// This file is adapted from registration script found at: http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';
	
$errors = array();

	$email = 'mickey@gmail.com';
	
	$query = "SELECT COUNT(EmailAddress) FROM UserTbl WHERE EmailAddress = '{$email}'"; // Checking for duplicate email address....

	if ($result = $link->query($query)) {

    /* Check the number of rows that match the SELECT statement */
    if ($result->fetchColumn() > 0) {
		$errors = "That email address is already in use.";
		echo $errors;
    }
}
try 
{
	$fname = 'Mickey';
	$lname = 'Mouse';
	$hash = '12;lasdoiuowejslda';
	$firstcontact = date("Y-m-d");
	$activation = 'a;sd;ou203923sd';

	$insert = "INSERT INTO UserTbl (FName, LName, EmailAddress, Password, 1stContact, Activation) VALUES (:fname, :lname, :email, :hash, :firstcontact, :activation)";

	$q = $link->prepare($insert);  

	$q->execute(array(':fname'=>$fname,  
		':lname'=>$lname,
		':email'=>$email,
		':hash'=>$hash,
		':firstcontact'=>$firstcontact,
		':activation'=>$activation,
	));
	echo "INSERT should have worked. Check your table.";
}
	// This block throws an error message if something goes wrong. 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. <br />";
	
	// The following echo will return php generated message. Use for stepping through an error.
	echo $e->getMessage();
}
?>
But... when I try to paste the above statement into register.php (and clean it up to work with "real" variables and in the "real" file) the script is returning errors. Following is register.php (as it stands now):

Code: Select all

<?php
// This file is adapted from registration script found at: http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/

session_start();

// Check to see if the user is already logged in. If so... send user to profile.php.
if(isset($_SESSION['user_id'])){
header("Location: profile.php");

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';

// including PasswordHash file for purposes of hashing passwords.
require '../PasswordHash.php';

}
// ___________________________________________________________________________________________________________//
// Error handling routine. 
$errors = array(); //Declare an Array to store any error message. As php process the following "if" statement, true results are added to the $errors array.
if (!empty($_POST))  // If NOT empty $_POST - exclamation point is "not" in php.
{
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    else
    {
        $email = mysql_real_escape_string($_POST['email']);

		// Run SELECT query to check for a duplicate email address.
		// This SELECT block is PDO Compliant.
		$query = "SELECT COUNT(EmailAddress) FROM UserTbl WHERE EmailAddress = '{$email}'"; // Checking for duplicate email address....
		if ($result = $link->query($query)) {

		// Check the number of rows that match the SELECT statement. If there is a match, send message to user that the email address is already registered.
		if ($result->fetchColumn() > 0) {
			$errors['email'] = "That email address is already in use.";
		}
		}
    }

    if (!$_POST['fname']) // If NOT $_POST - again exclamation point is "not" in php.
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
	}
	else
	{
		if ($_POST['password'] != $_POST['password2']) // This block of code checks for non-matching password submissions. If there is no match an error message is thrown. This "if" block is separate from the main "if" block checking for other empty fields, and invalid email addresses, because detecting non-matching password submissions has nothing to do with the function of the preceding "if" block.
		{
			$errors['password2'] = "Passwords do not match.";
		}
    }
	if (!$_POST['password'])
	{
        $errors['password'] = "Password cannot be empty.";
	}
}

// Error handling is complete. Now declare variables from $_POST data, Hash password and assign variable, run insert statement and send email to user.
// ___________________________________________________________________________________________________________//

if (!empty($_POST) && empty($errors)) // if NOT "!" empty $_POST and is empty $errors then proceed.
{
    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));
    $password = mysql_real_escape_string(trim($_POST['password']));
	$firstcontact = date("Y-m-d");
	
	// Now hash the $password before inserting into UserTbl
	$t_hasher = new PasswordHash(8, FALSE);

	$hash = $t_hasher->HashPassword($password);
	unset($hasher);
	
	// Create a unique  activation code:
	$timestamp = date(timestamp);
	$activation = md5($timestamp . rand(100000, 999999));
	
	### NEW Script

	try 
	{
		$insert = "INSERT INTO UserTbl (FName, LName, EmailAddress, Password, 1stContact, Activation) VALUES (:fname, :lname, :email, :hash, :firstcontact, :activation)";
		$q = $link->prepare($insert);  
		$q->execute(array(':fname'=>$fname,  
              ':lname'=>$lname,
			  ':email'=>$email,
			  ':hash'=>$hash,
			  ':firstcontact'=>$firstcontact,
			  ':activation'=>$activation,
			  ));  
			
		//Send Confirmation email. Following are the variables for the email 
		$sendto = $email; // this is the email address collected from the form 
		$subject = "Email Confirmation"; // Subject 
		$message = "Thank you for registering. To activate your account, please click this link: http://www.wearethedemocracy.com/schedule/activate.php?email=" . urlencode($email) . "&key=$activation";
		$header = "From: auto-confirm@yourdomain.com\r\n"; 
		$header .= "Reply-to: you@yourdomain.com\r\n"; 
		// Collect variables from above and insert into the mail() function. 
		mail($sendto, $subject, $message, $header);
	
		$confirmation = 'Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account.';
	}
		// This block throws an error message if something goes wrong. PDO uses "exceoptions" to handle errors.
		catch(PDOException $e)
		{
		echo "For some reason your record was not added to the database. <br />";
	
		// The following echo will return php generated message. Use for stepping through an error.
		/// echo $e->getMessage();
		}	

		### NEW SCRIPT	

}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Contact Form</title>
        <link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
    </head>
    <body>
	<div class="shadow"><div class="header"></div></div>
        <div class="shadow">
        <?php
        include '../schedule/include/menu.php';
        ?>
        </div>
	<h1>Register Here ....</h1>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
			<fieldset id="standardForm">
				<div id="standFormLeft">               
					<label>First Name</label>
                    <input tabindex="1" type="text" name="fname" /><br />
					<label>Last Name</label>
                    <input tabindex="2" type="text" name="lname" /><br />
					<label>Email Address</label>
                    <input tabindex="3" type="email" name="email" /><br />
				</div>
                <div id="standFormRight">
                    <label>Password</label>
                    <input tabindex="4" type="password" name="password" /><br />
                    <label>Verify Password</label>
                    <input tabindex="5" type="password" name="password2" /><br />
					<input tabindex="6" type="submit" value="Submit" />
                </div>
                <?php if (!empty($errors)): ?>
                <p class="error">The following errors were detected:</p>
                <ul class="error">
                    <?php if (isset($errors['fname'])): ?>
                        <li><?php echo $errors['fname']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['password'])):
                       ?>
                        <li><?php echo $errors['password']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['lname'])): ?>
                        <li><?php echo $errors['lname']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['password2'])): ?>
                        <li><?php echo $errors['password2']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['email'])): ?>
                        <li><?php echo $errors['email']; ?></li>
                    <?php endif; ?>
                </ul>
                <?php endif; ?>
			</fieldset>
        </form>
        <?php if (isset($confirmation)): ?>
        <p class="borderbx"><?php echo $confirmation; ?></p>
        <?php endif; ?>
    </body>
</html>
The error messages thrown by register.php follow:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/38/7901938/html/tfm/register.php on line 29

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/content/38/7901938/html/tfm/register.php on line 29

Fatal error: Call to a member function query() on a non-object in /home/content/38/7901938/html/tfm/register.php on line 34
Line 29:

Code: Select all

$email = mysql_real_escape_string($_POST['email']);
Line 43:

Code: Select all

if ($result = $link->query($query)) {
Celauran - I feel like I'm right back at square one, and am sorry for coming back to you so often. But... I really am back at the "baby step" level again.

Thanks Much:

Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Dalinggirl wrote:Hello,everybody.I'm new here.If you want to make friends to me ,just contact me.
Hello Everybody... say hello to the new troll - advertising her site.
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 don't use mysql_real_escape_string with PDO. Also, as you're using prepared statements, you don't need to worry about escaping your data. The second error I'm not seeing immediately. Try var_dump($link).
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Celauran wrote:You don't use mysql_real_escape_string with PDO. Also, as you're using prepared statements, you don't need to worry about escaping your data. The second error I'm not seeing immediately. Try var_dump($link).
Hello Celauran:

Yes - I've figured out the escape string is not necessary and that I should be preparing my statements. Following is my newest attempt (and it is NOT working). Sigh....

Code: Select all

<?php
// This file is adapted from registration script found at: http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/

session_start();

// Check to see if the user is already logged in. If so... send user to profile.php.
if(isset($_SESSION['user_id'])){
header("Location: profile.php");

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';

// including PasswordHash file for purposes of hashing passwords.
require '../PasswordHash.php';

}
// ___________________________________________________________________________________________________________//
// Error handling routine. 
$errors = array(); //Declare an Array to store any error message. As php process the following "if" statement, true results are added to the $errors array.
if (!empty($_POST))  // If NOT empty $_POST - exclamation point is "not" in php.
{
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    else
    {

		// Run SELECT query to check for a duplicate email address.

		$query = 'SELECT COUNT(EmailAddress) FROM UserTbl WHERE EmailAddress = ?;'; // Checking for duplicate email address....
		$prep = $link->pdo->prepare($query);
		$prep->execute(array($_POST['email']));
		
		if ($result = $link->query($query)) {

		// Check the number of rows that match the SELECT statement. If there is a match, send message to user that the email address is already registered.
		if ($result->fetchColumn() > 0) {
			$errors['email'] = "That email address is already in use.";
		}
		}
    }

    if (!$_POST['fname']) // If NOT $_POST - again exclamation point is "not" in php.
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
	}
	else
	{
		if ($_POST['password'] != $_POST['password2']) // This block of code checks for non-matching password submissions. If there is no match an error message is thrown. This "if" block is separate from the main "if" block checking for other empty fields, and invalid email addresses, because detecting non-matching password submissions has nothing to do with the function of the preceding "if" block.
		{
			$errors['password2'] = "Passwords do not match.";
		}
    }
	if (!$_POST['password'])
	{
        $errors['password'] = "Password cannot be empty.";
	}
}

// Error handling is complete. Now declare variables from $_POST data, Hash password and assign variable, run insert statement and send email to user.
// ___________________________________________________________________________________________________________//

if (!empty($_POST) && empty($errors)) // if NOT "!" empty $_POST and is empty $errors then proceed.
{
    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));
    $password = mysql_real_escape_string(trim($_POST['password']));
	$firstcontact = date("Y-m-d");
	
	// Now hash the $password before inserting into UserTbl
	$t_hasher = new PasswordHash(8, FALSE);

	$hash = $t_hasher->HashPassword($password);
	unset($hasher);
	
	// Create a unique  activation code:
	$timestamp = date(timestamp);
	$activation = md5($timestamp . rand(100000, 999999));
	
	### NEW Script

	try 
	{
		$insert = "INSERT INTO UserTbl (FName, LName, EmailAddress, Password, 1stContact, Activation) VALUES (:fname, :lname, :email, :hash, :firstcontact, :activation)";
		$q = $link->prepare($insert);  
		$q->execute(array(':fname'=>$fname,  
              ':lname'=>$lname,
			  ':email'=>$email,
			  ':hash'=>$hash,
			  ':firstcontact'=>$firstcontact,
			  ':activation'=>$activation,
			  ));  
			
		//Send Confirmation email. Following are the variables for the email 
		$sendto = $email; // this is the email address collected from the form 
		$subject = "Email Confirmation"; // Subject 
		$message = "Thank you for registering. To activate your account, please click this link: http://www.wearethedemocracy.com/schedule/activate.php?email=" . urlencode($email) . "&key=$activation";
		$header = "From: auto-confirm@yourdomain.com\r\n"; 
		$header .= "Reply-to: you@yourdomain.com\r\n"; 
		// Collect variables from above and insert into the mail() function. 
		mail($sendto, $subject, $message, $header);
	
		$confirmation = 'Thank you for registering! A confirmation email has been sent to ' . $email . ' Please click on the Activation Link to Activate your account.';
	}
		// This block throws an error message if something goes wrong. PDO uses "exceoptions" to handle errors.
		catch(PDOException $e)
		{
		echo "For some reason your record was not added to the database. <br />";
	
		// The following echo will return php generated message. Use for stepping through an error.
		/// echo $e->getMessage();
		}	

		### NEW SCRIPT	

}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Contact Form</title>
        <link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
    </head>
    <body>
	<div class="shadow"><div class="header"></div></div>
        <div class="shadow">
        <?php
        include '../schedule/include/menu.php';
        ?>
        </div>
	<h1>Register Here ....</h1>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
			<fieldset id="standardForm">
				<div id="standFormLeft">               
					<label>First Name</label>
                    <input tabindex="1" type="text" name="fname" /><br />
					<label>Last Name</label>
                    <input tabindex="2" type="text" name="lname" /><br />
					<label>Email Address</label>
                    <input tabindex="3" type="email" name="email" /><br />
				</div>
                <div id="standFormRight">
                    <label>Password</label>
                    <input tabindex="4" type="password" name="password" /><br />
                    <label>Verify Password</label>
                    <input tabindex="5" type="password" name="password2" /><br />
					<input tabindex="6" type="submit" value="Submit" />
                </div>
                <?php if (!empty($errors)): ?>
                <p class="error">The following errors were detected:</p>
                <ul class="error">
                    <?php if (isset($errors['fname'])): ?>
                        <li><?php echo $errors['fname']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['password'])):
                       ?>
                        <li><?php echo $errors['password']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['lname'])): ?>
                        <li><?php echo $errors['lname']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['password2'])): ?>
                        <li><?php echo $errors['password2']; ?></li>
                    <?php endif; ?>

                    <?php if (isset($errors['email'])): ?>
                        <li><?php echo $errors['email']; ?></li>
                    <?php endif; ?>
                </ul>
                <?php endif; ?>
			</fieldset>
        </form>
        <?php if (isset($confirmation)): ?>
        <p class="borderbx"><?php echo $confirmation; ?></p>
        <?php endif; ?>
    </body>
</html>
This is the error message:
Fatal error: Call to a member function prepare() on a non-object in /home/content/38/7901938/html/tfm/register.php on line 33
Line 33:

Code: Select all

$prep = $link->pdo->prepare($query);
:?

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 »

Have you tried var_dump($link) yet? It doesn't seem to be recognized as a PDO object.

Looks like this is the problem:

Code: Select all

if(isset($_SESSION['user_id'])){
header("Location: profile.php");

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';

// including PasswordHash file for purposes of hashing passwords.
require '../PasswordHash.php';

}
You're including the db_connect file inside that if block. The first line of the block redirects the user, so the rest aren't being executed.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

OK... this is getting really frustrating. You're pointing me in the right direction. It is a connection issue. After checking all my ; and } things are in order. But... now I'm getting the following error messages:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/38/7901938/html/tfm/register.php on line 73

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/content/38/7901938/html/tfm/register.php on line 73

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/38/7901938/html/tfm/register.php on line 74

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/content/38/7901938/html/tfm/register.php on line 74

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/38/7901938/html/tfm/register.php on line 75

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/content/38/7901938/html/tfm/register.php on line 75
Why is there a connection problem. I am using the exact same connection string that I used in the working test file. The connection string is ...

Code: Select all

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';
This string is used in PDO_reg.php (which works) and in this register.php file (which does not work). The ONLY difference I can see is that in the register.php file there is a require string right beneath it for PasswordHash.php. But would PasswordHash.php be messing it up???
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Yeah.... that if block is what I meant when I said I had to make sure all my } and ; were in order. Now the block is structured as follows:

Code: Select all

// This file is adapted from registration script found at: http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/

// include database connection file, if connection doesn't work the include file will throw an error message
include '../tfm/include/db_connect.php';

// including PasswordHash file for purposes of hashing passwords.
require '../PasswordHash.php';

	session_start();
	if(isset($_SESSION['user_id'])){
	header("Location: profile.php");
	}
And I'm still getting all those connection error messages.

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 »

The connection error messages you're getting all refer to mysql_connect, which you're no longer using. Remove any calls to mysql_real_escape_string and then see what errors, if any, remain.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

So just assign these variables to the raw posts?
$fname = mysql_real_escape_string(trim($_POST['fname']));
$lname = mysql_real_escape_string(trim($_POST['lname']));
$password = mysql_real_escape_string(trim($_POST['password']));
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 »

Or use the $_POST variables directly since you're using a prepared statement.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Mixing php and html

Post by Pavilion »

Celauran wrote:Or use the $_POST variables directly since you're using a prepared statement.
Thank you Celauran - that solved the problem. Now onto the other php files. The more I work with PDO and the more you guide me, the more logic it becomes.

Pavilion
Post Reply