0

I have my SQL query working fine in PHPMyAdmin but can't get it work with PHP. Let's say I have this query:

SELECT Login, Firstname, Lastname, Company INTO OUTFILE 'c:\\users.txt' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'  
FROM `Users` WHERE Company = 'SID';

I would like to call my query from a web page with a click. I did 2 files fonction.php and form.php as follow. For fonction.php

<?php
function connectMaBase(){
    $base = mysql_connect ('localhost', 'root', '');  
    mysql_select_db ('Dbase', $base) ;
}
?>

And for form.php I have this

<?php
include("fonction.php");
?>
<html>
    <head><title>Pages de requetes SQL </title></head>
    <body>
        <h1> Requete SQL </h1>
       <form name="sqlquery" method="post" action="form.php">        
        <input type="submit" name="valider" value="Go"/>
       </form>
 <?php 
    if (isset ($_POST['valider'])){
        connectMaBase();
        $sql = "SELECT Login, Firstname, Lastname, Company  INTO OUTFILE \'c:\\\\Users.txt\' FIELDS TERMINATED BY \',\' LINES TERMINATED BY \'\\r\\n\' \n"
     . "FROM `Users` WHERE Company = \'SID\'";

        mysql_query ($sql) or die ('Erreur SQL !'.$sql.'<br />'.mysql_error()); 
        mysql_close();
    }
?>
    </body>
</html>

I'm a beginner and could not find what is wrong in the code.

Thanks for your help.

Amalirou
  • 7
  • 2
  • 2
    If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) [statements](http://php.net/manual/en/pdo.prepared-statements.php) instead, and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jun 29 '15 at 19:51

1 Answers1

0

You don't need to escape single quotes when your main query is in double quotes. Try:

$sql = "SELECT Login, Firstname, Lastname, Company  INTO OUTFILE 'c:\\\\BA2112262201-P03.txt' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\r\\n' \n"
     . "FROM `OptiOutput` WHERE Company = 'SID'";

Also, I agree with Jay Blanchard. Try to avoid the mysql_* extension and use PDO instead. Also, is the table name 'OptiOutput' correct? It wouldn't be 'Users' like in your first query?

Osuwariboy
  • 1,335
  • 1
  • 14
  • 29
  • Thank you very much @Osuwariboy, it works just fine!! You are right I will try using PDO as this one is deprecated. Thanks. – Amalirou Jun 29 '15 at 20:19