首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数据从mysql表行导出为数组格式

问将数据从mysql表行导出为数组格式
EN

Stack Overflow用户
提问于 2012-11-10 20:09:19
回答 1查看 2.1K关注 0票数 0

我正在尝试从

  • 表:艺术家
  • 排:艺人

转换成这种格式。艺术家的名字可以有特殊的人物,其中有超过16000。它需要写到文件中。例如,调用任何artist.php

代码语言:javascript
复制
$Artist = array(
    "Name from database",
    "Name from database",
    "Name from database",
    "Name from database",
    "Name from database"
);

好的很抱歉没有解释。这样做是为了ajax自动完成。所以我需要创建一个包含这个数组的文件。

我让它工作和输出的方式,我需要它只是停留在如何说所有的文件后,它做了。

这是我有的东西

代码语言:javascript
复制
require_once('config.php'); 

$res = mysql_query("SELECT artist FROM artists");
$ids = array();
$NotAllowed = array("(", ")", "+", ".", "-", "$", "#", "'", "\"", "%",":", ",", "*", "\\", "/");
    echo '$aUsers = array('; echo "<br>";
while ($row = mysql_fetch_assoc($res)) {
  $ids[] = $row['artist'];
    $FixedArtist = str_replace($NotAllowed, " ", $row['artist']);
        echo "\""; echo $FixedArtist; echo "\","; echo "<br>";

}
    echo "\"Lastname\""; echo "<br>";
    echo ");";




    $FileToSaveTo = "ajax-search.php";
    $fp = fopen($FileToSaveTo,"w") or die ("Error opening file in write mode!");
    fputs($fp,$content);
    fclose($fp) or die ("Error closing file!");
EN

回答 1

Stack Overflow用户

发布于 2012-11-11 01:42:13

是的,尝试使用PDO读取结果并将其导出到一个单独的artists.json文件中,它更干净

代码语言:javascript
复制
/*require_once('config.php'); 
$res = mysql_query("SELECT artist FROM artists");
$ids = array();
$NotAllowed = array("(", ")", "+", ".", "-", "$", "#", "'", "\"", "%",":", ",", "*", "\\", "/");
/*while ($row = mysql_fetch_assoc($res)) {
  $ids[] = str_replace($NotAllowed, " ", $row['artist']);  
}*/

//PDO version
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$sth = $dbh->prepare("SELECT artist FROM artists");
$sth->execute();
$ids = $sth->fetch(PDO::FETCH_ASSOC);
//replace not allowed chars here

file_put_contents('artists.json', json_encode($ids));

然后ajax-search.php将加载该文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13325641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档