更新mysql记录以在单击循环按钮时添加计数

时间:2017-06-12 21:24:55

标签: php mysql

我有一个表单,使用mysql while循环显示候选人的详细信息,每个候选人下面是"投票"按钮也在循环内。单击按钮时,我需要将1count添加到记录中。我的问题是循环内的按钮具有相同的名称,因此即使只有一个按钮,它们也会受到更新的影响。

if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 

                $sql = "SELECT ename FROM election_title ORDER BY `sdate` ASC";
                $result = $conn->query($sql);
                if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $ename= $row['ename'];
        ?> 
            <p><font size= "6px" align = "center" color = "#efbf77"> <?php echo $row['ename']. "<br>";?></p>
        <?php


            $sql = "SELECT * FROM candidate_list T1 INNER JOIN election_title T2 ON T1.ename = T2.ename WHERE T1.ename LIKE '%$row[ename]%';";
            $res = $conn->query($sql);
            if ($res->num_rows > 0) {
                while($rowval = $res->fetch_assoc())  {
                    $id= $rowval['id'];
                    $image_content= $rowval['image_content'];
                    $ename= $rowval['ename'];
                    $pos= $rowval['pos'];
                    $fname= $rowval['fname'];
                    $mname= $rowval['mname'];
                    $lname= $rowval['lname'];

        ?> 

                <div class = "cand">
                <?php echo '<img src="data:image/jpeg;base64,' . base64_encode( $rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>
                 <form action="castvote.php" method="post">
                 <INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>">
                </div>
        <?php
        }
            } else {
            echo "No candidate(s) listed.";
        }

        ?>
        <?php
        }
            } else {
            echo "0 results";
        }
        ?>

这是我的疑问。

<html>
<head>
    <title>NSDCI Voting System</title>
    <link rel="stylesheet" href="css/style.css">
</head>
    <?php
        $host = 'localhost';
        $user = 'root';
        $pass = '';
        $db = 'voting_system';

        $fname = $_POST['fname'];
        $con = mysqli_connect($host, $user, $pass, $db);
        if($con)
        {

        $sql = "UPDATE candidate_list SET votes = votes +1 WHERE fname = $fname";
        $query = mysqli_query($con, $sql);

        if($query)
        echo 'data inserted succesfully';
        }

            echo 'connected succesfully to the db!';

    ?>

如何查询与我的按钮名称匹配的WHERE子句。提前致谢

2 个答案:

答案 0 :(得分:0)

我正在更改代码的以下部分。

KnoxKioskMode = KnoxKioskMode ?? KnoxKioskMode.GetInstance(context);
var knoxKioskSettings = new KioskSetting
{
    SystemBar = true,
    HomeKey = false,
    StatusBarExpansion = false,
    StatusBar = true,
    NavigationBar = false,
    MultiWindow = false,
    SettingsChanges = true,
    WipeRecentTasks = false,
    AirView = false,
    SmartClip = false,
    AirCommand = false,
    BlockedEdgeFunctions = KnoxKioskMode.EdgeFunctionAll
};

KnoxKioskMode.EnableKioskMode(knoxKioskSettings);
KnoxKioskMode.AllowHardwareKeys(DisabledKeys, false);

// This does not work as the system bar is still hidden.
KnoxKioskMode.HideSystemBar(false);
KnoxKioskMode.HideStatusBar(false);

尝试考虑不使用表单的想法。您可以使用带动作脚本的超链接。通过URL传递所选候选者的目标表中的AutoIncrement值。在此之后,使用<div class = "cand"> <?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?> <form action="castvote.php" method="post"> <INPUT TYPE=submit NAME="<?php echo $fname; ?>" VALUE="<?php echo 'Vote ' .$fname; ?>"> </div> 获取操作脚本中的值并执行更新。要确保不直接访问操作脚本,请添加$_GET验证。以下是代码。

isset($_GET)

现在,在您的操作脚本中,使用以下代码。

<div class = "cand">
    <?php echo '<img src="data:image/jpeg;base64,' . base64_encode($rowval['image_content'] ) . '" width = "100%" height = "auto" />';?><?php echo "<p class = 'bold'>" .$rowval['fname']. " " .$rowval['mname']. " " .$rowval['lname'] . "</p>" .$rowval['pos']. "<br/>" .$rowval['pname'];?>

    //I am changing your code here.

    <a href="castvote.php?id=<?php echo $auto_increment_value; ?>">Vote <php echo $fname; ?></a>
</div>

希望这有帮助。

答案 1 :(得分:0)

一种方法是为每个按钮分配dataset属性 - 例如data-id=$rowval['id']并使用javascript读取该数据集值并发送ajax请求或提交带有该值的表单。你不需要为每个候选人提供一个表格 - 一个表格应该足够并改变一个隐藏字段的值。

大概fname表示forenamefirstname - 如果是这样,那么这不是在更新语句中使用的好项目,特别是如果候选人的名字是John,例如可能很多。由于数据库中的每个候选人都有他/她自己的ID,因此使用该ID进行更新是有意义的,因为保证(?)是唯一的。

<html>
    <head>
        <title>vote</title>
        <script>
            document.addEventListener('DOMContentLoaded',function(e){
                var form=document.forms['vote'];
                var bttns=document.querySelectorAll('input.candidate');
                for( var n in bttns )if( bttns[ n ].nodeType==1 )bttns[ n ].addEventListener('click',function(e){
                    form['id'].value=this.dataset.id;
                    form.submit();
                }.bind(bttns[n]),false);
            },false);
        </script>
    </head>
    <body>
        <form id='vote' action="castvote.php" method="post">
            <input type='hidden' name='id' />
        </form>

        <?php

            if ( $conn->connect_error )exit('unable to connect to database');
            /*
                not sure about the query but there should be no need to use nested queries in a loop
                when a join or a selection as below should suffice.
            */
            $sql="select * from `candidate_list` c 
                inner join `election_title` e on c.`ename` = e.`ename` 
                where c.`ename` in ( select distinct `ename` from `election_title` );";


            $res = $conn->query( $sql );
            if( $res->num_rows > 0 ) {

                while( $rs = $res->fetch_object() ){
                    $id=$rs->id;
                    $pos=$rs->pos;
                    $image=$rs->image_content;
                    $ename=$rs->ename;
                    $fname=$rs->fname;
                    $mname=$rs->mname;
                    $lname=$rs->lname;
                    $pname=$rs->pname;

                    echo "
                        <div class='cand'>
                            <img src='data:image/jpeg;base64," . base64_encode( $image ) . "' />
                            <p class='bold'>
                                {$fname}{$mname}{$lname}
                            </p>{$pos}
                            <br/>
                            {$pname}
                            <input type='button' data-id='{$id}' class='candidate' value='Vote for {$fname}' />
                        </div>";
                }
            }

        ?>

    </body>
</html>

使用上述方法意味着更新数据库的PHP代码需要更改为使用ID(即:$ _POST ['id'])

$sql = "UPDATE candidate_list SET votes = votes+1 WHERE id='{$_POST['id']';";

我意识到代码很容易被sql注入 - 准备好的语句是前进的方法。

在发布我的答案之后我注意到的一件事是base64_encode( $image )行 - 如果这是来自db,那么我想那将是图像的路径而不是RAW数据?如果是这种情况,该行应该是base64_encode( file_get_contents( $image ) )

回应关于不安全代码的有效评论 - 如何使用预准备语句来缓解sql inection。

<?php
    session_start();
?>
<!doctype html>
<html>
    <head>
        <title>NSDCI Voting System</title>
        <link rel='stylesheet' href='css/style.css'>
    </head>
    <body>
        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['id'] ) ){

                $dbhost =   'localhost';
                $dbuser =   'root'; 
                $dbpwd  =   'xxx'; 
                $dbname =   'voting_system';
                $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

                $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );

                $sql='update `candidate_list` set `votes` = `votes`+1 where `id`=?';
                $stmt=$db->prepare( $sql );

                if( $stmt && $id ){

                    $stmt->bind_param( 's', $id );
                    $result=$stmt->execute();

                    echo $result ? 'data inserted succesfully' : 'oops';
                }
            }
        ?>
    </body>
</html>