从MySQL数据库中获取特定值

时间:2014-10-28 12:04:42

标签: php mysql

我正在尝试从MySQL数据库中获取值。我需要获取特定项目的价格,这是我的表格的样子:

enter image description here

我不确定如何解决这个问题,我唯一能想到从表中获取价格的方法是在查询中添加一个条件,它只会抓取与domain_address匹配的结果。

我通过调用返回<?php echo getPageURL();?>的函数http://vauxhallpartswarehouse.co.uk/来进行测试(它应该与数据库条目匹配。

//table which calls function
<td bgcolor="#999999" align="center">Price: <?php echo getPrice();?></td>

<?php
function getPrice() {
    $con=mysqli_connect("host","user","pass","db");
    $price = mysqli_query($con, "SELECT price FROM domains WHERE domain_address='<?php echo getPageURL();?>'");
    mysqli_close($con);
    return $price; //should only be 1 result returned since domain_address is unique
    }
?>

这似乎不想工作,我真的不知道如何抓住价格。

我知道连接很好,我已经在脚本中进一步编写了这个代码,它创建了一个包含数据库所有结果的表,所以也许我可以用下面的代码做些什么?

<?php
    $con=mysqli_connect("host","user","pass","db"));
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $results = mysqli_query($con, "SELECT domain_name, domain_address, price FROM domains");

    echo "<table border='1'>
    <tr><th>Domain</th>....
    </tr>";

    while($row = mysqli_fetch_array($results))
    {
    echo "<tr>";
    echo "<td>" . $row['domain_name'] . "</td>";
    echo "<td><a target='_blank' href=" . $row['domain_address'] . ">"....
    //etc
    mysqli_close($con);
    ?>

1 个答案:

答案 0 :(得分:4)

那是因为在这一行:

$price = mysqli_query($con, "SELECT price FROM domains WHERE domain_address='<?php echo getPageURL();?>'");

getPageURL()未执行,它只是整个字符串的静态部分。试试这个:

$price = mysqli_query($con, "SELECT price FROM domains WHERE domain_address='" .  getPageURL() . "'");