php mysql查询输出文件

时间:2016-07-19 09:20:01

标签: php mysql into-outfile

我正在尝试创建一个在我的数据库上运行的脚本。查询本身在phpmyadmin中工作正常,但需要能够在其他地方运行它。所以我的想法是,把它放到一个PHP脚本中。

我的查询如下:

SET @sql_text =
CONCAT ("SELECT
`table1`.`field1`,
`table2`.`field2`

FROM `table1`,`table2`

WHERE
`table1`.`field1`=`table2`.`field2`

 into outfile '/pathtofolder/myresult-"
   , DATE_FORMAT( NOW(), '%Y%m%d-%H:%i')
   , ".csv'
FIELDS TERMINATED BY '|'
    "    );

PREPARE s1 FROM @sql_text;
EXECUTE s1;

DROP PREPARE s1;

现在我似乎遇到了麻烦,试图把它变成php。我的尝试:

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

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

$sql = 'SET @sql_text =
CONCAT ("SELECT
`table1`.`field1`,
`table2`.`field2`

FROM `table1`,`table2`

WHERE
`table1`.`field1`=`table2`.`field2`

 into outfile '/pathtofolder/myresult-"
   , DATE_FORMAT( NOW(), '%Y%m%d-%H:%i')
   , ".csv'
FIELDS TERMINATED BY '|'
    "    );

PREPARE s1 FROM @sql_text;
EXECUTE s1;

DROP PREPARE s1;'

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?> 

不幸的是,这似乎不起作用。我在俯瞰什么?

1 个答案:

答案 0 :(得分:1)

由于sql在单引号内但包含单引号,您需要使用反斜杠转义它们。

$sql = 'SET @sql_text =
CONCAT ("SELECT
`table1`.`field1`,
`table2`.`field2`

FROM `table1`,`table2`

WHERE
`table1`.`field1`=`table2`.`field2`

 into outfile \'/pathtofolder/myresult-"
   , DATE_FORMAT( NOW(), \'%Y%m%d-%H:%i\')
   , ".csv\'
FIELDS TERMINATED BY \'|\'
    "    );

PREPARE s1 FROM @sql_text;
EXECUTE s1;

DROP PREPARE s1;'