你好overflower我有问题我想从数据库中获取可变数据“$ b,$ d,$ f,$ h”然后计算它 这是我的例子
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="cbrteh"
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$b= mysql_query("SELECT bobot FROM atribut where id= 1");
($row = mysql_fetch_assoc($b));
$row["bobot"];
$d= mysql_query("SELECT bobot FROM atribut where id= 2");
($row = mysql_fetch_assoc($d));
$row["bobot"];
$f= mysql_query("SELECT bobot FROM atribut where id= 3");
($row = mysql_fetch_assoc($f));
$row["bobot"];
$h= mysql_query("SELECT bobot FROM atribut where id= 4");
($row = mysql_fetch_assoc($h));
$row["bobot"];
$calc = $b+$d+$f+$h;
echo $calc;
是我的脚本 数据库上的值是50,50,50,50,因此值必须为200 但是我从echo $ calc得到的价值;是22
答案 0 :(得分:1)
试试这个:
$b= mysql_query("SELECT bobot FROM atribut where id= 1");
$row = mysql_fetch_row($b);
$b = $row[0];
$d= mysql_query("SELECT bobot FROM atribut where id= 2");
$row = mysql_fetch_row($d);
$d = $row[0];
[...] // repeat for $f and $h
$calc = $b + $d + $f + $h;
echo($calc);
或者,也许使用任何更合适的代码:
$b= mysql_query("SELECT SUM(bobot) as calc FROM atribut WHERE id IN (1,2,3,4)");
$row = mysql_fetch_row($b);
$calc = $row[0];
echo($calc);
答案 1 :(得分:1)
您应该将查询的值存储在变量中,然后对它们求和。
$b = $row["bobot"];
依旧......