如何从数据库中检索值? [英] How to retrieve values from a database?

查看:67
本文介绍了如何从数据库中检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据库中获取变量数据 "$b ,$d, $f,$h" 然后计算它.这是我的例子:

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;
<?

数据库中的值是50、50、50、50,结果是22,这是为什么呢?

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

推荐答案

每个查询字符串下面的行是错误的

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'];

(如果返回结果至少有一行,返回值到$_b变量)

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

请注意 $b 用于存储查询结果,而不是您从中获得的值.

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

然后将结果相加如下:$calc = $_b+$_d+$_f+$_h; 就是这样.

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

这篇关于如何从数据库中检索值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆