Getting multi records from check boxes - php

First of all before anyone here regrets and set this duplicate I don't know will be or not but I tried to search alot but wasn't able to find my answer I created a table from which there are some checkboxes what I want to do is if someone selects 3 entries then the data will be exported for those 3 entries only this is y query what I have done so far
$id = $_POST['select'];
foreach($id as $key) {
echo $key . ", ";
}
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));
$num_rows = mysqli_num_rows($sql);
I dont know why it's giving me the last record only ? it should have given me 3 records like happens in between query it give us the entries of d between 1 and 3 but what if we select id 1 3 5 it shoulld have given these 3 right so for exporting it to excel i did this code found some help working fine but having issue with my query not successful
if($num_rows >= 1)
{
$row = mysqli_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysqli_data_seek($sql, 0);
while($row = mysqli_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "Your file is ready. You can download it from <a href='$filename'>here!</a>";
}
else
{
echo "There is no record in your Database";
}

$key is only going to be the last value in the foreach. Give the following a go:
$id = $_POST['select'];
$key = "";
foreach($id as $vals) {
$key = $key . $vals . ",";
}
$key = trim($key, ",");
$sql = mysqli_query($con, "SELECT * FROM $table WHERE uid IN ('$key')") or die(mysqli_error($con));

Related

Saving data from localhost to online

I am trying to save my data coming from my localhost database to our live server database using PHP. I am getting a successful response but whenever I try to check the our live database server there is no data in it or the data was not inserted or updated.
Also the response I get is this "Import successful! Found a total of 4 records in patient.file" even though the file I am importing is only to data.
Here is my code:
<?php
//============FUNCTIONS=================
function export_table($target_table,$sdate,$edate,$station){
$i = mysql_num_rows(mysql_query("DESCRIBE $target_table"));
$get_columns = mysql_query("SHOW COLUMNS FROM " . $target_table);
while($row_columns = mysql_fetch_array($get_columns)){
$column_name = $row_columns['Field'] . "|";
$csv_output .= $column_name;
}
$csv_output = rtrim($csv_output, "|");
$csv_output .= "\r\n";
$values = mysql_query("SELECT * FROM ".$target_table." WHERE
dateEncoded >= '2017-07-01' and dateEncoded <= '2017-07-07'");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
if($rowr[$j] == NULL){$rowr[$j] = "NULL";}
if($j==($i-1)){$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j]);
}else{$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j])."|";}
}// end for
$csv_output .= "\r\n";
}// end while
return $csv_output;
}// end function export_table
//========CREATION OF THE FILE===========================
include_once "../ewcfg8.php";
include_once "../dbcon.php";
date_default_timezone_set('Asia/Manila');
ini_set('memory_limit', '-1');
set_time_limit(0);
// $startdate = '2017-06-01';
// $enddate = '2017-07-07'; ;
// $defaulStation = $_POST['defaultStation'];
$tables = array('patient',
'tb_adr',
'tb_case',
'tb_casecomment',
'tb_comorbidity',
'tb_consilium',
'tb_consultations',
'tb_contact',
'tb_pe',
'tb_prescript',
'tb_prevcase',
'tb_resultculture',
'tb_resultgx',
'tb_resultdst',
'tb_resultdstdrug',
'tb_resulthiv',
'tb_resultxray',
'tb_symptom',
'tb_resultdssm',
'tb_dot');
//put tables in an array within an array(make a multi-dimensional array)
$dl_table = array();
foreach ($tables as $table) {
$content = export_table($table,$startdate,$enddate,$defaulStation);
$dl_table[$table] = $content;//multi-dimensional array
}
//#mysql_close($con); //close localhost connection
//=========INSERTING VALUES TO DATABASE===============
//===============Open New Connection And Connect to Live Database========
$dbhost = "http/mywebsite.example";
$localport = "3306";
$dbuser = "user";
$dbpass = "12345";
$dbname = "myonlinedb";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $conn);
$fieldseparator = "|";
$lineseparator = "\n";
foreach ($tables as $table) {
$databasetable = $table;
$csvfile = $dl_table[$table]; //variable that hold the multi-dimensional array
$lines = 0;
$header = 0;
$queries = "";
$linearray = array();
$columns = array();
//====================================Get the Columns (First line in the CSV)===================================
while(($header == 0 && $columns = fgetcsv(${$table},0,"|")) != false){
$header = 1;
$num_columns = count($columns);
$list_columns = "";
for ($c=0; $c < $num_columns; $c++) {
$list_columns .= "`" . $columns[$c] . "`" . ", ";
}
$list_columns = substr($list_columns,0,-2);
//echo $list_columns . "<br /><br />";
break;
}// close while(($columns = fgetcsv($file,0,"|")) !== false && $header == 0)
//====================================Get the contents of the CSV===================================
//Set the header to skip the first row
$header = 0;
//opening the csv file
// $size = filesize($csvfile);
// echo $size;
// if(!$size) {echo "File is empty.\n";}
// $csvcontent = fread($file,$size);
// fclose($file);
//foreach(split($lineseparator,$csvcontent) as $line)
foreach(explode($lineseparator,$csvfile) as $line) {
//if($header == 0){
//$header = 1;
//}else{
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
//*********get the csvID id and the columns in the db table to know if an insert or update will be performed****************
if ($databasetable == "patient"){
$csvID = $linearray[2];
$searchField = "patientID";
}else if($databasetable == "tb_case"){
$csvID = $linearray[0];
$searchField = "caseID";
}else if($databasetable == "tb_resultdstdrug"){
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseIDplus, series)";
}else{
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseID, series)";
}
//***********convert id of each row to 0*******************************
if($databasetable != "tb_case"){$linearray['0'] = '';}
//*****************search the csvID in the database************************************
$searchID = mysql_query("SELECT * FROM $databasetable WHERE $searchField = '$csvID'");
//******************count the number of columns in csv and the db table**************
$countcsv = count($linearray);
$countColumns = $num_columns;
//$countColumns = mysql_num_fields($searchID);
//****************count if the csvID exists in the database********************************
$countResults = mysql_num_rows($searchID);
//*************************get the date encoded in the csv and db table***************
$row = mysql_fetch_assoc($searchID);
$db_dateEncoded = $row['dateEncoded'];
if($databasetable == "tb_dot"){$csv_dateEncoded = $linearray[($countcsv-3)];}
else{$csv_dateEncoded = $linearray[($countcsv-2)];}
//*****************if else statement for checking number of fields****************************************
if ($countResults > 0){
//if a result was found, UPDATE the row
if ($csv_dateEncoded>$db_dateEncoded){
// if table is dot, delete all dot of the tb_case
$query = "UPDATE $databasetable SET ";
$i = 1;
while ($i < $countColumns){
$meta = mysql_fetch_field($searchID, $i);
if($linearray[$i] == "NULL"){
$query .= $columns[$i] . "=" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= " WHERE $searchField = '$csvID';";}else{$query .= ",";}
}else{
$query .= $columns[$i] . "='" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= "' WHERE $searchField = '$csvID';";}else{$query .= "',";}
}//end if($linearray[$i] == "NULL")
$i = $i + 1;
}//close while ($i < $countColumns)
}// end if($csv_dateEncoded>=$db_dateEncoded)
}else{//if no id was found, INSERT a new row
//$query = "INSERT INTO $databasetable VALUES(";
if($databasetable == 'patient'){$query = "INSERT INTO $databasetable VALUES(";}
else{$query = "INSERT INTO $databasetable ($list_columns) VALUES(";}
$i = 0;
while ($i < $countColumns){
if($linearray[$i] == "NULL"){
$query .= $linearray[$i];
if($i == ($countColumns-1)){$query .= ");";}else{$query .= ",";}
}else{
$query .= "'" . $linearray[$i];
if($i == ($countColumns-1)){$query .= "');";}else{$query .= "',";}
}
$i = $i + 1;
}//end While
}// close if ($countResults > 0){
//$queries .= $query . "\n";
//print "$query<br />";
#mysql_query($query);
//}//close if($header == 0)
}// close foreach(split($lineseparator,$csvcontent) as $line)
//unlink("data_uploading/files/" . $user . "/" . $databasetable . ".csv");
echo "Import successful! Found a total of $lines records in $table.file.\n<br /><br />";
//mysql_close($conn);
#mysql_close($con);
//====================================Get the Contents===================================
}//close foreach ($tables as $table)
//rmdir("data_uploading/files/" . $user);
//==========END OF INSERTING VALUES TO DATABASE ===========

Need Help on Export SQL to CSV through PHP

I have this PHP script which is supposed to take an SQL Query and output it to a CSV file, I know that when I run it i'm getting the right Statement put in but it does not seem to generate a file to my uploads folder.
Could anyone debug this for me?
<?php
function ExportExcel($statement)
{
$filename = "uploads/".strtotime("now").'.csv';
$sql = mysql_query("$statement") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
echo "error";
}
}
?>
If someone has a similar script that uses mysqli that would be nice
here is a example of a export script I use on my apps using MySqli. This will get you started...
<?php
function ExportExcel($statement){
$output = "";
$sql = mysqli_query($db , $statement);
$columns_total = mysqli_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_field_direct($sql, $i);
$output .= '"'.$heading->name.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "CSV_NAME_GOES_HERE.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
?>

Instead of saving CSV file how to Download the file

I am exporting data from a database using CSV extension and I want to download the results as a CSV file. How can I do that?
This is my code:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1)
{
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen($filename, "w");
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
echo "Data successfully exported";
fclose($fp);
} else {
echo "No data is Available";
}
}
How can I download it as a CSV file?
You need to set the HTTP headers correctly for a CSV file download and then instead of writing your query results to a CSV file on the local server, you need to write it to the PHP output buffer (php://output):
Full working example:
public function actionExportexcel() {
$con = mysql_connect("localhost", "root", "") or die();
mysql_select_db("fiducial", $con);
$filename = 'uploads/'.strtotime("now").".csv";
$query = mysql_query("SELECT * FROM
(
SELECT employeecode,name,dob,age,sex,employee_relation,company_id
FROM employeedetails
UNION
SELECT employeecode,father_name,father_dob,father_age,father_gender,father_relation,company_id
FROM employeedetails
WHERE father_name IS NOT NULL AND company_id IS NOT NULL
UNION
SELECT employeecode,mother_name,mother_dob,mother_age,mother_gender,mother_relation,company_id
FROM employeedetails
WHERE mother_name IS NOT NULL AND mother_dob IS NOT NULL
)t WHERE t.company_id = '56' ORDER by t.employeecode ") or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows >= 1) {
header('Content-Description: Your Download Name ');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=yourfilename.csv');
$rows = mysql_fetch_assoc($query);
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
$fp = fopen('php://output', 'w');
fputs($fp, $seperator);
mysql_data_seek($query, 0);
while($rows = mysql_fetch_assoc($query))
{
$seperator = "";
$comma = "";
foreach ($rows as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
} else {
echo "No data is Available";
}
}
Use
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename=<filename>.csv');

Submit SQL data to CSV file using PHP

Hi I am trying to submit msSQL data to create a csv file using PHP; however, when I click submit the csv file is never created. I am wondering if it has something to do with the way I am reading from my database. But I am new to php and sql programming and I am lost as to what is going wrong. Also I have no errors. My code is below.
<p>
<input name="submit" class="submit" type="submit" value="SUBMIT" />
</p>
<?php
if(isset($_POST['submit']))
{
$db = get_db_connection('swcrc');
$db->connect();
$filename = 'uploads/'.strtotime("now").'.csv';
$fp = fopen($filename,"w");
$db->query("SELECT [request_ID], [user_ID], [complete], [comment], [response_date], [animalClass], [animalCommon], [bioSurveyStatus] FROM dbo.Response");
$num_rows = mysql_num_rows($db);
$row = mysql_fetch_assoc($db);
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$name);
$comma = ",";
}
$seperator = "\n";
echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($db,0);
while($row = mysql_fetch_assoc($db))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$value);
$comma = ",";
}
$seperator = "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
?>
Thank you for the help and looking.

excel automatically open file after downloading in php

below is my codes for my excel. its functioning except for one thing. i don't see if my file is already save to excel.. can you help me how to automatically open my file after i download it.. i think something is missing or wrong in my codes.. so please. help . thanks.
{
$conn = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("copylandia",$conn);
//$fp = fopen($filename,"w+");
$filename = 'attachment'. date('Y-m-d') .'.csv';
$fp = fopen($filename,"w+");
$sql = mysql_query("select * from user") or die (mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w+");
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$name);
$comma = ",";
}
$seperator .= "\n";
//echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No records in the database!';
}
}
You can't force the browser/computer to open a file after download. The user must make that decision.
Although, since you are trying to make a CSV file, I will at least make a suggestion to help you out instead of crushing your dreams by telling you you can't do this:
Try fputcsv() instead of trying to make the string yourself:
I'm really cool! Click me!

Categories