根据从SQL查询返回的行数返回值

时间:2013-05-10 02:42:47

标签: php sql

我是PHP和SQL的新手,我正在尝试编写一个函数,如果SQL查询返回至少一个结果,它将返回true。

到目前为止我所拥有的是

function isNew($canNum)
  {
  connectToDatabase();

   SELECT COUNT(*) as cnt FROM
   FROM 'cans' c
   WHERE c.date >= DATE_SUB(NOW(), INTERVAL 1 DAY)
   AND c.canId = '$canNum';

  disconnectDatabase();
  //return true if above returns a row

  disconnectDatabase();
  }

我的问题是如何进行返回,因为计数不是我可以执行的php变量<与。比较。

5 个答案:

答案 0 :(得分:1)

function isNew($canNum)
  {
if (count(mysql_fetch_assoc(mysql_query("
   SELECT COUNT(*) as cnt FROM
   FROM 'cans' c
   WHERE c.date >= DATE_SUB(NOW(), INTERVAL 1 DAY)
   AND c.canId = '$canNum';
")))>0)
{
return true;
}
else
{
return false;
}
  }

答案 1 :(得分:1)

您可能需要在代码中使用其中一个php函数

<?php

$q = mysql_query("your query here!")

if($q = mysql_num_row() > 1 ){
//your code
}

?>

答案 2 :(得分:1)

<?php
    function isNew($canNum)
    {
    $con=mysqli_connect("localhost","UID","PSW","DB"); //Db connection
    //connectToDatabase();

    $sql="SELECT COUNT(*) as cnt FROM 'cans' c WHERE c.date >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND c.canId = '$canNum'";
    $result = mysqli_query($con,$sql);
    $count_1=mysqli_fetch_array($result);
    $count=$count_1['cnt'];
    // disconnectDatabase();
    //return true if above returns a row
    mysqli_close($con);
    //  disconnectDatabase();
    return $count; //returns count you can modify it the way you want
}

    echo "Current count is ".isNew(10);
?>

答案 3 :(得分:1)

您的代码看起来不像是一段PHP代码!试试这个:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$number=mysql_num_rows(mysql_query("SELECT `canId` FROM `cans` WHERE `date` >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND `canId` = '$canNum';"));

if($number>0){
  // do what you want to do
}

mysql_close($con);

答案 4 :(得分:0)

请避免使用其他答案中建议的mysql_query,并查看mysqli_query或PDO。使用PDO,您可以执行以下操作:

function isNew($canNum){
  $db = new PDO();
  $statement = $db->prepare('....your query... WHERE canID=:canID');
  $statement->bindParam(':canID', $canNum);
  $statement->execute();
  if($result = $statement->fetch()){
     //exists
     return true;
  } else {
     return false;
  }
}

您也可以避免SQL注入;