如何使用php创建查询

时间:2015-11-05 13:37:08

标签: php mysql

我尝试使用php下拉列表查询后获取列表。 我的代码现在看起来像这样:          

     $con = mysql_connect($server,$user_name,$password,$database);
     $db_found = mysql_select_db($database, $con);
     if ($db_found) {
     print "Database Found ";
     }
     else {
     print "Database NOT Found ";
     }

     $result = mysql_query($con,$db_found,"SELECT
     connection_log.user,count(*)  
     as 'connection_count', sum(TIMESTAMPDIFF(MINUTE,
     connection_log.logondate,connection_log.logoffdate)) 
     as `connection_time`
     FROM connection_log 
     INNER JOIN users 
     ON connection_log.user=users.user WHERE users.groups 
     LIKE '%cpg_sirket_dyo%' 
     and connection_log.logondate>='2015-09-01 00:00:00' 
     and connection_log.logoffdate<'2015-10-01 00:00:00' 
     group by connection_log.user 
     order by connection_count desc");
     while ($row = mysql_fetch_array($result)) {  
     echo $row['name']."<br />";  
     } 

但是当我运行这个php时,我会收到如下所示的错误:

  

找到数据库PHP警告:mysql_query()最多需要2个参数,3>在第22行的/var/www/html/test.php中给出   PHP警告:mysql_fetch_array()期望参数1为资源,null&gt;在第23行的/var/www/html/test.php中给出

你有什么想法吗?

4 个答案:

答案 0 :(得分:2)

mysql_query

  

mysql_query(string $ query [,resource $ link_identifier = NULL])

只需要两个参数

1)您的查询。

2)MySQL连接

您只需删除查询和连接的mysql_query 也交换位置中的数据库名称

 $result = mysql_query("SELECT....",$con);
  

在列名和表名中使用反引号而不是引号

纠正你的问题
     SELECT
     connection_log.user,count(*)  
     as `connection_count`, sum(TIMESTAMPDIFF(MINUTE,
     connection_log.logondate,connection_log.logoffdate)) 
     as `connection_time`
     FROM connection_log 
     INNER JOIN users 
     ON connection_log.user=users.user WHERE users.groups 
     LIKE '%cpg_sirket_dyo%' 
     and connection_log.logondate>='2015-09-01 00:00:00' 
     and connection_log.logoffdate<'2015-10-01 00:00:00' 
     group by connection_log.user 
     order by connection_count desc
  

注意: - 不推荐使用mysql而是使用mysqli或PDO

答案 1 :(得分:1)

您需要从函数中删除此$ db_found:

http://php.net/manual/en/function.mysql-query.php

$result = mysql_query($yourQuery,$con);

还尝试使用mysqli而不是不推荐使用的mysql。

MySQL vs MySQLi when using PHP

答案 2 :(得分:1)

查看http://php.net/manual/en/function.mysql-query.php

只有2个参数,查询和(optinal)连接,所以你必须使用:

$result = mysql_query("SELECT ...", $con);

答案 3 :(得分:1)

使用以下代码,

$con = mysql_connect($server,$user_name,$password);
     $db_found = mysql_select_db($database);
     if ($db_found) {
     print "Database Found ";
     }
     else {
     print "Database NOT Found ";
     }

     $result = mysql_query("YOUR QUERY",$con);
     while ($row = mysql_fetch_array($result)) {  
     echo $row['name']."<br />";  
     }