繁体   English   中英

检索单个列的值

[英]Retrieve Value of a single column

我需要从单个列中检索数据并放入API(Json)中,但是由于某些原因,我也从该列中获取标题。

$sql = "SELECT workingJson FROM dataTable";

我以为这就像workingJson.Value ,但是没有运气。

这是API.php

// Create connection
$con=mysqli_connect("localhost","user","password","database");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT column1 FROM database";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);

根据您的评论进行编辑:

要只返回值而不是PHP中的键,可以将代码更改为:

// Loop through each row in the result set
while($row = $result->fetch_object())
{
    // Add value to array
    array_push($resultArray, $row->column1);
}

在这种情况下,您不需要$tempArray

您可以得到所有结果,并在执行特征后:

<?php

// Create connection
$con=mysqli_connect("localhost","user","password","database");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT column1 FROM database";


if ($result = $mysqli->query($sql)) {

    //get all fields :
    $finfo = $result->fetch_fields();

    foreach ($finfo as $val) {
        $resultArray[] = $val->column1;
    }
    $result->close();
}

// Finally, output the results without encode because is also in json format:
echo '{'. implode(','.chr(10), $resultArray) .'}';

$mysqli->close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM