简体   繁体   中英

mysql php script only works first time

I have a script to add companies and categories to a database, however it only works first time. When I try to add a second company, it fails on the final error check after passing all other error checks. The category is added successfully to the categories table but the company and its details do not get added to the companies table.

Is this likely to be a code error or an error in my database construction?

Here is the final error check and mysql query:

if (empty($errors)) { // If everything's OK.

    // Add the company to the database:
    $q = 'INSERT INTO companies (category_id, company_name, phone, email, website, address_1, address_2, address_3, postcode, description, image_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
    $stmt = mysqli_prepare($dbc, $q);
    mysqli_stmt_bind_param($stmt, 'issssssssss', $catid, $cn, $p, $e, $w, $a1, $a2, $a3, $pc, $d, $i);
    mysqli_stmt_execute($stmt);

    // Check the results...
    if (mysqli_stmt_affected_rows($stmt) == 1) {

        // Print a message:
        echo '<p>The company has been added.</p>';

        // Rename the image:
        $id = mysqli_stmt_insert_id($stmt); // Get the company 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.

Here is the entire code:

<?php
require_once ('../../../mysqli_connect.php');

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

// Validate the incoming data...
$errors = array();

// Check for a company name:
if (!empty($_POST['company_name'])) {
    $cn = trim($_POST['company_name']);
} else {
    $errors[] = 'Please enter the company\'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;
}

// Validate the category...
if (isset($_POST['category']) && ($_POST['category'] == 'new') ) {
    // If it's a new category, add the category to the database...

    // Check for a category name...
    if (!empty($_POST['category_name'])) {

        $catn = trim($_POST['category_name']);

        // Add the category to the database:
        $q = 'INSERT INTO categories (category_name) VALUES (?)';
        $stmt = mysqli_prepare($dbc, $q);
        mysqli_stmt_bind_param($stmt, 's', $catn);
        mysqli_stmt_execute($stmt);

        // Check the results....
        if (mysqli_stmt_affected_rows($stmt) == 1) {
            echo '<p>The category has been added.</p>';
            $catid = mysqli_stmt_insert_id($stmt); // Get the category ID.
        } else { // Error!
            $errors[] = 'The new category could not be added to the database!';
        }

        // Close this prepared statement:
        mysqli_stmt_close($stmt);

    } else { // No category name value.
        $errors[] = 'Please enter the category\'s name!';
    }

} elseif ( isset($_POST['category']) && ($_POST['category'] == 'existing') && ($_POST['existing'] > 0) ) { // Existing category.
    $catid = (int) $_POST['existing'];
} else { // No category selected.
    $errors[] = 'Please enter or select the category\'s name!';
}

if (empty($errors)) { // If everything's OK.

    // Add the company to the database:
    $q = 'INSERT INTO companies (category_id, company_name, image_name) VALUES (?, ?, ?)';
    $stmt = mysqli_prepare($dbc, $q);
    mysqli_stmt_bind_param($stmt, 'iss', $catid, $cn, $i);
    mysqli_stmt_execute($stmt);

    // Check the results...
    if (mysqli_stmt_affected_rows($stmt) == 1) {

        // Print a message:
        echo '<p>The company has been added.</p>';

        // Rename the image:
        $id = mysqli_stmt_insert_id($stmt); // Get the company 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 company image and try again.</p>';
}

// Display the form...
?>

I needed to specify the primary key as auto-increment, in this case it is the company_id field.

A simple way to add detailed error checking is to insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

before the mysqli_connection is made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM