1

I have code to create a CSV file with SQL query data and then I send it by email.

function create_csv_string($data) {
    mysql_connect("xxxx", "xxxx", "xxxx");
    echo mysql_error();
    mysql_select_db("xxxxx");
    $data = mysql_query("SELECT NOMBRE, TELEFONO, HORARIO, EMAIL FROM _LEADS WHERE ENVIADO = 0");
    echo mysql_error();
    if (!$fp = fopen('php://temp', 'w+')) {
        return FALSE;
    } else {
        echo "entra";
    }
    fputcsv($fp, array('Nombre', 'Telefono', 'Horario', 'Email'));
    while ($line = mysql_fetch_assoc($data)) fputcsv($fp, $line);
    rewind($fp);
    return stream_get_contents($fp);
}

My problem is that I executing this in local and it works, but I upload it to a server and it doesn't work. I think that the problem is in !$fp = fopen('php://temp', 'w+')) but I am not sure.

8
  • Please do not use mysql_* functions, as they are deprecated and removed. Try using mysqli_* or PDO. Commented Jun 9, 2016 at 10:15
  • The problem seems to be in MySQL Server and the file permissions. Can you set the permissions as 777 just for a moment and check? You can use something like chmod -R 777 /var/www or something. Commented Jun 9, 2016 at 10:15
  • Have you tried by giving filename with path in fopen function? Commented Jun 9, 2016 at 10:19
  • Ok, I change mysql_* to mysqli_* later. How I can change permissions?? Like this? if (!$fp = fopen('php://temp', '777')) { sorry I am rookie in php.. @PraveenKumar Commented Jun 9, 2016 at 10:20
  • But my file is not exist.. in my localhost works.. @sAcH Commented Jun 9, 2016 at 10:22

1 Answer 1

1

You need to do something like this:

<?php
    function create_csv_string() {
        echo "entssssra?";
        $connection = mysqli_connect("**","**","**","**") or die("Cannot Connect to MySQL Server");
        $data = mysqli_query($connection, "SELECT NOMBRE, TELEFONO, HORARIO, EMAIL FROM _LEADS WHERE ENVIADO = 0");
        // Build the CSV:
        $csv = "'Nombre', 'Telefono', 'Horario', 'Email'" . PHP_EOL;
        while (false != ($line = mysqli_fetch_assoc($data)))
            $csv .= array_values($line);
        echo $csv;
        return file_put_contents('temp.csv', $csv);
    }

And you don't need the $data as a parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.