Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - How to retrieve values from a database?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...