Почему эта форма PHP не работает? - PullRequest
0 голосов
/ 23 июня 2011

Почему эта форма не отправляет выбранную категорию в mysql?

Я новичок в теге <select> ... http://www.pastie.org/2110032

<?php
require_once('../../includes/initialize.php');


if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>

<?php 
$max_file_size = 1048576;

if(isset($_POST['submit'])){
    $product = new Product();
    $product->caption = $_POST['caption'];
    $product->category = $_POST['category'];
    $product->attach_file($_FILES['file_upload']);
    if($product->save()) {
        $session->message("product uploaded successfully.");
        redirect_to('list_products.php');
    } else {
        $message = join("<<br />", $product->errors);
    }
}
?>

<?php include_layout_template('admin_header.php'); ?>

<h2>Product Upload</h2>

<?php echo output_message($message); ?>

<form action="product_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size;?>" />
<p><input type="file" name="file_upload" /></p>
<p>Caption: <input type="text" name="caption" value="" /></p>
<p>Category: 
<select name="category">
<option value="Pins">Pins</option>
<option value="Busings">Bushings</option>
<option value="Miscellaneous">Miscellaneous</option>
<option value="Ejector Sleeves">Ejector Sleeves</option>
<option value="Polishing">Polishing</option>
<option value="End Mills">End Mills</option>
</select></p>
<input type="submit" name="submit" value="Upload" />
</form>

<?php include_layout_template('admin_footer.php'); ?>

с настройкой таблицы моего продукта следующим образом:

mysql> describe products;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| category | varchar(255) | NO   |     | NULL    |                |
| filename | varchar(255) | NO   |     | NULL    |                |
| type     | varchar(100) | NO   |     | NULL    |                |
| size     | int(11)      | NO   |     | NULL    |                |
| caption  | varchar(255) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)



public function create() {
        global $database;
        $attributes = $this->sanitized_attributes();
        unset($attributes['id']);

      $sql = "INSERT INTO ".self::$table_name." (";
        $sql .= join(", ", array_keys($attributes));
      $sql .= ") VALUES ('";
        $sql .= join("', '", array_values($attributes));
      $sql .= "')";
        if($database->query($sql)) {
        $this->id = $database->insert_id();
        return true;
      } else {
        return false;
      }
    }

protected static $table_name="products";
    protected static $db_fields=array('id', 'category','filename', 'type', 'size', 'caption');
    public $id;
    public $category;
    public $filename;
    public $type;
    public $size;
    public $caption;

Функция сохранения продукта:

public function save() {
        // A new record won't have an id yet.
        if(isset($this->id)) {
            // Really just to update the caption
            $this->update();
        } else {
            // Make sure there are no errors

            // Can't save if there are pre-existing errors
          if(!empty($this->errors)) { return false; }

            // Make sure the caption is not too long for the DB
          if(strlen($this->caption) >= 255) {
                $this->errors[] = "The caption can only be 255 characters long.";
                return false;
            }
            if(strlen($this->category) >= 255) {
                $this->errors[] = "The category can only be 255 characters long.";
                return false;
            }

          // Can't save without filename and temp location
          if(empty($this->filename) || empty($this->temp_path)) {
            $this->errors[] = "The file location was not available.";
            return false;
          }

            // Determine the target_path
          $target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;

          // Make sure a file doesn't already exist in the target location
          if(file_exists($target_path)) {
            $this->errors[] = "The file {$this->filename} already exists.";
            return false;
          }

            // Attempt to move the file 
            if(move_uploaded_file($this->temp_path, $target_path)) {
            // Success
                // Save a corresponding entry to the database
                if($this->create()) {
                    // We are done with temp_path, the file isn't there anymore
                    unset($this->temp_path);
                    return true;
                }
            } else {
            $this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
            return false;
            }
        }
    }

Ответы [ 2 ]

2 голосов
/ 23 июня 2011

Вы должны изолировать, где это идет не так.

а) между вашей HTML-формой и PHP? используйте

var_dump($_POST);

б) между PHP и классом, который вы используете? использовать

var_dump( $product );

в) между вашим классом и sql dbal?

echo $sql;

d) что-то не так с этим sql, который вы не смогли обнаружить?

look at the last entry in your sql log file

Или включите ведение журнала mysql http://dev.mysql.com/doc/refman/5.0/en/server-logs.html

0 голосов
/ 23 июня 2011

Вы получаете какие-либо ошибки вообще?Перенаправление может произойти сбой, потому что у вас есть пустая строка между разделами php, которые включают перенаправления.Вы сделали print_r переменных $ POST, чтобы проверить, являются ли значения такими, как вы думаете?Помимо $ product-> save (), поскольку для этого нет видимого кода, подтвердили ли вы, что sql его формирование корректно и выполняется без ошибок?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...