通过php作为数组回应mysql列

时间:2016-04-20 10:20:01

标签: php mysql arrays

我想获取一个名为" my_table"的mysql表。列名为" Email"通过php将内容作为数组,所以这是我的代码:

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

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

    if ($result === FALSE) {
        die(mysql_error()); // TODO: better error handling
    }

    $data = array();
    while ($row = mysql_fetch_array($result)) {
        $data[] = $row['Email'];
    }
    echo join($data, ',');
?>

但此代码返回此错误: 没有选择数据库

但是我已经选择了我的桌子和数据库...

我知道这段代码有一些问题,如混合mysql和mysqli内容,但我不知道如何解决它我只是想要那个数组回声,如果这个代码需要修复只是guid我,  如何解决这个问题呢 ?提前致谢 感谢@Martin 我的问题已经解决了我只是通过这种方式更改了代码:

<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "my_db"; 
// Create connection
 $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection 
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}
$result = mysqli_query($conn, "SELECT * FROM my_table");
if($result === FALSE) { 
die(mysql_error()); // TODO: better error handling
}


$data = array();
while ($row = mysqli_fetch_array($result))
{
$data[] = $row['Email'];
}
echo join($data, ',')
?>

1 个答案:

答案 0 :(得分:-2)

您正在联系这里名为“my_table”的数据库:

  class model: NSObject {
      var name:String!
      var email:String!
   init(name:String , email:String){
      super.init()
      self.name = name
      self.email = email
      }
    }

然后,在您的SQL语句中,您尝试连接到一个名为相同的表:

$dbname = "my_table";

您确定这是您数据库的正确名称吗?

在PHPMyAdmin上,您可以单击“数据库”以查看数据库名称,然后在单击数据库时,它将为您提供表格列表:

Image file of getting database views from tables in PHPMyAdmin