从数据库中读取单个值并将其保存在变量中

时间:2015-09-26 18:27:10

标签: php mysql sql database

我的数据库中有一个小表,如下所示:

----------------------
id | name      | value
----------------------
1  | test.flag | 0
----------------------
2  | username  | franz
----------------------

我只是尝试读取test.flag的值并将结果存储在变量中。

<?php

    $servername = "127.0.0.1";
    $username   = "test";
    $password   = "test123";
    $dbname     = "testdb";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if (!$conn)
    { 
        die("Connection to database failed with error#: " . mysqli_connect_error()); 
    }   

    $sql = "SELECT value FROM mytable WHERE name='test.flag';";

    $result = mysqli_query($conn, $sql);
    echo "<p>".$result."</p><br>";

    if (mysqli_query($conn, $sql))
    {
        echo "<p>Sucessfully</p><br>";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    echo "<p>".$sql."</p><br>";
?>

但在执行此script.php文件后,它会加载一个空白页。

2 个答案:

答案 0 :(得分:5)

您需要获取行,然后echo

$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo "Result: " . $row['value'];

答案 1 :(得分:2)

查询的值未存储在$sql变量中。

就像@ user5173426一样,您必须先获取它。

示例(http://www.w3schools.com/php/php_mysql_select.asp):

while($row = $result->fetch_assoc())
   $toEcho = $row["value"];
echo $toEcho;