dongtan3395 2017-03-11 12:29
浏览 51

在同一页面上具有相同变量的多个查询

QUESTION 1

Okay so I need to clear a confusion. I have multiple queries on the same page like this.

$abc = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$abc-> execute();
$count1 = $abc->fetchColumn();

$bcd = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$bcd-> execute();
$count2 = $bcd->fetchColumn();

$def = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$def-> execute();
$count3 = $def->fetchColumn();

This works fine. But declaring a new name for each query somewhat gives me an irritation. Therefore, I assumed that wouldn't it be nice if all the queries could be written in the same variable? So, will it be wrong if I write these queries in one variable only? Like the following code.

$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count1 = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count2 = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM tablename");
$stmt-> execute();
$count3 = $stmt->fetchColumn();

Will writing the queries in the same way give any errors in the future? Is it safe to write in the same variable? Is there any difference? Which method is better?

QUESTION 2

To get $count1, $count2 and $count3 I had to pass three different queries. But I prefer writing as less query as possible to prevent the use of much resources. So, is it necessary to be done this way? Or, is it possible to get them all in one single query? If yes, then how?

Please help me clear these doubts devs.

  • 写回答

1条回答 默认 最新

  • doulingna9420 2017-03-11 12:57
    关注

    as long as you are sure that you won't use the first variable, it will be okey to use it's name to define another variable.

    however, it's a good practice to unset unused variables.

    for your second question, you may combine your three queries in one query using Unions as follows: i'm assuming that you are asking for those particular three queries

    SELECT COUNT(*) FROM `table1`
    UNION
    SELECT COUNT(*) FROM `table2`
    UNION
    SELECT COUNT(*) FROM `table3`
    
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)