当输入为空时,phpmyadmin不使用DEFAULT值

时间:2016-12-02 23:10:44

标签: php mysql

我有这个问题,如果我将'Title'的输入留空,那么它将不会设置默认值:“Untitled”发送到数据库时。我已经在线查看并确保我的设置在phpmyadmin中是正确的,但它仍然不会设置默认值。任何建议都表示赞赏!

以下是“标题”列的PHPmyadmin设置:

enter image description here

这些是我的文件:

addart.php

<form method="post" action="addtodb.php">

  <label for="Title">
     <h4>Title</h4>
  </label>

  <input class="u-full-width" 
         type="text" 
         placeholder="Title of art" 
         id="Title"
         name="Title">

</form>

addtodb.php

<?php

if($_SERVER['REQUEST_METHOD'] == "POST") {

$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';

$dbConnection = new mysqli($host, $user, $pass, $db);

if (mysqli_connect_errno()) {
    printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
    exit();
}

if($_POST) {

    $artwork = $_POST["Artwork"];
    $medium = $_POST["Medium"];
    $artist = $_POST["Artist"];
    $title = $_POST["Title"];

    $results = $dbConnection->query("INSERT INTO art 
                                   (Artwork, Title, Artist, Medium) VALUES      
                               ('$artwork','$title','$artist','$medium');");

    if (!$results) {
        echo 'Unable to insert into database.';
        exit();
    } else {
        echo 'Successfully added!';
    }

    mysqli_close($dbConnection);
    header("Location: galleryonly.php"); /* Redirect browser */
    exit();
}
?>

3 个答案:

答案 0 :(得分:2)

$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];

if(!empty($title)) {
   $sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
   $sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}

$results = $dbConnection->query($sql);

您可以试用此代码。

如果您要删除该列,则会设置默认值。

因为您只有一列具有默认值,所以您可以坚持使用此代码。

如果您有多个具有默认值的列,则需要根据您的要求进行更改。

答案 1 :(得分:1)

您前面有一些技巧,因为如果您需要默认值,您将无法使用标题列。

// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';

// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');

// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');

foreach ($cols as $i=>&$col) {
  $var = ${$vars[$i]};
  if ($col == 'Title') {
    if (empty($var)) {
      // don't add this column if empty
      continue;
    }
  }
  // otherwise (if not Title)
  // add it to a column = "value" insert string
  $pcs[] = "`$col` = '$var'";
}

// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);

答案 2 :(得分:0)

中始终使用小写字母
<input class="u-full-width" 
         type="text" 
         placeholder="Title of art" 
         id="Title"
         name="title">