Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to get variable data "$b ,$d, $f,$h" from database and then calculate it. Here is my example:

    <?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"); 
    ($row4 = mysql_fetch_assoc($h));
    $row["bobot"];
    $calc = $b+$d+$f+$h;
    echo $calc;
<?

The values in the database are 50,50,50,50 but the result is 22. Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

The line below every query string is wrong

($row = mysql_fetch_assoc($b));
    $row["bobot"];

Because you are not storing the result anywhere.The correct way to get the values should be:

if(count($res=mysql_fetch_assoc($b))>0)$_b=$res[0]['bobot'];

(if returning result has at least one row, return the value to $_b variable)

Mind that $b is being used to store the query result, not the value you get from it.

Then you sum the results like this: $calc = $_b+$_d+$_f+$_h; and that's all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...