PHP中的SQL数据库连接成功,但我无法查询它

时间:2016-12-09 15:40:49

标签: php mysql sql sql-server mysqli

<?php
  $servername = "localhost";
  $username = "user";
  $password = "pass";
  $dbname = "test";
  $tablename = "mapcoords";

  $conn = new mysqli($servername, $username, $password, $dbname);

  if ($conn->connect_error)
  {
    echo "Failure";
    die("Connection failed: " . $conn->connect_error);
  }

  echo "Connected successfully";
  $sql = "SELECT (lat, lng) FROM mapcoords";
  $result = $conn->query($sql);

    while($row = $result->fetch_assoc())
    {
      echo "ok";
    }



  $conn->close();

?>

这是代码。就像我说的,它可以成功连接,但代码不会成功查询。奇怪的是,如果我复制并粘贴相同的代码,这似乎完全相同,它就可以工作。这没有道理。我找不到他们的代码和我的代码之间的单一区别,除了他们分散事物的方式和我分隔事物的方式。这是他们的代码:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT (lat, lng) FROM mapcoords";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo $row["lat"]. " " . $row["lng"] . "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

1 个答案:

答案 0 :(得分:3)

问题是这个查询:

SELECT (lat, lng) FROM mapcoords

返回以下错误:

  

[21000] [1241]操作数应包含1列

您必须将查询更改为

SELECT lat, lng FROM mapcoords