1我尝试构建产品表单,但记录无法插入数据库中

时间:2019-10-02 08:12:12

标签: php mysql

我使用了this answer中的代码,并根据需要进行了修改,但是查询运行了,但记录无法插入数据库中。

这是我的test.php文件,我使用输入表单(标题,规范,类别,子类别,价格,描述)等来形成表单。

此表单基于将多个图像插入一个产品中。 我从数据库中获取了类别和子类别的名称,

<?php
   include("header.php");
   $con=mysqli_connect("localhost","root","","bakery");
   if(!$con)
   {
       echo mysqli_error($con);
   }
   ?>
<div class="content-page">
<!-- Start content -->
<div class="content">
   <div class="container-fluid">
      <div class="row">
         <div class="col-12">
            <div class="page-title-box">
               <h4 class="page-title float-left">Product Page</h4>
               <div class="clearfix"></div>
            </div>
         </div>
      </div>
      <!-- end row -->
      <div class="row">
         <div class="col-12">
            <div class="card">
               <div class="card-header">
                  <h4 class="m-t-0 header-title mb-0">Add New Product</h4>
               </div>
               <div class="card-body">
                  <div>
            <form class="form-horizontal" action="testWork.php" method="post" enctype="multipart/form-data">
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Product Name</label>
                           <div class="col-10">
                              <input type="text" class="form-control" id="title" name="title" placeholder="Enter  Name" required="required" value="<?php echo isset($productName) ? $productName : ''; ?>" />
                           </div>
                        </div>
                         <div class="form-group row">
                           <label class="col-2 col-form-label">Specification</label>
                           <div class="col-10">
                              <input type="text" class="form-control" id="specification" name="specification" placeholder="Enter  Specification" required="required"  value="<?php echo isset($productSpecification) ? $productSpecification : ''; ?>" />
                           </div>
                        </div>
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Product Price</label>
                           <div class="col-10">
                              <input type="text" class="form-control" id="price" value="Rs." name="price" placeholder="Enter  Price" required="required"  value="<?php echo isset($productQuantity) ? $productQuantity : ''; ?>"/>
                           </div>
                        </div>
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Input Select</label>
                           <div class="col-10">
                              <select name="category" id="category" class="form-control"  value="<?php echo isset($productCategory) ? $productCategory : ''; ?>">
                              <?php
                                 $com=mysqli_query($con,"select * from category");
                                 if(mysqli_num_rows($com)>0)
                                 {
                                     while($row = mysqli_fetch_array($com))
                                     {
                                         echo ("<option value='$row[id]'>$row[category]</option>");
                                     }
                                 }

                                 ?>
                              </select>
                           </div>
                        </div>
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Select Product Sub Category</label>
                           <div class="col-10">
                              <select name="subcategory" id="subcategory" class="form-control" value="<?php echo isset($productSubcategory ) ? $productSubcategory : ''; ?>">
                              <?php
                                 $com=mysqli_query($con,"select * from subcategory");
                                 echo ("<option value=''>Select Sub-Category if you have it</option>");
                                 if(mysqli_num_rows($com)>0)
                                 {
                                     while($row = mysqli_fetch_array($com))
                                     {
                                         echo ("<option value='$row[id]'>$row[subcategory]</option>");
                                     }
                                 }

                                 ?>
                              </select>
                           </div>
                        </div>
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Product Description</label>
                           <div class="col-10">
                              <textarea class="form-control" rows="5" id="description" name="description" placeholder="Enter  Description" required="required" />
                              <?php echo isset($productDescription) ? $productDescription : ''; ?>
                              </textarea>
                           </div>
                        </div>
                        <div class="form-group row">
                           <label class="col-2 col-form-label">Product Photos</label>
                           <div class="col-10">
                              <input type="file" class="form-control" id="file" name="file[]" multiple>
                           </div>
                        </div>
                        <div class="form-group mb-0 justify-content-end row">
                           <div class="col-10">
                              <button type="submit" type="submit" name="submit" id="submit" class="btn btn-info waves-effect waves-light">Submit</button>
                           </div>
                        </div>
                     </form>
                  </div>
               </div>
            </div>
            <!-- end card -->
         </div>
         <!-- end col -->
      </div>
      <!-- end row -->
      <!-- end row -->
   </div>
   <!-- container -->
</div>
<!-- content -->
<!-- jQuery  -->

这是我在后端代码中编写的testWork.php文件。

<?php
// Upload configs.
define('UPLOAD_DIR', 'uploads');
define('UPLOAD_MAX_FILE_SIZE', 5485760); // 10MB.
//@changed_2018-02-17_14.28
define('UPLOAD_ALLOWED_MIME_TYPES', 'image/jpeg,image/png,image/gif');
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'example');
define('USERNAME', 'root');
define('PASSWORD', '');
define('CHARSET', 'utf8');

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 * 
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
$productSaved = FALSE;

if (isset($_POST['submit'])) {
    /*
     * Read posted values.
     */
    $productName = isset($_POST['title']) ? $_POST['title'] : '';
    $productSpecification = isset($_POST['specification']) ? $_POST['specification'] : '';
    $productCategory = isset($_POST['category']) ? $_POST['category'] : '';
    $productSubcategory = isset($_POST['subcategory']) ? $_POST['subcategory'] : '';
    $productQuantity = isset($_POST['price']) ? $_POST['price'] :'';
    $productDescription = isset($_POST['description']) ? $_POST['description'] : '';

    /*
     * Validate posted values.
     */
    if (empty($productName)) {
        $errors[] = 'Please provide a product title.';
    }

    if ($productQuantity == 0) {
        $errors[] = 'Please provide the price.';
    }

    if (empty($productDescription)) {
        $errors[] = 'Please provide a description.';
    }

    /*
     * Create "uploads" directory if it doesn't exist.
     */
    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0777, true);
    }

    /*
     * List of file names to be filled in by the upload script 
     * below and to be saved in the db table "products_images" afterwards.
     */
    $filenamesToSave = [];

    $allowedMimeTypes = explode(',', UPLOAD_ALLOWED_MIME_TYPES);

    /*
     * Upload files.
     */
    if (!empty($_FILES)) {
        if (isset($_FILES['file']['error'])) {
            foreach ($_FILES['file']['error'] as $uploadedFileKey => $uploadedFileError) {
                if ($uploadedFileError === UPLOAD_ERR_NO_FILE) {
                    $errors[] = 'You did not provide any files.';
                } elseif ($uploadedFileError === UPLOAD_ERR_OK) {
                    $uploadedFileName = basename($_FILES['file']['name'][$uploadedFileKey]);

                    if ($_FILES['file']['size'][$uploadedFileKey] <= UPLOAD_MAX_FILE_SIZE) {
                        $uploadedFileType = $_FILES['file']['type'][$uploadedFileKey];
                        $uploadedFileTempName = $_FILES['file']['tmp_name'][$uploadedFileKey];

                        $uploadedFilePath = rtrim(UPLOAD_DIR, '/') . '/' . $uploadedFileName;

                        if (in_array($uploadedFileType, $allowedMimeTypes)) {
                            if (!move_uploaded_file($uploadedFileTempName, $uploadedFilePath)) {
                                $errors[] = 'The file "' . $uploadedFileName . '" could not be uploaded.';
                            } else {
                                $filenamesToSave[] = $uploadedFilePath;
                            }
                        } else {
                            $errors[] = 'The extension of the file "' . $uploadedFileName . '" is not valid. Allowed extensions: JPG, JPEG, PNG, or GIF.';
                        }
                    } else {
                        $errors[] = 'The size of the file "' . $uploadedFileName . '" must be of max. ' . (UPLOAD_MAX_FILE_SIZE / 1024) . ' KB';
                    }
                }
            }
        }
    }

    /*
     * Save product and images.
     */
    if (!isset($errors)) {
        /*
         * The SQL statement to be prepared. Notice the so-called markers, 
         * e.g. the "?" signs. They will be replaced later with the 
         * corresponding values when using mysqli_stmt::bind_param.
         * 
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $sql = 'INSERT INTO products (
                    title,
                    price,
                    specification,
                    category,
                    subcategory,
                    description
                ) VALUES (
                    ?, ?, ? , ?, ?, ?
                )';

        /*
         * Prepare the SQL statement for execution - ONLY ONCE.
         * 
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $statement = $connection->prepare($sql);
        if($statement)
        {
            header('Location: testget.php?id=$lastInsertId');
        }
        else
        {
            echo mysqli_error($connection);
        }

        /*
         * Bind variables for the parameter markers (?) in the 
         * SQL statement that was passed to prepare(). The first 
         * argument of bind_param() is a string that contains one 
         * or more characters which specify the types for the 
         * corresponding bind variables.
         * 
         * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
         */
        $statement->bind_param('sis', $productName, $productQuantity, $productDescription, 
            $productSpecification, $productCategory, $productSubcategory);

        /*
         * Execute the prepared SQL statement.
         * When executed any parameter markers which exist will 
         * automatically be replaced with the appropriate data.
         * 
         * @link http://php.net/manual/en/mysqli-stmt.execute.php
         */
        $statement->execute();

        // Read the id of the inserted product.
        $lastInsertId = $connection->insert_id;

        /*
         * Close the prepared statement. It also deallocates the statement handle.
         * If the statement has pending or unread results, it cancels them 
         * so that the next query can be executed.
         * 
         * @link http://php.net/manual/en/mysqli-stmt.close.php
         */
        $statement->close();

        /*
         * Save a record for each uploaded file.
         */
        foreach ($filenamesToSave as $filename) {
            $sql = 'INSERT INTO products_images (
                        product_id,
                        filename
                    ) VALUES (
                        ?, ?
                    )';

            $statement = $connection->prepare($sql);

            $statement->bind_param('is', $lastInsertId, $filename);

            $statement->execute();

            $statement->close();
        }

        /*
         * Close the previously opened database connection.
         * 
         * @link http://php.net/manual/en/mysqli.close.php
         */
        $connection->close();

        $productSaved = TRUE;

        /*
         * Reset the posted values, so that the default ones are now showed in the form.
         * See the "value" attribute of each html input.
         */
        $productSpecification = $productCategory =$productSubcategory=$productName = $productQuantity = $productDescription = NULL;
    }
}
?>

我的英语不好。请帮助贫困的英语学习者。

这是我的错误消息

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in C:\xampp\htdocs\bakery1\admin_4\testWork.php on line 152

Fatal error: Uncaught mysqli_sql_exception: No data supplied for parameters in prepared statement in C:\xampp\htdocs\bakery1\admin_4\testWork.php:162 Stack trace: #0 C:\xampp\htdocs\bakery1\admin_4\testWork.php(162): mysqli_stmt->execute() #1 {main} thrown in C:\xampp\htdocs\bakery1\admin_4\testWork.php on line 162

1 个答案:

答案 0 :(得分:0)

执行此操作时:

$statement->bind_param('sis', $productName, $productQuantity, $productDescription, $productSpecification, $productCategory, $productSubcategory);

'sis'的意思是:您具有三个分别为String,Integer和String类型的参数。

那么,如果有3个参数,它会“ sis”吗?

您要做的是使用“ sisssss”代替“ sis”。我假设productSpecification,productCategory,productSubCategory是字符串