更新表行并使用+ 1增加行数据

时间:2014-01-29 19:36:56

标签: php mysql row

我想为我的网站制作投票脚本,它现在看起来像这样 //输入表格

<form action='votes.php' method='post'>
<input type='hidden' name='buttonUp' value='1'/>
<input type='submit' name='submitVote' value='Vote Up'/>
</form>

处理此

的php文件
isset($_POST['submitVote'])) {  

$sql="INSERT INTO answers 
SET up = '$_POST[buttonUp]',
questionId = (SELECT id FROM quesitons WHERE id = '$_POST[id]');
";

Sql表包含字段id, answer, questionId, user, date, ip, up, down 所以,如果某人喜欢使用特定ID回答,请点击Vote Up,并在提交的UP中更新值+ 1.我几乎没有时间这个,也不知道如何制作。另外我想应该有UPDATE answers SET...但我也尝试过,而且没有... 谢谢

表格问题

CREATE TABLE IF NOT EXISTS `pitanja` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pitanje` text NOT NULL,
  `korisnik` varchar(255) NOT NULL,
  `datum` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

这是表格答案

CREATE TABLE IF NOT EXISTS `answers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `answer` text COLLATE utf8_unicode_ci NOT NULL,
  `questionId` int(11) NOT NULL,
  `user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ip` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `up` int(11) NOT NULL,
  `down` int(11) NOT NULL,
  PRIMARY KEY (`id`)
  ) 

2 个答案:

答案 0 :(得分:1)

首先关闭:

1)切勿将原始用户数据直接插入数据库。 (See here for more info

2)您应该在表单中提供带有问题ID的隐藏字段。


尝试这样的事情:

<form action='votes.php' method='post'>
    <!-- The "questionID" value here (12345) is just an example. -->
    <!-- Substitute the 12345 for the actual ID of this answer. -->
    <input type='hidden' name='questionID' value='12345'/>
    <input type='hidden' name='buttonUp' value='1'/>
    <input type='submit' name='submitVote' value='Vote Up'/>
</form>

则...

isset($_POST['submitVote'])) {  

    // Absolute MINIMUM data santitation here as an example.
    // You should do more. And NOT use msql_* functions as they are deprecated
    $sanitizedQuestionID = mysql_real_escape_string($_POST['questionID']);

    // Edited Query. This one works!
    $sql = "UPDATE `answers`
            SET `up` = up + 1
            WHERE `questionId` = $sanitizedQuestionID;";

答案 1 :(得分:1)

在MySQL方面,您可以利用ON DUPLICATE KEY声明

INSERT子句
INSERT INTO answers (questionId, up) VALUES (?, 1)
ON DUPLICATE KEY UPDATE up = COALESCE(up, 0) + 1

为了使其正常工作,您必须在questionId

上具有UNIQUE约束

这是 SQLFiddle 演示