HTML表单没有按预期填充MySQL DB

时间:2017-11-10 16:20:43

标签: php html mysql

当我将表单从html保存到php并最终将其存储在MySQL中的某个位置时,保存var=,包括=之后的内容

这是我的HTML:

   <form action="searchResultsSave.php" method="POST">
     What are we looking for? <input type="text" name="searchVar" />
     <input type="submit" value="Submit">
   </form>

Php:

    $searchVar = file_get_contents('php://input');

    $sql = "INSERT INTO g_information(searchVar) VALUES ('$searchVar')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

最后我在mysql中的输出是:&#34; searchVar = cars&#34;什么时候应该只是&#34;汽车&#34;。

你认为我哪里出错?

2 个答案:

答案 0 :(得分:1)

class Customer(db.Model):
    __tablename__ = 'customers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)

    def get_url(self):
        return url_for('get_customer', id=self.id, _external=True)

    def export_data(self):
        return {
            'self_url': self.get_url(),
            'name': self.name
        }

    def import_data(self, data):
        try:
            self.name = data['name']
        except KeyError as e:
            raise ValidationError('Invalid customer: missing ' + e.args[0])
        return self


@app.route('/customers/', methods=['GET'])
def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.paginate(page=1, per_page=1)]})

@app.route('/customers/<int:id>', methods=['GET'])
def get_customer(id):
    return jsonify(Customer.query.get_or_404(id).export_data())

应该是

$searchVar = file_get_contents('php://input'); 

这样您就可以获得搜索字词的值。

答案 1 :(得分:1)

您应该从表单

中读取输入变量
    <?php
    $_POST["searchVar"];
    ?>

然后对输入进行一些验证,确保没有输入非法字符,并且数据可以安全存储在MySQL数据库中

    <?php
    $_POST['searchVar'] = filter_var($_POST['searchVar'], FILTER_SANITIZE_STRING);
    $sql = "INSERT INTO g_information(searchVar) VALUES ("'.$_POST['searchVar'].'")"; 
    ?>