是否可以将 sql 计数结果分配给 php 变量? [英] Is it possible to get a sql count result assign to a php variable?

查看:36
本文介绍了是否可以将 sql 计数结果分配给 php 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在网上查找了一种将 MySQL 查询计数结果转换为整数以供我分配为 php 变量的方法,我找到了几个不同的链接,并阅读了多个文档.他们似乎都没有完全涵盖我想要的.例如:

So I have looked online about finding a way to convert a MySQL query count result into an integer for me to assign as a php variable, I had found several different links, and have read multiple documentation. None of them seem to cover exactly what I want. For example:

//code for connecting to database
$query = "SELECT COUNT(*) FROM `user_table` WHERE `username` = 'John12'";
$result = mysql_query($query);
if(!$result) die($db->error);

现在上面的代码运行查询后应该返回1,如果用户名字段是唯一的并且该查询结果将只有一个实例.另一个例子:

Now the code above after running the query should return 1, in the case that the username field is unique and there will only be one instance of that query result. Another example:

//code for connecting to database
$query = "SELECT COUNT(*) FROM `user_table` WHERE `username` = 'John12' AND `username` = 'Paula25'";
$result = mysql_query($query);
if(!$result) die($db->error);

现在运行查询后上面的代码应该返回 2.我遇到的问题是将结果分配给一个 php 变量.它总是说无法将 mysql_result 转换为 int.我也看过很多关于这方面的论坛,但没有一个成功地帮助过我.我在网上发现 MariaDB 为计数查询返回 BIGINT 类型.我希望能够做这样的事情:

Now the code above after running the query should return 2. What I been having trouble with is assigning the result to a php variable. It always says something about unable to convert mysql_result into int. I have seen plenty of forums on this as well, and none have successfully helped me. I have found online that the MariaDB return a BIGINT type for the count query. I would like to be able to do something like this:

$count = $result->result;
if($count < 2) { 
  // do this if true
} else {
  // do this
}

推荐答案

你可以使用 mysql_fetch_row :

//code for connecting to database
$query = "SELECT COUNT(*) FROM `user_table` WHERE `username` = 'John12' OR `username` = 'Paula25'";
$result = mysql_query($query);
if(!$result) die($db->error);    

$row = mysql_fetch_row($result);

$count = $row[0];

if($count < 2) { 
  // do this if true
} else {
  // do this
}

正如@mith 在评论中提到的,如果你刚刚开始你的项目,使用 mysqli 比使用 mysql 更好.阅读此内容:使用 PHP 时的 MySQL 与 MySQLi

As @mith mentioned in comment, if you just starting your project, better using mysqli than mysql. Read this : MySQL vs MySQLi when using PHP

这篇关于是否可以将 sql 计数结果分配给 php 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆