SQL, PHP export to CSV - php

I have created this php script to pull some data from my database and export it to CSV.
I've got headers set to 0,1,2, but I need some static text in column 0.
Eg static, stock code, QTY.
The stock code, QTY are being pulled from the database.
Any help would be appreciated.
My code is below.
// open connection to mysql database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
// fetch mysql table rows
$sql = "select ManufacturerPartNumber, (QuantityOnHand - QuantityOnSalesOrder) from iteminventory";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));
$fp = fopen('inventory.csv', 'w');
fputcsv($fp, array('0', '1', '2'));
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp, $row);
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>

If I understand correctly, you want to put some kind of ID into the first column of your csv, so you have to add the "static" item in the first position of the array you'll get from sql result.
EDIT - updated to have static value in the first column
Example:
...
while($row = mysqli_fetch_assoc($result))
{
array_unshift($row, 0);
fputcsv($fp, $row);
}
...

Try this:
$header = array('Static', 'Stock code', 'QTY');
$fp = fopen('inventory.csv', 'w');
fputcsv($fp, $header);

This worked
$id = 0; // or whatever else you want to have in the first column
while($row = mysqli_fetch_assoc($result))
{
array_unshift($row, $id);
fputcsv($fp, $row);
$id;
}

Related

How to select data from 'logged in user' from database to a graph

I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards

How to get data from MySQL with PHP

Hello all I am tryin to build IOS app and I need to get data my MySQL database. I do not know php. I found a tutorial https://codewithchris.com/iphone-app-connect-to-mysql-database/
In section 3 where we create PHP service I copy it and edit for mine information. PHP code is like that
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
I load it the my server and nothings pops up just the blank page... Is there any reason or where is my mistake. Thanks for helps.
Have a nice day.
I didn't read you're whole code, but I'm pretty sure you're trying to put the results into a JSON format and echo them.
Here's an easy way to do so;
<?php
//
// EDIT: dont use this code, scroll a little bit lower to see the edit I made.
//
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// Puts all results in $row
$row = $res->fetch_assoc();
// echo & encode datas
echo json_encode($row);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);
Edit: The code above does work but only echoes the first row.
Here's one that actually echoes all of the rows in JSON format (tested).
<?php
//create connection
$con=mysqli_connect("localhost","myuserid","mypassword","i4142489_wp1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM treelibrary";
// Executes the SQL statement and puts results into $res
$res = $con->query($sql);
// Checks if there's any rows
if($res->num_rows > 0) {
// defines $data
$data = array();
// grabs all data and adds them to the $data array
while ($row = $res->fetch_assoc()) {
array_push($data, $row);
}
// echo & encode datas
echo json_encode($data);
} else {
echo "no data found";
}
// Close connections
mysqli_close($con);

creating new db rows from data in array?

Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}

JSON output from MySQL works, but then white screen appears?

I've used the below code to generate JSON from a MySQL table. It works great when I'm only generating 2 arrays, but for some reason when I try and generate 3 or 4 arrays, I get the "white screen of death". I thought it was happening because I needed to bump up my PHP Memory Limit, but I've done that and still get the same problem. See below:
The code that works is:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
But when I attempt to call more values, this is where I get the blank screen:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customertel'] = $row['customertel'];
//push the values in the array
array_push($json_response,$row_array);
}
var_dump($json_response);
echo json_encode($json_response);
?>
Update**
The error appears to be with my last line (echo json_encode ($json_response);
The following output is generated when I add print_r($row) before that last line.
Array ( [id] => 1 [customerfname] => First [customerlname] => Last [customeremail] => test#test.com [customerphone] => 000-000-0000
Update 2
Adding var_dump($json_response); before the echo json_encode line results in the blank screen.
For future reference: If someone else is visiting this question due to having a similar problem, the error with the blank page occurred since the query returned too many rows and json_encode() did not seem to be able to handle it.
Try the following, and share with us your result,
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db)
die('Could not connect to db: ' . mysql_error());
mysql_select_db("dbname",$db);
mysql_query('SET CHARACTER SET utf8');
$result = mysql_query("select `customerfname`, `customerlname`, `customeremail`, `customertel` from customer", $db) or die("Error: ".mysql_error());
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json_response[] = $row;
}
var_dump($json_response);
/* If the var_dump works, you can try and uncomment this section
if (function_exists('json_encode'))
{
echo json_encode($json_response);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
*/
?>
When you use flcose($db) that is going to cause some trouble. remove that line.
flcose is used to close ressources such as writing to text files.
to close connection use mysql_close():
mysql_close($db);
and also Your loop can be reduce to this:
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//push the values in the array
array_push($json_response,$row);
}
//Close the database connection
mysql_close($db);
echo json_encode($json_response);
and I would probably echo the json after closing the connection but thats no biggie.
And I find white screen of death very funny :D

Unable to execute fetch(PDO::FETCH_ASSOC) and not updating csv file

// First, prepare the statement, using placeholders
$query = "SELECT * FROM tableName";
$stmt = $this->connection->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "Hi";
// Export every row to a file
fputcsv($data, $row);
}
Is this correct way to do and if yes than why do I get false value for var_dump and than it does not go into while loop and does not write into csv file.
Any suggestions ?
One thing that is missing is that you first need to open the csv file:
$fp = fopen('file.csv', 'w');
then you can put data into it:
fputcsv($fp, $data);
As for the var_dump printing out false, you would have to provide more information about what objects you are actually using I think. (ie: what is $this->connection ?)
I don't know if this will help, but try to do it without the $this->connection:
$config['database'] = 'sakila';
$config['host'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$d = new PDO('mysql:dbname='.$config['database'].';host='.$config['host'], $config['username'], $config['password']);
$query = "SELECT * FROM actor";
$stmt = $d->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('file.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "Hi";
// Export every row to a file
fputcsv($data, $row);
}

Categories