php post删除按钮

时间:2017-01-28 01:23:45

标签: php mysql button

嗨,我有一个while循环,打印出来自表用户的所有用户名,名称等,但我需要的是一个按钮,可以运行查询,删除该行上的用户ID,所以基本上在最后对于每个用户的行,应该有一个删除按钮,该按钮仅删除该用户但不刷新页面。到目前为止我有这个

# text_dcnn.py

import tensorflow as tf

class TextDCNN(object):

"""
A CNN for NLP tasks. Architecture is as follows:
Embedding layer, conv layer, max-pooling and softmax layer
"""

def __init__(self, sequence_lengths, num_classes, vocab_size, embedding_size, filter_sizes, num_filters):
    """
    Makes a new CNNClassifier
    Args:
        sequence_length: The length of each sentence
        num_classes: Number of classes in the output layer (positive and negative would be 2 classes)
        vocab_size: The size of the vocabulary, needed to define the size of the embedding layer
        embedding_size: Dimensionality of the embeddings
        filter_sizes: Number of words the convolutional filters will cover, there will be num_filters for each size
        specified.
        num_filters: The number of filters per filter size.

    Returns: A new CNNClassifier with the given parameters.

    """
    # Define the inputs and the dropout
    self.max_length = max([l for l in sequence_lengths])

    self.input_x = tf.placeholder(tf.int32, [None, self.max_length], name="input_x")
    self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
    self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

    # Runs the operations on the CPU and organizes them into an embedding scope
    with tf.device("/cpu:0"), tf.name_scope("embedding"):
        W = tf.Variable(  # Make a 4D tensor to store batch, width, height, and channel
            tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
            name="W"
        )

        self.embedded_chars = tf.nn.embedding_lookup(W, self.input_x)
        self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)

    pooled_outputs = []
    for i, filter_size in enumerate(filter_sizes):
        with tf.name_scope("conv-maxpool-%s" % filter_size):
            # Conv layer
            filter_shape = [filter_size, embedding_size, 1, num_filters]
            # W is the filter matrix
            W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
            b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
            conv = tf.nn.conv2d(
                self.embedded_chars_expanded,
                W,
                strides=[1, 1, 1, 1],
                padding="VALID",
                name="conv"
            )

            # Apply nonlinearity
            h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")

            # Max-pooling layer over the outputs
            pooled = tf.nn.max_pool(
                h,
                ksize=[1, sequence_lengths[i] - filter_size + 1, 1, 1],
                strides=[1, 1, 1, 1],
                padding="VALID",
                name="pool"
            )
            pooled_outputs.append(pooled)

    # Combine all of the pooled features
    num_filters_total = num_filters * len(filter_sizes)

    pooled_outputs = [tf.reshape(out, [-1, 94, 1, self.max_length]) for out in pooled_outputs]

    self.h_pool = tf.concat(3, pooled_outputs)

    # self.h_pool = tf.concat(3, pooled_outputs)
    self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])

    # Add dropout
    with tf.name_scope("dropout"):
        # casted = tf.cast(self.dropout_keep_prob, tf.int32)
        self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)

    # Do raw predictions (no softmax)
    with tf.name_scope("output"):
        W = tf.Variable(tf.truncated_normal([num_filters_total, num_classes], stddev=0.1), name="W")
        b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
        # xw_plus_b(...) is just Wx + b matmul alias
        self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
        self.predictions = tf.argmax(self.scores, 1, name="predictions")

    # Calculate mean cross-entropy loss
    with tf.name_scope("loss"):
        # softmax_cross_entropy_with_logits(...) calculates cross-entropy loss
        losses = tf.nn.softmax_cross_entropy_with_logits(self.scores, self.input_y)
        self.loss = tf.reduce_mean(losses)

    # Calculate accuracy
    with tf.name_scope("accuracy"):
        correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
        self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

但我遇到的问题是,如果我把这行代码:

while($row = mysql_fetch_array($theuser)){
    $accid = $row["account_id"];
    echo '<tr><td>'.$row["username"].'</td>
                        <td>'.$row["name"].'</td>
                        <td>'.$row["l_name"].'</td>
                        <td>'.$row["email"].'</td>
                        <td>'.$row["phone"].'</td>
                        <td><form action="" method="post" >
                        <input class="button" type="submit" name="submitdelete" value="delete"></form></td></tr>';}

在while循环中,它将删除所有用户。如果我把它放在while循环之外它就不会得到id。

有没有办法例如写输入的名称,如: name =“submitdelete34”和34表示用户的id,因此在while循环中它的编码如下:

if(isset($_POST['submitdelete'])){
    mysql_query("Delete from users where account_id='$accid'");
}

并使其发挥作用。

请帮帮我

2 个答案:

答案 0 :(得分:1)

让它变得更容易。让我们添加一个隐藏的输入:

<input type="hidden" name="account_id" value="<?php echo $accid;?>">
<input class="button" type="submit" name="submitdelete" value="delete">

现在在你的php中你可以获得id:

$connection = mysqli_connect("my_host", "my_user", "my_password", "my_db");

// simple error handler
if (!$connection){
    echo "SQL connection failed: ". mysqli_error($connection);
    exit;
}

if(isset($_POST['submitdelete'])){
    $acctid = (int) $_POST['account_id'];// <-- gotta protect from sql injection.
    mysqli_query($connection, "Delete from users where account_id='$accid'");
}

<强> BUT:

更好的解决方案是不删除记录。你桌子上的一个字段可以叫做“活跃”字样。并且您可以将其设置为TINYINT。通过这种删除记录的方式,您可以设置active=0

如果您误删了,可以随时将其重新设置为active=1

注意我使用了mysqli_而不是mysql_。您需要将代码全部更新为mysqli_,因为the other is deprecated。它已从较新版本的php中删除

答案 1 :(得分:-1)

使用mysql_fetch_assoc

while($row = mysql_fetch_assoc($theuser)){
    echo '<tr><td>'.$row["username"].'</td>
          <td>'.$row["name"].'</td>
          <td>'.$row["l_name"].'</td>
          <td>'.$row["email"].'</td>
          <td>'.$row["phone"].'</td>
          <td><form action="" method="post" >
          <input type="hidden" name="accid" value="'.$row["account_id"].'" />
          <input class="button" type="submit" name="submitdelete" value="delete"></td></tr>';
}
echo "</form>";

动作php脚本:

if($_POST['submitdelete']=='delete'){
    mysql_query("delete from users where account_id='{$_POST["accid"]}'");
}