优化PHP / MySQL脚本以减少服务器使用

时间:2015-02-13 14:52:24

标签: php mysql optimization ads banner

我有一个每日浏览量超过1'000'000的网站和一个php脚本,可以在每个页面上显示2-3个横幅广告并计算展示次数

要计算展示次数,请在每个横幅后面都有一张图片:

<img src="https://example.com/impression.php?client=ABC&banner=XYZ" width=1 height=1>

以下是展示脚本的示例:

require('global.php'); // connect to mysql, read default settings, etc

if( isset( $_GET['client'] ) ) && !empty( $_GET['client'] ) ) { $client = secure( $_GET['client'] ); } else { die('error param'); }
if( isset( $_GET['banner'] ) ) && !empty( $_GET['banner'] ) ) { $banner = secure( $_GET['banner'] ); } else { die('error param'); }

$check_client = mysqli_query( $con, "SELECT id FROM clients WHERE id = '$client' AND status = 1 LIMIT 1" ) or die( 'error mysql' );
if( mysqli_num_rows( $check_client ) == 0 ) { die('error client'); }

$check_banner = mysqli_query( $con, "SELECT campaign_id FROM banners WHERE id = '$banner' AND status = 1 LIMIT 1" ) or die( 'error mysql' );
if( mysqli_num_rows( $check_banner ) == 0 ) { die('error banner'); }    
$read_campaign_id = mysqli_fetch_array( $check_banner ); 

$check_campaign = mysqli_query( $con, "SELECT id FROM campaigns WHERE id = '$read_campaign_id[0]' AND status = 1 LIMIT 1" ) or die( 'error mysql' );
if( mysqli_num_rows( $check_campaign ) == 0 ) { die('error campaign' );  }

$check_unique = mysqli_query( $con, "SELECT id FROM impressions WHERE datetime LIKE '$today%' AND banner = '$banner' AND ip = '$ip' ORDER BY datetime DESC LIMIT 1" ) or die( 'error mysql');
if( mysqli_num_rows( $check_unique ) == 1 ) { $unique = 0; } else { $unique = 1; }

mysqli_query( $con, "INSERT INTO impressions ( client, campaign, banner, datetime, unique, ip, page ) VALUES ( '$client', '$read_campaign_id[0]', '$banner', '$now', '$unique', '$ip', '$url' )" ) or die( 'error mysql' );

header( 'Content-type: image/png' );
header( $path . '/img/pixel.png' );
mysqli_close( $con );
exit;

在这种情况下,优化脚本并减少服务器上的资源使用和并发连接的最佳方式是什么?

  • 例如,它可以在一个查询中加入一些mysql查询吗?我认为应该快得多,但我不确定......
  • 另一种可能的方法是将展示次数保存在CSV文件中,并且每隔2-5分钟在mysql上导入此文件?但它只保存1个查询...

修改 这是mysql表结构(仅适用于此示例的有用字段) http://sqlfiddle.com/#!2/1ffe3/1

1 个答案:

答案 0 :(得分:1)

是的,您可以在单个查询中运行所有选择。

相当令人困惑(因为你只需要每行一行,并且它们之间没有明显的关系)你可以用笛卡尔积来做到这一点。

您的架构很糟糕(WHERE datetime LIKE'$ today%'使用字符串存储日期!!!!)

当你只想查看是否存在任何行时,为什么要订购$ check_unique的结果?

SELECT clients.id AS client_id
, banner.campaign_id AS banner_campaign_id
, campaign_id
,(SELECT COUNT(*)
   FROM impressions 
   WHERE impressions.datetime LIKE '$today%' 
   AND impressions.banner = '$banner' 
   AND ip = '$ip' 
   LIMIT 1) AS check_unique
FROM clients
INNER JOIN banners
INNER JOIN campaigns
WHERE clients.id = '$client' AND clients.status = 1
AND banners.id = '$banner' AND banners.status = 1
AND campaigns.id = '$read_campaign_id[0]' AND campaigns.status = 1
LIMIT 1

或者你可以将它展开到一个UNION中,但那不那么有趣。