为什么这个PHP脚本只返回6号?

时间:2011-05-14 17:59:54

标签: php mysql

这个脚本应该从Mysql中获取当前的流行度,向该数字添加一位数然后更新它。但这并没有发生,它只返回'6'任何想法为什么?

来源:

<?php
include_once("../scripts/config.php");


$url = mysql_real_escape_string($_POST['url']);
preg_match("/id=(\\d+)/", $url, $matches);
$like = $matches[1];
$current_pop = mysql_query("SELECT pop FROM likes WHERE id=$like") or die ("Query failed: " . mysql_error());

$one = '1';

$pop = $current_pop + $one;  

print $pop;
$update = mysql_query("UPDATE likes SET pop = ".$pop." WHERE id = ".$like."") or die ("Query failed: " . mysql_error());

?>

5 个答案:

答案 0 :(得分:1)

您必须从结果中获取值。使用mysql_fetch_assoc或类似的东西。

答案 1 :(得分:1)

您需要使用mysql_fetch_array()从第一行获取值:

 $row = mysql_fetch_array($current_pop);
 $current_pop = $row[0];

但是,您可以使用一个SQL查询更新pop值:

mysql_query("UPDATE likes SET pop=(pop+1) WHERE id=$like") or die ("Query failed: " . mysql_error());

答案 2 :(得分:1)

mysql_query返回对资源的引用,而不是查询中pop字段的结果。

你需要做这样的事情......

$result = mysql_query("SELECT pop FROM likes WHERE id=$like") or die ("Query failed: " . mysql_error());
if ($result) {
    $row = mysql_fetch_assoc($result);
    $current_pop = $row['pop'];
} else {
    // handle error here
}

您还应该在像您这样的原始SQL查询中的任何变量周围使用mysql_real_esacpe_string。

答案 3 :(得分:1)

应该是

<?php
include_once("../scripts/config.php");

$url = mysql_real_escape_string($_POST['url']);

preg_match("/id=(\\d+)/", $url, $matches);

$current_pop = mysql_query("UPDATE likes SET pop=pop+1 WHERE id='{$matches[1]}'") or die ("Query failed: " . mysql_error());

?>

答案 4 :(得分:0)

尝试

<?php
include_once("../scripts/config.php");


$url = mysql_real_escape_string($_POST['url']);
preg_match("/id=(\\d+)/", $url, $matches);
$like = $matches[1];
$current_pop = mysql_query("SELECT pop FROM likes WHERE id=$like") or die ("Query failed: " . mysql_error());
$row = mysql_fetch_assoc($result)
$one = 1;

$pop = $row["pop"] + $one;  

print $pop;
$update = mysql_query("UPDATE likes SET pop = ".$pop." WHERE id = ".$like."") or die ("Query failed: " . mysql_error());

?>