0

我是 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();
  }

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

4

5 回答 5

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;
}
  }
于 2013-05-10T02:49:17.773 回答
1

可能您需要在代码中使用这些 php 函数之一

<?php

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

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

?>
于 2013-05-10T02:50:45.843 回答
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);
?>
于 2013-05-10T02:57:26.540 回答
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);
于 2013-05-10T02:58:37.537 回答
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 注入;

于 2013-05-10T03:06:37.317 回答