Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hi,

I'm trying to modify the 10.3 edit user script on page 310,  specifically,  the create form section.  I would like to use a <select> tag instead of a text input for one of the form fields.  It seems very basic, however, I'm struggling to get the code to work for the select option values. 

 

Maybe it's a matter of single or double quotes, but I need some help to actually figure this out.  The form is inside an echo.

 

I've tried:

 

echo '
<form action="edit-users.php" method="post">
<fieldset>
<legend>Update User Information</legend>
<label>Your First Car:</label>
<select name="car_type">
<option value="'. $row[0] .'>VW Van</option>
<option value="'. $row[0] .'>Toyota Corolla</option>
<option value="'. $row[0] .'>Chevy Camaro</option>
</select>
<br />
<br />
<label>First Name:</label><input type="text" name="first_name" size="20" maxlength="60" value="' .$row[1] . '" /><br />
<label>Last Name:</label><input type="text" name="last_name" size="20" maxlength="60" value="' .$row[2] . '" /><br />
<label>Email:</label><input type="text" name="email" size="20" maxlength="60" value="' .$row[3] . '" /><br /><br />
<p><input type="submit" class="button" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</fieldset>
</form>';

And this:

echo '
<form action="edit-users.php" method="post">
<fieldset>
<legend>Update User Information</legend>
<label>Your First Car:</label>
<select name="car_type">
<option value="VW Van"' if($row['0'] =='VW Van') echo "selected='selected'"'>VW Van</option>
<option value="Toyota Corolla"'if ($row['0'] =='Toyota Corolla') echo "selected='selected'"'>Toyota Corolla</option>
<option value="Chevy Camaro"'if ($row['0'] =='Chevy Camaro') echo "selected='selected'"'>Chevy Camaro</option
</select>
<br />
<br />
<label>First Name:</label><input type="text" name="first_name" size="20" maxlength="60" value="' .$row[1] . '" /><br />
<label>Last Name:</label><input type="text" name="last_name" size="20" maxlength="60" value="' .$row[2] . '" /><br />
<label>Email:</label><input type="text" name="email" size="20" maxlength="60" value="' .$row[3] . '" /><br /><br />
<p><input type="submit" class="button" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</fieldset>
</form>';

Plus I have tried numorous other combinations with no luck.  Any help will be appreciated.

 

Link to post
Share on other sites

If I understand the question correctly, you want to output a select field in your form, something like

<option value="1">VW Van</option>
<option value="2">Toyota Corolla</option>
<option value="3">Chevy Camarro</option>

You will need a loop for this, because at the moment the option value will always be the same value. Here's a suggestion on the assumption that you are querying a table which has the fields car_type_id and car_type. You will need to alter the code based on how you are getting the info but hopefully this gives you some idea.

<select name="car_type">;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
    echo '<option value="' . $row['car_type_id'] . '">' . $row['car_type'] . '</option>';
}
echo '</select>';

Also you have a missing double quote in your first example on rows 7, 8 and 9. Should be

<option value="'. $row[0] . '">VW Van</option>
 
  • Upvote 2
Link to post
Share on other sites

Margaux and HS thanks for the replies:

Yes, this was a typo.  As you said, missing a double quote.

<option value="'. $row[0] . '>VW Van</option>

What I'm trying to achieve is the same as the 10.3 edit_user script except that in addition to first name, last name and email, I would like to UPDATE the user's car type using a select, dropdown.  

 

The two screenshot links will hopefully make sense.

 

I would like to change Ringo Starr's car type from Chevy Camaro to VW Van.  Clicking on the Edit user here: https://docs.google.com/file/d/0B5uX0wJkztzXMjJVTWRoR3liNW8/edit?usp=sharing

 

Should display as shown here:  https://docs.google.com/file/d/0B5uX0wJkztzXOUI5dmhiRTh3cjA/edit?usp=sharing


With the exception of a dropdown menu for car type, like this: https://docs.google.com/file/d/0B5uX0wJkztzXUVE3d1hiLXlFZ1U/edit?usp=sharing

 

Here is the code from the book, script 10.3, with the html.

echo '<form action="edit_user.php" method="post">
<fieldset>
<legend>Update User</legend>
<label>Car Type:</label><input type="text" name="car_type" size="15" maxlength="15" value="' .$row[0] . '" /><br />
<label>First Name:</label><input type="text" name="first_name" size="15" maxlength="15" value="' .$row[1] . '" /><br />
<label>Last Name:</label><input type="text" name="last_name" size="15" maxlength="30" value="' .$row[2] . '" /><br />
<label>Email Address:</label><input type="text" name="email" size="20" maxlength="60" value="' .$row[3] . '" /><br />
<br />
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';

 

I have tried to change line 4 to this: (below code)

<label>Car Type:</label>
<select>
<option value="' . $row[0] . '">VW Van</option>
<option value="' . $row[0] . '">Chevy Camaro</option>
<option value="' . $row[0] . '">Toyota Corolla</option>
</select>

But when submitting, only get this: https://docs.google.com/file/d/0B5uX0wJkztzXaFJXeEhzY1lWZmM/edit?usp=sharing

btw

There is only one table (users) in the database, with the following columns: user_id, car_type, first_name, last_name, email, pass, and registration_date.

:

 

 

Link to post
Share on other sites

This does not make sense - unless you use a loop, the option value is always going to be the same so how will you know what type of car is being selected?

 

The error you're getting is resulting from your form validation. How are you validating the car_type field? You can't use empty, you need to use isset.

 

In order to help, we need to see your code and it would help to see the d/b query you are using to populate the form. I am happy to try to help but I don't always have access to the book you refer to so please post the relevant code.

Link to post
Share on other sites

Ok.  Here is the entire code for view users.php script.

<?php #Sript 10.5 - view_users.php
//This script retrieves all the records from the users table.
// This new version links to edit and delete pages.

//Add the title, header, and h1 tag.
$page_title = 'View Registered Users';
include ('includes/header.html');
echo '<h1>Registered Users</h1>';

// connect to the database, use require for "mission critical" includes.
require_once ('mysqli_connect.php');

//Add number of records to show per page as a variable.
$display = 15;

//Determine the total number pages.
if (isset($_GET['p']) && is_numeric($_GET['p'])) {
		// if the number of records is already determined.
	$pages = $_GET['p'];
	}
	else {
		// Count the number of records
		$q = "SELECT COUNT(user_id) FROM users";
		$r = mysqli_query($dbc, $q); //mysqli_query — Performs a query on the database: mysqli $link , string $query
		$row = mysqli_fetch_array($r, MYSQLI_NUM);
		$records = $row[0];
		//Calculate the number of pages
		if ($records > $display){
		$pages = ceil($records/$display);  //ceil — Round fractions up
		}
		else {
			$pages = 1;
			}
		}  //End of p IF.
		
		// Determine where in the database to start returning results.
		if (isset($_GET['s']) && is_numeric($_GET['s'])) {
			$start = $_GET['s'];
			}
				else{
				$start = 0;
				}
		//Determine the sort...default is by registration date.
		$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';
		
		/*Taken from forum post http://board.phpbuilder.com/showthread.php?10368862-RESOLVED-ASC-DESC-Table.
			$sort_order = 'asc'; 
		if(isset($_GET['sort_by'])) 
		{ 
			if($_GET['sort_by'] == 'asc') 
			{ 
				$sort_order = 'desc'; 
			} else 
			{ 
				$sort_order = 'asc'; 
			} 
		} End forum code */
	
		//Determine the sorting order.
		$ln_sort = 'ln';
		$car_type_sort = 'car_type';
		$fn_sort = 'fn';
		$rd_sort = 'rd';
		
		switch ($sort) {
			case 'ln':
				$order_by = 'last_name ASC';
				$ln_sort = 'lnr';
				break;
			case 'lnr':
				$order_by = 'last_name DESC';
				break;
				
			case 'car_type':
				$order_by = 'car_type ASC';
				$car_type_sort = 'rcar_type';
				break;
			case 'rcar_type':
				$order_by = 'car_type DESC';
				break;
				
			case 'fn':
				$order_by = 'first_name ASC';
				$fn_sort = 'fnr';
				break;
			case 'fnr':
				$order_by = 'first_name DESC';
				break;
			case 'rd':
				$order_by = 'registration_date ASC';
				$rd_sort = 'rdr';
				break;
			case 'rdr':
				$order_by = 'registration_date DESC';
				break;
			default:
				$order_by = 'registration_date ASC';
				$rdr_sort = 'rdr';
				$sort = 'rd';
			break;
		}
		
		//Define the query:
		$q = "SELECT car_type, last_name, first_name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr, user_id FROM users ORDER BY $order_by LIMIT $start, $displsay";
		
		//Run the query
		$r = @mysqli_query($dbc, $q);  
	
		//Start the table header
		echo '<table align="center" cellspacing="0" cellpadding="5" width="75%">
		<tr>
			<td align="left"><b>Edit</b></td>
			<td align="left"><b>Delete</b></td>
			<td align="left"><b><a href="view_users.php?sort='. $car_type_sort . '">Car Type</a></b></td>
			<td align="left"><b><a href="view_users.php?sort='. $ln_sort . '">Last Name</a></b></td>
			<td align="left"><b><a href="view_users.php?sort='. $fn_sort .'">First Name</a></b></td>
			<td align="left"><b><a href="view_users.php?sort='. $rd_sort .'">Date Registered</a></b></td>
		</tr>
		';
		
		//Fetch and print all the records.
		$bg = '#eeeeee';
		while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
		$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
		echo '<tr bgcolor="' .$bg . '">
		<td align="left"><a href="edit_user.php?id=' . $row['user_id'] . '">Edit</a></td>
		<td align="left"><a href="delete_user.php?id=' . $row['user_id'] . '">Delete</a></td>
		<td align="left">' .$row['car_type'] . '</td>
		<td align="left">' .$row['last_name'] .'</td>
		<td align="left">' .$row['first_name'] .'</td>
		<td align="left">' .$row['dr'] .'</td>
		</tr>
		';
		} //End of WHILE loop.
		
		echo '</table>';
		mysqli_free_result ($r);
		mysqli_close($dbc);
		
		//Make the links to other pages, if necessary.
		if ($pages > 1) {
		echo '<br /><p>';
		$current_page = ($start/$display) + 1;
		
		// If it's not the first page, make a Previous buttion:
		if ($current_page != 1) {
		echo '<a href="view_users.php?s=' . ($start - $display) . '&p=' . $pages . '&sort=' . 
		$sort . '">Previous</a>';
		}
		
		// Make all the numbered pages.
		for ($i = 1; $i <= $pages; $i++) {
		if ($i != $current_page) {
		echo '<a href="view_users.php?s=' . (($display * ($i - 1))) .'&p=' . $pages . '&sort=' . $sort . '">' 
		. $i . '</a>';
		} else {
			echo $i . ' ';
			}
			} // End of FOR loop.
			
		//If it's not the last page, make a Next buttion:
		if ($current_page != $pages) {
		echo '<a href="view_users.php?s=' . ($start + $display) . '&p=' . $pages . '&sort=' . $sort . '">Next</a>';
		}
		echo '</p>'; // Close the paragraph
		} // End the page links section

		include ('includes/footer.html');
		?>	

And here is the entire coder for the the edit_users.php.  Lines 92, 93, and 94 are the problem lines.

 

<?php # Script 10.3 - edit_user.php
// This page is accessed through view_users.php.

$page_title = 'Edit a User';
include ('includes/header.html');
echo '<h1>Edit a User</h1>';

//Check for a valid user id
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) {
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ){
$id = $_POST['id'];
} else {
	echo '<p class="error">This page has been accessed in error.</p>';

	include ('includes/footer.html');
	exit();
	}
// End of user id check

// Add the MySQL connection
include ('mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	//Make use of an array to track all errors.
	$errors = array();
	
	if (empty($_POST['car_type'])) {
	$errors[] = 'You forgot to enter your car_type.';
	} else {
		$car_type = mysqli_real_escape_string($dbc, trim($_POST['car_type']));
		}
	
	if (empty($_POST['first_name'])) {
	$errors[] = 'You forgot to enter your first name.';
	} else {
		$fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
		}
	
	if (empty($_POST['last_name'] )) {
	$errors[] = 'You forgoe to enter your last name.';
	} else {
		$ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
		}
		
	if (empty($_POST['email'] )) {
	$errors[] = 'You forgot to enter your email.';
	} else {
		$e = mysqli_real_escape_string($dbc, trim($_POST['email']));
		}
	if (empty($errors)) {
	$q = "SELECT user_id FROM users WHERE email='$e' AND user_id !=$id";
	$r = @mysqli_query($dbc, $q);
	if (mysqli_num_rows($r) == 0) {
	$q = "UPDATE users SET car_type='$car_type', first_name='$fn', last_name='$ln', email='$e' WHERE user_id=$id LIMIT 1";
	$r = @mysqli_query($dbc, $q);
	
	if (mysqli_affected_rows($dbc) == 1) {
	echo '<p>The user has been edited.</p>';
	} else {
		echo '<p class="error">The user could not be edited due to a system error. </p>';
		echo '<p>'.mysqli_error($dbc) . '<br />Query: ' . $q .'</p>';
		}
		} else {
			echo '<p class="error">The email address has already been registered.</p>';
			}
		} else {
		echo '<p class="error">The following error(s) occurred:<br />';
		foreach ($errors as $msg) {
			echo " - $msg<br />\n";
		}
		echo '</p><p>Please try again.</p>';
		}
		
	} //End of submit conditional.
	
	//Retrieve the information for the user being edited
	
$q = "SELECT car_type, first_name, last_name, email FROM users WHERE user_id=$id";
$r = @mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
		
	//DISPLAY THE FORM
echo '<form action="edit_user.php" method="post">
<fieldset>
<legend>Update User</legend>

<label>Car Type:</label>
<select>
<option value="' . $row[0] . '">VW Van</option>
<option value="' . $row[0] . '">Chevy Camaro</option>
<option value="' . $row[0] . '">Toyota Corolla</option>
</select><br /> <br />
<label>First Name:</label><input type="text" name="first_name" size="15" maxlength="15" value="' .$row[1] . '" /><br />
<label>Last Name:</label><input type="text" name="last_name" size="15" maxlength="30" value="' .$row[2] . '" /><br />
<label>Email Address:</label><input type="text" name="email" size="20" maxlength="60" value="' .$row[3] . '" /><br />
<br />
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';

}else {
	echo '<p class="error">This page has been accessed in error.</p>';
	}
mysqli_close($dbc);
include ('includes/footer.html');
?>

 

Link to post
Share on other sites

Firstly you need to give the select field a name otherwise you will not be able to access it via $_POST. Secondly, the value of all the options are always going to have the same value so it won't matter which option is selected. Thirdly, you need to use isset to validate select fields. Try this

 <select name="car_type">';
    $car_types = array('VW Van','Chevy Camaro', 'Toyota Corolla' ); //create an array for car_types
    foreach ($car_types as $value) {loop through the array
		echo '
		<option value="'. $value . '" '; //set the option value equal to the array value
		 if ($row[0] == $value) echo 'selected '; //make sticky
		
		 echo ">$value</option>"; //end option field
	}
	echo '</select><br /> <br />'; //end select input field

Change line 29 to

 if (!isset($_POST['car_type'])) {

 


 

 


 
  • Upvote 1
Link to post
Share on other sites

Brilliant.  It works perfect.

At first I kept getting unexpected T_String on the foreach line, until I saw that your loop through the array comment did not have //.

 

Here is the final code in case it may help someone else.

 

Thanks again margaux!

 

<?php # Script 10.3 - edit_user.php
// This page is accessed through view_users.php.

$page_title = 'Edit a User';
include ('includes/header.html');
echo '<h1>Edit a User</h1>';

//Check for a valid user id
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) {
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ){
$id = $_POST['id'];
} else {
	echo '<p class="error">This page has been accessed in error.</p>';

	include ('includes/footer.html');
	exit();
	}
// End of user id check

// Add the MySQL connection
include ('mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	//Make use of an array to track all errors.
	$errors = array();
	
	if (!isset($_POST['car_type'])) {
	$errors[] = 'You forgot to enter your car_type.';
	} else {
		$car_type = mysqli_real_escape_string($dbc, trim($_POST['car_type']));
		}
	
	if (empty($_POST['first_name'])) {
	$errors[] = 'You forgot to enter your first name.';
	} else {
		$fn = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
		}
	
	if (empty($_POST['last_name'] )) {
	$errors[] = 'You forgoe to enter your last name.';
	} else {
		$ln = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
		}
		
	if (empty($_POST['email'] )) {
	$errors[] = 'You forgot to enter your email.';
	} else {
		$e = mysqli_real_escape_string($dbc, trim($_POST['email']));
		}
	if (empty($errors)) {
	$q = "SELECT user_id FROM users WHERE email='$e' AND user_id !=$id";
	$r = @mysqli_query($dbc, $q);
	if (mysqli_num_rows($r) == 0) {
	$q = "UPDATE users SET car_type='$car_type', first_name='$fn', last_name='$ln', email='$e' WHERE user_id=$id LIMIT 1";
	$r = @mysqli_query($dbc, $q);
	
	if (mysqli_affected_rows($dbc) == 1) {
	echo '<p>The user has been edited.</p>';
	} else {
		echo '<p class="error">The user could not be edited due to a system error. </p>';
		echo '<p>'.mysqli_error($dbc) . '<br />Query: ' . $q .'</p>';
		}
		} else {
			echo '<p class="error">The email address has already been registered.</p>';
			}
		} else {
		echo '<p class="error">The following error(s) occurred:<br />';
		foreach ($errors as $msg) {
			echo " - $msg<br />\n";
		}
		echo '</p><p>Please try again.</p>';
		}
		
	} //End of submit conditional.
	
	//Retrieve the information for the user being edited
	
$q = "SELECT car_type, first_name, last_name, email FROM users WHERE user_id=$id";
$r = @mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_NUM);


	//DISPLAY THE FORM
echo '<form action="edit_user.php" method="post">
<fieldset>
<legend>Update User</legend>
<label>Car Type:</label>
<select name="car_type">';
    $car_type = array('VW Van','Chevy Camaro', 'Toyota Corolla'); //create an array for car_types
    foreach($car_type as $value) {//loop through the array
		echo '
		<option value="'. $value .'"'; //set the option value equal to the array value
		 if ($row[0] == $value) echo 'selected'; //make sticky
		 echo ">$value</option>"; //end option field
	}
	echo '</select><br /><br />'; //end select input field
echo'
<label>First Name:</label><input type="text" name="first_name" size="15" maxlength="15" value="' .$row[1] . '" /><br />
<label>Last Name:</label><input type="text" name="last_name" size="15" maxlength="30" value="' .$row[2] . '" /><br />
<label>Email Address:</label><input type="text" name="email" size="20" maxlength="60" value="' .$row[3] . '" /><br />
<br />
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';

}else {
	echo '<p class="error">This page has been accessed in error.</p>';
	}
mysqli_close($dbc);
include ('includes/footer.html');
?>
Link to post
Share on other sites

That's great. Arrays and loops are worth getting to know well as they do a lot of work for you. In this instance if you want to add or change the car types, its just a quick change to the contents of the array.

 

One suggestion that I learned here and will pass on - when debugging, print_r your variables. For example if you had inserted print_r($_POST); initially you would have seen that there was nothing in the select field and then you'd know where to amend your code.

Link to post
Share on other sites
  • 11 months later...

Thank you to Deaddog for his view_users.php (script 10.5) code which solved a problem for me. I wanted to switch form ASC to DESC for the lists, and got about halfway there, but this solved the problem for me. I have altered it slightly to suit my own requirements but gave honourable mention in the comments.

  • Upvote 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...