dounou9751 2017-06-03 15:47
浏览 26

POST方法不将数据插入数据库表

I'm trying to play around with databases and inserting data dynamically with php. At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

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

<label for="name">Name</label>
<input type="text" name="name" required>

<label for="breed">Breed</label>
<input type="text" name="breed">

<label for="age">Age</label>
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>

connect.php:

<?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>
  • 写回答

3条回答 默认 最新

  • dongyu2047 2017-06-03 15:48
    关注

    Change if('submit') {

    TO

    if(isset($_POST['submit'])){//check if it is set
    
    }
    

    Also change this line:

    $newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');

    TO

    $newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable

    Your code is very well vulnerable to SQL injection

    Using prepared statements,

    $stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $breed, $age);
    if($stmt->execute() == true){
       echo 'Saved';
    } else {
       echo 'Error '. $stmt->error;
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题