【问题标题】:mysql/php increase number or insert not workingmysql/php 增加数量或插入不起作用
【发布时间】:2013-08-29 09:38:08
【问题描述】:

我有这个代码:

$q = $_GET['q'];
$results= mysql_query("SELECT number FROM words WHERE keyword='$q'") or 

die(mysql_error());;
if($results){
mysql_query("UPDATE words SET number = number + 1 WHERE keyword='$q'") or die(mysql_error());
}
else{
mysql_query("INSERT INTO words VALUES ('$q', '1', '$d')") or die(mysql_error());    
}

我有桌子words:

+--------+--------+-- -----+
|keyword |number  |date    |
+--------------------------+
|one     |1       |01-01-01|
+--------------------------+

$qone 时,数字增加1 但是当$q 其他词什么都没有发生。我希望当$q 不在关键字列表中时进行注册,并且如果$q 在关键字列中,则数字增加1。“如果单词存在”有效,但“如果不存在”则无效不行…… 请帮忙!谢谢!

【问题讨论】:

  • $results 只有在出现阻止第一个查询运行的错误时才会为假。没有找到任何匹配的行不是错误。使用mysql_num_rows() 找出找到了多少行。
  • 感谢您的建议,我会努力的!
  • keyword 字段是否有唯一索引?如果是这样,您可以将INSERTON DUPLICATE KEY 选项一起使用。
  • 你可以用'$d'代替NOW()
  • 如果没有匹配的行,$row_num 将为 0?

标签: php mysql datatable count


【解决方案1】:

假设keyword是表的主键,则一次查询即可:

INSERT INTO words (keyword, number, date)
VALUES ('$q', 1, '$d')
ON DUPLICATE KEY UPDATE number = number + 1

【讨论】:

  • 我正在使用 phpmyadmin,当我尝试将其设为主键时出现此错误:#1170 - BLOB/TEXT column 'keyword' used in key specification without a key length
  • 不要使用文本,使用 varchar。在文本列上使用索引是有限制的。
  • 我把它变成了 varchar,但现在它说:这不是一个数字
  • 您必须在定义 char 或 varchar 列时指定最大大小,例如varchar(32)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多