Page 1 of 1

PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 9:00 am
by alex123
I am almost done the edit profile page on my site. I have been following this tutorial: http://www.youtube.com/watch?v=2gcKp6hcSAY

For some reason, when I click on update, the page simply refreshes and nothing is updated in the database. Do you have any idea why? Thanks again for any help.

Relevant files:
core/inc/user.inc.php (rows 46-59)
<?php
	$link = mysql_connect('localhost','root','1234') or die('Cannot connect to database');
	mysql_select_db('youtube');

//1
function fetch_users(){
        $result = mysql_query('SELECT `id`, `username` FROM `user`') or die(mysql_error());

        $users = array();
//2
        while (($row = mysql_fetch_assoc($result)) !== false){
                $users[] = $row;
        } 
        return $users;
}

function fetch_user_info($id){
	$id = (int)$id;

	$sql = "SELECT `username`,
				`email`, 
				`description`,
				`birthdate`, 
				`firstname`,
				`lastname`,
				`gender`,
				`city`, 
				`country`,
				`datereg`
			FROM `user`
			WHERE `id` = {$id}";
			
	$result = mysql_query($sql);
	
	return mysql_fetch_assoc($result);
}

$username = $_SESSION['username'];
$query = mysql_query("SELECT id FROM user WHERE username='$username'")
or die(mysql_error());
	if (!$query){
		echo mysql_error();
	}
$row = mysql_fetch_row($query);

function set_profile_info ($email, $description, $city, $country){
	$email = mysql_real_escape_string(htmlentities($email));
	$city = mysql_real_escape_string($city);
	$country = mysql_real_escape_string($country);
	$description = mysql_real_escape_string(nl2br(htmlentities($description)));
	
	$sql = "UPDATE 'users' SET
		'email' = '{$email}',
		'city' = '{$city}',
		'country' = '{$country}',
		'description' = '{$description}'
		WHERE 'id' = {$row[0]}";
		
	mysql_query($sql);
}	
?>
edit_profile.php
<?php
session_start();
include('core/inc/user.inc.php');

if (isset($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description'])){
	$errors = array();
	
	if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false){
		$errors[] = 'The email address you entered is not valid.';
	}
	
	if (preg_match('#^[a-z0-9 ]+$#i', $_POST['location']) === 0){
		$errors[] = 'Your location must only contain a-z, 0-9 and spaces.';
	}
	
	if (empty($errors)){
		set_profile_info($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description']);
	}
	
	$user_info = array(
		'email' => htmlentities($_POST['email']),
		'descriptiom' => htmlentities($_POST['city']),
		'city' => htmlentities($_POST['country']),
		'country' => htmlentities($_POST['description']) );
}

else{
	$user_info = fetch_user_info($row[0]);
}
?>
<html>
	<head>
		<style type="text/css">
			form {margin: 10px 0 0 0;}
			form div {float:left; clear:both; margin: 0 0 4px 0;}
			label{float:left; width:100px;}
			input[type="text"], textarea {float:left; width:400px;}
			input[type="submit"] {margin:10px 0 0 100px;}
		</style>
		<title>Edit Your Profile</title>
	</head>
	<body>
		<div>
			<?php
			if (isset($errors) === false){
				echo 'Click update to edit your profile.';
			}
			else if (empty($errors)){
				echo 'Your profile has been updated/';
			}
			else{
				echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
			}
			?>
		</div>
		<br>
	<form action="" method="post">
		<div>
			<label for="email">Email:</label>
			<input type="text" name="email" id="email" value="<?php echo $user_info['email']; ?>" />
		</div>
		<div>
			<label for="location">City:</label>
			<input type="text" name="city" id="city" value="<?php echo $user_info['city']; ?>" />
		</div>
		<div>
			<label for="location">Country:</label>
			<input type="text" name="country" id="country" value="<?php echo $user_info['country']; ?>" />
		</div>
		<div>
			<label for="about">About me:</label>
			<textarea name="about" id="about" rows="14" cols="50"><?php echo strip_tags($user_info['description']); ?></textarea>
		</div>
		<div>
			<input type="submit" value="Update" />
		</div>
	</body>
</html>

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 1:33 pm
by Tino
In the set_profile_info function, you use quotes around your field and table names, whereas they should be backticks. You should only use quotes around values that are strings.

In the future, if your query is failing and you don't know why, use the mysql_error function right after you perform your query to display the error.
echo mysql_error();

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 6:37 pm
by alex123
Well I just added echo mysql_error(); to my code and it says: Unknown column 'bob123' in 'where clause'
Yet bob123 is the username.

I changed my code to this, as you recommended
$query = mysql_query("SELECT `id` FROM `user` WHERE `username`=$username")
Thanks!

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 6:44 pm
by Tino
You still need the quotes around $username

As I said, you should use quotes only around strings. Considering the username is going to be a string, like bob123 in this case, you should wrap $username in quotes.

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 6:54 pm
by alex123
I scrapped much of the code. The database updates perfectly, but after I click on update, depending on which fields I modify, the fields turn to some strange code, such as <br /><br /><font size='1'><table class='xdebug-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'><br /><tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: description in C:\wamp\www\edit_profile.php on line <i>131</i></th></tr><br /><tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr><br /><tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr><br /><tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0014</td><td bgcolor (no idea where this comes from)

This the code I have now (the $_SESSION['id'] variable wasn't working so I had to add some lines)
<?php
session_start();
$link = mysql_connect('localhost','root','1234') or die('Cannot connect to database');
mysql_select_db('youtube');

function fetch_user_info($id){
	$id = (int)$id;

	$sql = "SELECT `username`,
				`email`, 
				`description`,
				`birthdate`, 
				`firstname`,
				`lastname`,
				`gender`,
				`city`, 
				`country`,
				`datereg`
			FROM `user`
			WHERE `id` = {$id}";
			
	$result = mysql_query($sql);
	
	return mysql_fetch_assoc($result);
}


function set_profile_info($email, $city, $country, $description){
	$email = mysql_real_escape_string(htmlentities($email));
	$city = mysql_real_escape_string($city);
	$country = mysql_real_escape_string($country);
	$description = mysql_real_escape_string(nl2br(htmlentities($description)));
	$username = $_SESSION['username'];
$query = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'")
or die(mysql_error());
	if (!$query){
		echo mysql_error();
	}
$row = mysql_fetch_row($query);
	
	
	$sql = "UPDATE `user` SET
		`email` = '{$email}',
		`city` = '{$city}',
		`country` = '{$country}',
		`description` = '{$description}'
		WHERE `id` = {$row[0]}";
		
	mysql_query($sql);
}	

if (isset($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description'])){
	$errors = array();
	
	if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false){
		$errors[] = 'The email address you entered is not valid.';
	}
	
	if (preg_match('#^[a-z0-9 ]+$#i', $_POST['city']) === 0){
		$errors[] = 'Your city must only contain a-z, 0-9 and spaces.';
	}
	
	if (preg_match('#^[a-z0-9 ]+$#i', $_POST['country']) === 0){
		$errors[] = 'Your country must only contain a-z, 0-9 and spaces.';
	}
	
	if (empty($errors)){
		set_profile_info($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description']);
	}
	
	$user_info = array(
		'email' => htmlentities($_POST['email']),
		'descriptiom' => htmlentities($_POST['city']),
		'city' => htmlentities($_POST['country']),
		'country' => htmlentities($_POST['description'])); 
}

else{
	$username = $_SESSION['username'];
	$query = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'")
	or die(mysql_error());
		if (!$query){
			echo mysql_error();
		}
$row = mysql_fetch_row($query);
	$user_info = fetch_user_info($row[0]);
}
echo mysql_error();
?>
<html>
	<head>
		<style type="text/css">
			form {margin: 10px 0 0 0;}
			form div {float:left; clear:both; margin: 0 0 4px 0;}
			label{float:left; width:100px;}
			input[type="text"], textarea {float:left; width:400px;}
			input[type="submit"] {margin:10px 0 0 100px;}
		</style>
		<title>Edit Your Profile</title>
	</head>
	<body>
		<div>
			<?php
			if (isset($errors) === false){
				echo 'Click update to edit your profile.';
			}
			else if (empty($errors)){
				echo 'Your profile has been updated.';
			}
			else{
				echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
			}
			?>
		</div>
		<br>
	<form action="edit_profile.php" method="post">
		<div>
			<label for="email">Email:</label>
			<input type="text" name="email" id="email" value="<?php echo $user_info['email']; ?>" />
		</div>
		<div>
			<label for="city">City:</label>
			<input type="text" name="city" id="city" value="<?php echo $user_info['city']; ?>" />
		</div>
		<div>
			<label for="country">Country:</label>
			<input type="text" name="country" id="country" value="<?php echo $user_info['country']; ?>" />
		</div>
		<div>
			<label for="about">About me:</label>
			<textarea name="description" id="description" rows="14" cols="50"><?php echo $user_info['description']; ?></textarea>
		</div>
		<div>
			<input type="submit" value="Update" />
		</div>
	</body>
</html>
Here's what happens after I change the description and click on update. The database updated, but this strange code appears. This happens for other fields too http://s1085.photobucket.com/albums/j43 ... nt=123.png

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 9:45 pm
by Tino
If you look closely at those messages, you should be able to read something along the lines of this:
Notice: Undefined index: description in C:\wamp\www\edit_profile.php on line 131
Basically, in your input fields you're trying to print the value of $_POST variables. You do this even if the form has not been submitted yet. You can use the isset function to fix this issue.
<input type="text" name="name" id="name" value="<?php if ( isset($_POST['name']) ) echo $_POST['name']; ?>" />
You should then do that for every field where you want this functionality, and of course making the appropriate changes to the variables names and field names ;)

As a side note, normally I wouldn't recommend writing if statements on one line, but I think it's fine in this case. ;)

Re: PHP edit profile page does not update database

Posted: Sat Dec 24, 2011 11:59 pm
by alex123
Thanks a lot for pointing the error message out (I didn't define the array variables properly)
here's the fully functional script if anyone needs it
<?php
session_start();
$link = mysql_connect('localhost','root','1234') or die('Cannot connect to database');
mysql_select_db('youtube');

function fetch_user_info($id){
	$id = (int)$id;

	$sql = "SELECT `username`,
				`email`, 
				`description`,
				`birthdate`, 
				`firstname`,
				`lastname`,
				`gender`,
				`city`, 
				`country`,
				`datereg`
			FROM `user`
			WHERE `id` = {$id}";
			
	$result = mysql_query($sql);
	
	return mysql_fetch_assoc($result);
}


function set_profile_info($email, $city, $country, $description){
	$email = mysql_real_escape_string(htmlentities($email));
	$city = mysql_real_escape_string($city);
	$country = mysql_real_escape_string($country);
	$description = mysql_real_escape_string(nl2br(htmlentities($description)));
	$username = $_SESSION['username'];
$query = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'")
or die(mysql_error());
	if (!$query){
		echo mysql_error();
	}
$row = mysql_fetch_row($query);
	
	
	$sql = "UPDATE `user` SET
		`email` = '{$email}',
		`city` = '{$city}',
		`country` = '{$country}',
		`description` = '{$description}'
		WHERE `id` = {$row[0]}";
		
	mysql_query($sql);
}	

if (isset($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description'])){
	$errors = array();
	
	if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false){
		$errors[] = 'The email address you entered is not valid.';
	}
	
	if (preg_match('#^[a-z0-9 ]+$#i', $_POST['city']) === 0){
		$errors[] = 'Your city must only contain a-z, 0-9 and spaces.';
	}
	
	if (preg_match('#^[a-z0-9 ]+$#i', $_POST['country']) === 0){
		$errors[] = 'Your country must only contain a-z, 0-9 and spaces.';
	}
	
	if (empty($errors)){
		set_profile_info($_POST['email'], $_POST['city'], $_POST['country'], $_POST['description']);
	}
	
	$user_info = array(
		'email' => htmlentities($_POST['email']),
		'city' => htmlentities($_POST['city']),
		'country' => htmlentities($_POST['country']),
		'description' => htmlentities($_POST['description'])); 
}

else{
	$username = $_SESSION['username'];
	$query = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'")
	or die(mysql_error());
		if (!$query){
			echo mysql_error();
		}
$row = mysql_fetch_row($query);
	$user_info = fetch_user_info($row[0]);
}
?>
<html>
	<head>
		<style type="text/css">
			form {margin: 10px 0 0 0;}
			form div {float:left; clear:both; margin: 0 0 4px 0;}
			label{float:left; width:100px;}
			input[type="text"], textarea {float:left; width:400px;}
			input[type="submit"] {margin:10px 0 0 100px;}
		</style>
		<title>Edit Your Profile</title>
	</head>
	<body>
		<div>
			<?php
			if (isset($errors) === false){
				echo 'Click update to edit your profile.';
			}
			else if (empty($errors)){
				echo 'Your profile has been updated.';
			}
			else{
				echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
			}
			?>
		</div>
		<br>
	<form action="edit_profile.php" method="post">
		<div>
			<label for="email">Email:</label>
			<input type="text" name="email" id="email" value="<?php echo $user_info['email']; ?>" />
		</div>
		<div>
			<label for="city">City:</label>
			<input type="text" name="city" id="city" value="<?php echo $user_info['city']; ?>" />
		</div>
		<div>
			<label for="country">Country:</label>
			<input type="text" name="country" id="country" value="<?php echo $user_info['country']; ?>" />
		</div>
		<div>
			<label for="about">About me:</label>
			<textarea name="description" id="description" rows="14" cols="50"><?php echo $user_info['description']; ?></textarea>
		</div>
		<div>
			<input type="submit" value="Update" />
		</div>
	</body>
</html>