2011-04-17 35 views
1

好吧,这是我第一个使用PHP和MySQL的项目,我认为使用HTML,PHP和MySQL的Facemash风格的网站将是一个很好的开始。从图像超链接运行PHP函数(Facemash项目)

除了像图片超链接调用“updateHits”函数的行为不像我所期望的那样,一切正常。

我相信MySQL数据库能够正常运行并且图片按预期显示。我的研究指向使用iFrames,jQuery或AJAX来更新“点击”字段,尽管我无法理解如何在这里应用它们。

我希望我的代码可读,任何建议将不胜感激!

<html> 
<body> 
<?php 
// Make a MySQL Connection 
mysql_connect("localhost", "admin", "admin") or die(mysql_error()); 
mysql_select_db("facemash") or die(mysql_error()); 

// Select two random people 
$personA = rand(1, 28); 
$personB = rand(1, 28); 

// Ensure that it is not the same person 
if ($personB == $personA) { 
    $personB = rand(1, 28); 
} 

// Function to return path of photo 
function photoPath ($person){ 

$query = mysql_query("SELECT photo FROM people WHERE id=$person"); 
$result = mysql_fetch_row($query); 
$result = $result[0]; 

echo $result; 
} 

// Function to update the hits field 
function updateHits($person){ 

$query = mysql_query("SELECT hits FROM people WHERE id=$person;"); 
$result = mysql_fetch_row($query); 
$result = $result[0]; 

$result++; 

mysql_query("UPDATE people SET hits = $result WHERE id=$person"); 
} 
?> 

<!--Image for personA--> 
<a href="<?php updateHits($personA);?>"><img src="<?php photoPath($personA);?>"/></a> 

<!--Image for personB--> 
<a href="<?php updateHits($personB);?>"/><img src="<?php photoPath($personB);?>"/></a> 
</body> 
</html> 

谢谢。

+0

你期待什么? – ITroubs 2011-04-17 23:43:14

回答

0

呃,PHP不能这样工作。 ;)

PHP是服务器端代码,你正在创建一个指向任何地方的链接。为了达到你想要的效果,你需要对服务器进行AJAX调用,告诉它更新命中。

+0

谢谢,我会研究它:) – Josh 2011-04-17 23:52:44

+0

本质上,运行代码时发生的情况是,即使您在链接中添加updateHits()函数,PHP也会解析整个事件,并在相同的位置生成输出时间。这意味着,由于updateHits($ personB)实际上并没有向浏览器提供任何输出(通过打印或回显,或者只是在标签之外或其他任何地方),您的标签看起来就像是 ......这显然不是你想要什么。 – 2011-04-17 23:57:39

+0

基本上,您将要创建第二个PHP文件,该文件使用在URL字段中提供的用户名来调用updateHits()函数,然后在您的页面链接中使用Javascript在点击链接时在后台加载并(可选)更新加载的页面以显示新数据。 – 2011-04-17 23:59:26