繁体   English   中英

使用mysql查询作为条件

[英]Using mysql query as a condition

我在mySQL数据库中有一个表,在其中放置了使用php从android应用程序中检索到的值。 现在该值是一个UniqueID,因此我要对其进行计数,以便我可以知道我的应用程序被访问了多少次。 当一个新的UniqueID到达时,它将以count = 1的方式添加到数据库中,而当一个现有的UniqueID被取消时,其计数将简单地增加。 我多次尝试了我的php脚本,但是没有运气。 我附上我的PHP脚本以供参考。

<?php


ini_set('default_charset', 'utf-8');
header('Content-Type: text/html; charset=UTF-8');
$n=$_POST['UniqueID'];  
$count=1;  
$Today=date("F j, Y, g:i a");

mysql_connect("localhost","root","");  
mysql_select_db("farm-o-pedia");

$con="select userid from uniqueid";  
$result=mysql_query($con) or die(mysql_error());  
if($result=$n)  
{  

$upd="update uniqueid set count=count+1 where userid=$n";  
$result=mysql_query($upd) or die(mysql_error());  
}  
else  {  
$que="insert into uniqueid (userid,count,date) values($n,\"$count\",\"$Today\")";    
$sql=mysql_query($que) or die(mysql_error());  
}

mysql_close();
?>

任何帮助将不胜感激。谢谢!

另一种方法是利用MySQL的ON DUPLICATE KEY UPDATE

首先要做的是在列userid上定义UNIQUE约束( 如果它是PRIMARY KEY,则跳过此步骤。 ),

ALTER TABLE uniqueid ADD CONSTRAINT tb_uq UNIQUE (userid)

执行查询后, ON DUPLICATE KEY UPDATE现在可以正常工作。

您将没有SELECT和其他IF

INSERT INTO UNIQUEID (userID `count`, date)
VALUES ('idHere', 0, NOW())
ON DUPLICATE KEY 
UPDATE `count` = `count` + 1;

mysql_query返回一个结果集 ,而不是单个结果,因此:

$con="select userid from uniqueid";  
$result=mysql_query($con) or die(mysql_error());  
if($row=mysql_fetch_assoc($result)) { //if a row is found in resultset, then you already have this id in your table
    $upd="update uniqueid set count=count+1 where userid=$n";  
    $result=mysql_query($upd) or die(mysql_error());  
} else {  
    $que="insert into uniqueid (userid,count,date) values($n,\"$count\",\"$Today\")";    
    $sql=mysql_query($que) or die(mysql_error());  
}

另外,您应该开始使用mysqli函数而不是mysql,因为不推荐使用mysqli函数

查看if($result=$n) -这将永远行不通。 比较运算符的一部分是== not = ,结果字符串也包含查询结果而不是单个值。

将行替换为:

if (mysql_num_rows($result)===1)  

其次,您应该真正着眼于转义查询,最好从使用不推荐使用的mysql_ *函数更改为PDO或mysqli。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM