Jump to content
Larry Ullman's Book Forums

Chapter 17 - Ecommerce - Add_Book Customisation Issue


Recommended Posts

Hi boys and girls,
 
I have an issue with an altered version of add_book.php, which is used to add musical artists to an artists table in database. As far as I can see my code is fine as have altered this script a couple of times for various uses but for the life of me I cannot figure out why it is not working.
 
The error that is being thrown out is :
 
Your submission could not be processed due to a system error.
 
I have tracked through the code slowly but cannot work out what is causing this error. I have attached the code below and if anyone can help then I would be very appreciative.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
	<title>Add an Artist</title>
</head>
<body>


<?php #  add_artist.php
// This page allows the administrator to add a artist (product).

require_once ('../mysqli_connect_rock.php');

if (isset($_POST['submitted'])) { // Handle the form.
	
	// Validate the incoming data...
	$errors = array();

	// Check for a artist name:
	if (!empty($_POST['artist_name'])) {
		$an = trim($_POST['artist_name']);
	} else {
		$errors[] = 'Please enter the artist\'s name!';
	}
	
	// Check for an image:
	if (is_uploaded_file ($_FILES['image']['tmp_name'])) {
	
		// Create a temporary file name:
		$temp = '../../uploads/' . md5($_FILES['image']['name']);
	
		// Move the file over:
		if (move_uploaded_file($_FILES['image']['tmp_name'], $temp)) {
	
			echo '<p>The file has been uploaded!</p>';
			
			// Set the $i variable to the image's name:
			$i = $_FILES['image']['name'];
	
		} else { // Couldn't move the file over.
			$errors[] = 'The file could not be moved.';
			$temp = $_FILES['image']['tmp_name'];
		}

	} else { // No uploaded file.
		$errors[] = 'No file was uploaded.';
		$temp = NULL;
	}
	
	// Check for a description (not required):
	$d = (!empty($_POST['description'])) ? trim($_POST['description']) : NULL;
	
	// Validate the genre
	if (isset($_POST['genre']) && ($_POST['genre'] == 'new') ) {
		// If it's a new genre, add the genre to the database...
		
		// Check for a genre_name...
		if (!empty($_POST['genre_type'])) {
			
			$gt = trim($_POST['genre_type']);
			
			// Add the genre to the database:
			$q = 'INSERT INTO genres (genre_type) VALUES (?)';
			$stmt = mysqli_prepare($dbc, $q);
			mysqli_stmt_bind_param($stmt, 's', $gt);
			mysqli_stmt_execute($stmt);
			
			// Check the results....
			if (mysqli_stmt_affected_rows($stmt) == 1) {
				echo '<p>The genre has been added.</p>';
				$gt = mysqli_stmt_insert_id($stmt); // Get the genre ID.
			} else { // Error!
				$errors[] = 'The new genre could not be added to the database!';
			}
			
			// Close this prepared statement:
			mysqli_stmt_close($stmt);
			
		} else { // No genre type value.
			$errors[] = 'Please enter a genre type!';
		}
		
	} elseif ( isset($_POST['genre']) && ($_POST['genre'] == 'existing') && ($_POST['existing'] > 0) ) { // Existing genre.
		$gt = (int) $_POST['existing'];
	} else { // No genre selected.
		$errors[] = 'Please enter or select the artist\'s genre!';
	}
	
	if (empty($errors)) { // If everything's OK.
	
		// Add the Artist to the database:
		$q = 'INSERT INTO artists (artist_name, description, image_name, genres_genre_id) VALUES (?, ?, ?, ?)';
		$stmt = mysqli_prepare($dbc, $q);
		mysqli_stmt_bind_param($stmt, 'ssis', $a, $d, $gi, $i);
		mysqli_stmt_execute($stmt);
		
		// Check the results...
		if (mysqli_stmt_affected_rows($stmt) == 1) {
		
			// Print a message:
			echo '<p>The artist has been added.</p>';
			
			// Rename the image:
			$id = mysqli_stmt_insert_id($stmt); // Get the artist ID.
			rename ($temp, "../../uploads/$id");
			
			// Clear $_POST:
			$_POST = array();
			
		} else { // Error!
			echo '<p style="font-weight: bold; color: #C00">Your submission could not be processed due to a system error.</p>'; 
		}
		
		mysqli_stmt_close($stmt);
		
	} // End of $errors IF.
	
	// Delete the uploaded file if it still exists:
	if ( isset($temp) && file_exists ($temp) && is_file($temp) ) {
		unlink ($temp);
	}
	
} // End of the submission IF.

// Check for any errors and print them:
if ( !empty($errors) && is_array($errors) ) {
	echo '<h1>Error!</h1>
	<p style="font-weight: bold; color: #C00">The following error(s) occurred:<br />';
	foreach ($errors as $msg) {
		echo " - $msg<br />\n";
	}
	echo 'Please reselect the artists image and try again.</p>';
}

// Display the form...
?>
<h1>Add an Artist</h1>
<form enctype="multipart/form-data" action="add_artist.php" method="post">

	<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
	
	<fieldset><legend>Fill out the form to add an artist to the catalog:</legend>
	
	<p><b>Artist Name:</b> <input type="text" name="artist_name" size="30" maxlength="60" value="<?php if (isset($_POST['artist_name'])) echo htmlspecialchars($_POST['artist_name']); ?>" /></p>
	
	<p><b>Image:</b> <input type="file" name="image" /></p>
	
	<div><b>Genre:</b> 
	<p><input type="radio" name="genre" value="existing" <?php if (isset($_POST['genre']) && ($_POST['genre'] == 'existing') ) echo ' checked="checked"'; ?> /> Existing =>
	<select name="existing"><option>Select One</option>
	<?php // Retrieve all the genres and add to the pull-down menu.
	$q = "SELECT genre_id, CONCAT_WS(' ', genre_type) FROM genres ORDER BY genre_type ASC";		
	$r = mysqli_query ($dbc, $q);
	if (mysqli_num_rows($r) > 0) {
		while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
			echo "<option value=\"$row[0]\"";
			// Check for stickyness:
			if (isset($_POST['existing']) && ($_POST['existing'] == $row[0]) ) echo ' selected="selected"';
			echo ">$row[1]</option>\n";
		}
	} else {
		echo '<option>Please add a new genre.</option>';
	}
	mysqli_close($dbc); // Close the database connection.
	?>
	</select></p>
	
	<p><input type="radio" name="genre" value="new" <?php if (isset($_POST['genre']) && ($_POST['genre'] == 'new') ) echo ' checked="checked"'; ?> /> New =>
	Genre Name: <input type="text" name="genre_type" size="10" maxlength="40" value="<?php if (isset($_POST['genre_type'])) echo $_POST['genre_type']; ?>" /></p>
	</div>

	<p><b>Description:</b> <textarea name="description" cols="40" rows="5"><?php if (isset($_POST['description'])) echo $_POST['description']; ?></textarea></p>
	
	</fieldset>
		
	<div align="center"><input type="submit" name="submit" value="Submit" /></div>
	<input type="hidden" name="submitted" value="TRUE" />

</form>

</body>
</html>

Many thanks in advance

 

Roman

 

EDIT : I think the issue is to do with the :

 

// Rename the image:
            $id = mysqli_stmt_insert_id($stmt); // Get the artist ID.
            rename ($temp, "../../uploads/$id");

 

as its looking for the auto_increment id in the previous query but there isn't one. Is there an alternative to use the artists name?

 

cheers

Link to comment
Share on other sites

  • 4 months later...

I'm customizing the code from this chapter too, and I'm all tangled up in it and going blind. I suspect that the problem is from the insert section, but it could also be that I am trying to insert a country_id in a location table in kind of a sneaky way that I don't fully understand.

 

The table rows match. Do I need to do a JOIN here, maybe?

 

Here is the code: sorry it's all cluttered up with debugging attempts.

if (isset($_POST['submitted'])) { //Handle the form

    //validate the incoming data...
    $errors = array();
            
            
        //check for collection location
    if (!empty($_POST['loc_address'])) {
        $addr1 = trim($_POST['loc_address']);
    }else {
        $errors[] = 'no address posted';
    }
    if (!empty($_POST['loc_address2'])) {
        $addr2 = trim($_POST['loc_address2']);
    }else {
        $errors[] = 'no address2 posted';
    }
    if (!empty($_POST['loc_city'])) {
        $city = trim($_POST['loc_city']);
    }else {
        $errors[] = 'no city posted';
    }
    if (!empty($_POST['loc_state'])) {
        $state = trim($_POST['loc_state']);
    }else {
        $errors[] = 'no state posted';
    }
    if (!empty($_POST['loc_zip'])) {
        $zip = trim($_POST['loc_zip']);
    }else {
        $errors[] = 'no zip posted';
    }
    var_dump($addr1, $addr2, $city, $state, $zip);
    
    //check the country    
        if (!empty($_POST['country'])) {
        $coun = (int)trim($_POST['country']);
    }    else {
        $errors[] = 'no country posted';
    }
    var_dump($coun);
    
    if (empty($errors)){ //if everything is ok
            //add the location to the database
            $q = 'INSERT INTO location (loc_address, loc_address2, loc_city, loc_state, loc_zip, coll_id, country_id) VALUES
            (?, ?, ?, ?, ?, ?, ?)';
            $stmt = mysqli_prepare($dbc, $q);
            mysqli_stmt_bind_param($stmt, 'sssssii', $addr1, $addr2, $city, $state, $zip, $c, $coun);
            mysqli_stmt_execute($stmt);
            
            //Check the results
            if (mysqli_stmt_affected_rows($stmt)== 1){
                echo '<p>The location has been added</p>';
                $locid = mysqli_stmt_insert_id($stmt);//Get the location ID
                }else{//Error!
                    $errors[] = 'the location could not be added to the database.';
                }
                
            //Close this prepared statement
            mysqli_stmt_close($stmt);
            
        }//end of errors IF
        
    }//end of submission IF
            
    //check for any errors and print them
    if (!empty($errors) && is_array($errors)){
        echo '<h1>Error!</h1>
        <p style="font-weight:bold; color:#C00">The following error(s) occurred:<br />';
        foreach ($errors as $msg){
            echo " - $msg<br />\n";    
        }
        echo 'Please try again.</p>';
    }        
            
//Display the form    
?>    

<h1>Add a location</h1>
<form enctype="multipart/form-data" action="addCollectionTest.php" method="post">


<fieldset><legend></legend>


<p><b>(optional) Please enter the location : </b></p>
<p><b>Address 1: <input type="text" name="loc_address" size="10" maxlength="25"
value="<?php if (isset($_POST['loc_address'])) echo $_POST['loc_address']; ?>"/></b></p>

<p><b>Address 2: <input type="text" name="loc_address2" size="10" maxlength="25"
value="<?php if (isset($_POST['loc_address2'])) echo $_POST['loc_address2']; ?>"/></b></p>

<p><b>City: <input type="text" name="loc_city" size="10" maxlength="25"
value="<?php if (isset($_POST['loc_city'])) echo $_POST['loc_city']; ?>"/></b></p>

<p><b>State: <input type="text" name="loc_state" size="10" maxlength="25"
value="<?php if (isset($_POST['loc_state'])) echo $_POST['loc_state']; ?>"/></b></p>

<p><b>Postal Code: <input type="text" name="loc_zip" size="10" maxlength="10"
value="<?php if (isset($_POST['loc_zip'])) echo $_POST['loc_zip']; ?>"/></b></p>


<select name="country"><option>Select one</option>
<?php //retrieve all the countries and add to the pull-down menu

$q = "SELECT country_id, short_name FROM country";

$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
    while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
        echo "<option value=\"$row[0]\"";
        //Check for stickyness
        if (isset($_POST['country'])&&($_POST['country']== $row[0]))
        echo 'selected="selected"';
        echo ">$row[1]</option>\n";    
    }    
}else{
    echo '<option>Please select a country.</option>';    
}

mysqli_close($dbc);//close the database connection
?>
</select></p>
</fieldset>

<div align="center"> <input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />

</form>

Link to comment
Share on other sites

Could you be more precise about what the problem is? What are you expecting to happen and what is actually occurring? Are you getting any system error messages?  Have you tried running your sql statements directly using something like phpmyadmin to determine if the queries are valid?

 

I did notice that this statement

mysqli_stmt_bind_param($stmt, 'sssssii', $addr1, $addr2, $city, $state, $zip, $c, $coun);

refers to $c variable. Have you declared that variable?

$q = "SELECT country_id, short_name FROM country";

$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
    while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
        echo "<option value=\"$row[0]\"";
        //Check for stickyness
        if (isset($_POST['country'])&&($_POST['country']== $row[0]))
        echo 'selected="selected"';
        echo ">$row[1]</option>\n";    
    }    
}else{
    echo '<option>Please select a country.</option>';    
}

Is the above code the bit you don't understand? I haven't looked at it closely but basically it is getting all the countries from the d/b, looping through the results to display a drop down menu for the user to select a country and making the user's selection sticky. Look at the resulting source code to see how efficiently it creates the drop down menu for you. Hope that helps.

 

Oh and could you use code tags for posting any code, it's the <> icon on the edit toolbar.

  • Upvote 1
Link to comment
Share on other sites

The $c variable is a table id # from another part of the code and it works fine in other areas (I just posted the problem area of the code). The drop down menu is also working just fine. The problem is that nothing posts to the location table and the only error code I get is "the location could not be added to the database." I assume that this means there are no errors happening when the form is validated, but that something is just not happening when it goes to post to the table.

 

I am wondering: since I am pulling information from the countries table (the $coun variable is the country_id field) and trying to insert it into the location table (the country_id field in "location"), is something going wrong here? the country_id fields are identical in both tables.

 

thanks for the tag info!

 

LATER: the queries are valid too. (I'm stumped).

 

LATER: you were right about the $c variable. It was posting as a string in an integer column in my test script. Thanks for your eagle eyes and patience.

Link to comment
Share on other sites

  • 1 month later...
 Share

×
×
  • Create New...