dongpiansui8755 2016-12-02 15:10
浏览 15
已采纳

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

I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!

Here are my PHPmyadmin settings for the "Title" column:

enter image description here

These are my files:

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
", 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条回答 默认 最新

  • doubianyan9749 2016-12-02 15:35
    关注
    $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);
    

    You can try out this code.

    If you're omitting the column, the default value will be set.

    Because you have only one column with default value, you can stick with this code.

    If you have more than one column with default value, you will need to make changes according to your requirements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部