PHP CSV Upload to MySQL Not Doing Anything - php

I wrote a script to download a google sheet, and then upload this sheet to my dadabase.
Everything seems to be working fine except that the data is now being uploaded to my database.
I navigated to the folder and then ran this command:
php -f updatedatabase.php
This is the script I wrote (the googel sheet key is filled in with the actual key--i tested the link and it is working, and the database credentials have been starred out for security reasons):
<?php
$datas = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
$datas = explode( PHP_EOL, $datas );
//FORMAT ("Name1", "Image1", "Description1", "Rarity1", "Price1", "Status1", "Store1"), ("Name2", "Image2", "Description2", "Rarity2", "Price2", "Status2", "Store2").....
// Info to connect to the database
$servername = ".com";
$dbusername = "";
$password = "!19";
$dbname = "";
$con=mysqli_connect( $servername, $dbusername, $password, $dbname );
mysqli_query( $con, "TRUNCATE TABLE Items" );
foreach ( $datas as $data ) {
echo $data . "\n";
mysqli_query( $con, "INSERT INTO Items (Name,Image,Description,Rarity,Price,Status,Store) VALUES " . $data );
}
mysqli_close($con);
?>

Your data string is not well formated:
$csvData = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
// format the data string
// work with PHP7.0 or later
$datas = array_map(function ($data) {
$dataString = implode("','", $data);
return "('$dataString')";
}, $array);
// remove the head line
array_shift($datas);
// Info to connect to the database
$servername = "192.168.10.10";
$dbusername = "homestead";
$password = "secret";
$dbname = "gooledoc";
$con = mysqli_connect($servername, $dbusername, $password, $dbname);
mysqli_query($con, "TRUNCATE TABLE Items");
foreach ($datas as $data) {
echo $data . "\n";
$result = mysqli_query($con, "INSERT INTO `Items` (`Name`,`Image`,`Description`,`Rarity`,`Price`,`Status`,`Store`) VALUES " . $data);
var_dump($result);
}
mysqli_close($con);

Related

Change PHP mssql to sqlsrv (mssql_fetch_row)

I have this code:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
$encode = array();
//$query = strtr($query, array('{$raum}' => $raum));
$query_result = mssql_query($query);
while ($row = mssql_fetch_row($query_result))
{
$encode[] = $row;
$text = $row[1];
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row[0] . "</h2>" . $text . "<br>";
}
I have to change the connections to the sqlsrv model. I managed to do it this way:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
//$params = array(SQLSRV_PHPTYPE_*);
$encode = array();
$query_result = sqlsrv_query($connection, $query);
if ($query_result === false){
die(print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_object($query_result))
{
//echo "Contenido de Row ". $row -> NOTES;
$encode[] = $row;
$text = $row -> NOTES;
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row -> SUBJECT . "</h2>" . $text . "<br>";
}
But I need to keep the structure in which I use the position of the array instead of calling the object.
Does anyone know of any way? Thank you very much.
Solution:
Function mssql_fetch_row() is part of the MSSQL PHP extension (mssql_ functions) and fetches one row of data as a numeric array. If you want to get the data in similar way using PHP Driver for SQL Server (sqlsrv_ functions), you should use sqlsrv_fetch_array() with SQLSRV_FETCH_NUMERIC as second parameter value.
Your code should look like this:
<?php
....
while ($row = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_NUMERIC)) {
$encode[] = $row;
// Additional code here ...
}
...
?>
Additional explanations:
If the SELECT statement returns more than one result set, you need to use sqlsrv_next_result() to make the next result of the specified statement active.
Example, using MSSQL extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$conn = mssql_connect($server, $username, $password);
mssql_select_db($database, $conn);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = mssql_query($sql, $conn);
// Fetch data
do {
while ($row = mssql_fetch_row($stmt)) {
echo print_r($row, true);
}
} while (mssql_next_result($stmt));
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Example, using SQLSRV extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$info = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $info);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = sqlsrv_query($conn, $sql);
// Fetch data
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo print_r($row, true);
}
} while (sqlsrv_next_result($stmt));
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Function equivalence:
The table below displays more information about the equivalence between the functions from each extension:
--------------------------------------------------------------------------------------
MSSQL PHP extension PHP Driver for SQL Server
--------------------------------------------------------------------------------------
mssql_fetch_assoc($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_row($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_ASSOC) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_array($stmt, MSSQL_NUM) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_BOTH) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)
mssql_next_result($stmt) sqlsrv_next_result($stmt)

creating table with a csv file to database mysql

I'm trying to create a table using my csv file with fields and I also have column headers inside my csv file. However, when I try to run it.. it just shows and gives me a query... I'm trying to find out what seems to be the problem and I'm stuck with it... can you help me on this? Thank
Here's my code
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "test";
$conn = new PDO("mysql:host=$server;dbname=$dbname", $username,
$pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Parameters: filename.csv table_name
$file = 'C:\Users\HP\Desktop\ACC.DBF.csv';
$table = 'acc';
// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($file,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = strtolower(trim($data[$i]));
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 20);
$field_count++;
$fields[] = $f.' VARCHAR(255)';
}
}
$sqlcreate = $conn->prepare("CREATE TABLE $table (" . implode(', ', $fields) . ')');
$sqlcreate->execute();
echo "Create Table success" . "<br /><br />";
//$db->query($sql);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
$fields = array();
for($i=0;$i<$field_count; $i++) {
$fields[] = '\''.addslashes($data[$i]).'\'';
}
$sqlinsert = $conn->prepare("Insert into $table values(" . implode(', ',
$fields) . ')');
$sqlinsert->execute();
echo "Insert Table success" ;
}
fclose($handle);
ini_set('auto_detect_line_endings',FALSE);
?>
I have created a utility script which does the same thing that you are trying.. Please check if it helps you.
<?php
$fileName = './WP.csv';
function connectDB()
{
$server = "mysql2345";
$username = "root";
$pass = "root";
$dbname = "sc1";
$conn = new PDO("mysql:host=$server;dbname=$dbname", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
function createDb($csv_path, $db)
{
if (($csv_handle = fopen($csv_path, "r")) === false) {
throw new Exception('Cannot open CSV file');
}
if(!isset($delimiter)) {
$delimiter = ',';
}
if (!isset($table)) {
$table = preg_replace("/[^A-Z0-9]/i", '', basename($csv_path));
}
if (!isset($fields)) {
$fields = array_map(function ($field){
return $field;
}, fgetcsv($csv_handle, 0, $delimiter));
}
$create_fields_str = join(', ', array_map(function ($field){
return "$field VARCHAR(200) NULL";
}, $fields));
echo $create_table_sql = "CREATE TABLE IF NOT EXISTS $table ($create_fields_str)";
$db->query($create_table_sql);
return ['table'=>$table, 'fields'=>$fields];
}
function loadData($fileName, $tableName, $fields, $db)
{
$fieldStr = implode(',', $fields);
$query = <<<eof
LOAD DATA LOCAL INFILE '$fileName'
INTO TABLE $tableName
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r'
($fieldStr)
eof;
echo $query;
$db->query($query);
}
$db = connectDB();
$tableInfo = createDb($fileName, $db);
loadData($fileName, $tableInfo['table'], $tableInfo['fields'], $db);

SQL syntax error in php code

I am passing value from android using POST and run the query in SQL DB using PHP. I am always getting
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1.
The code is working fine if i pass the values directly insted $_POST[].
I've gone through SO but no questions solved my problem. I tried with mysql_real_escape_string($searchTermBits) also but that doesn't worked.
PHP:
<?php
$username = "xxxx";
$password = "xxxx";
$host = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$search = $_POST["deskey"];
$search = explode(" ", $search);
$commonwords = "a,an,and,I,it,is,do,does,for,from,go,how,the,etc,in,on,are";
$commonwords = explode(",", $commonwords);
foreach ($search as $value)
{
if (!in_array($value, $commonwords))
{
$query[] = $value;
}
}
$query = implode(" ", $query);
$searchTerms = explode(" ", $query);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "description LIKE '%$term%'";
}
}
$myquery = "SELECT * FROM `logins` WHERE " . implode(' OR ', mysql_real_escape_string($searchTermBits)) . "";
$query = mysql_query($myquery);
if (!$query)
{
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++)
{
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What changes can i make this code to work with $_POST[].

null value when i opened the php script in IE

I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?

CSV output is duplicated

I am trying to output the database selected rows in csv format, but it outputs me duplicated values instead of single one. I want it to have columns and below the column the value. The output:
onlineId,paramId,paramValue 4cd87b00dddca780fcaf66d0108b25f6,4cd87b00dddca780fcaf66d0108b25f6,1,1,11,11
The code below:
$output = fopen('php://output', 'w');
fputcsv($output, array('onlineId', 'paramId', 'paramValue'));
$host = "localhost";
$database = "keytarget";
$username = "root";
$password = "";
$con = new PDO("mysql:host=" . $host . ";dbname=" . $database, $username, $password);
//Run our query
$sql = "
SELECT
ui.onlineId, uin.paramId, uin.paramValue
FROM
v5_userinfo ui
JOIN
v5_userinfo_number uin
ON
uin.userId = ui.id
;
";
$statement = $con->prepare($sql);
$statement->execute();
while ($row = $statement->fetch()) {
fputcsv($output, $row);
}
That's becouse when you retrieve the data it gives you a mix between an associative array and a normal array More info. So your $row var is something like:
array(
[0]=>4cd87b00dddca780fcaf66d0108b25f6
[onlineId]=>4cd87b00dddca780fcaf66d0108b25f6
[1]=>1
[paramId]=>1
[2]=>11
[paramValue]=>11
)
So your solution could be:
while ($row = $statement->fetch()) {
$array=array($row[0],$row[1],$row[2]);
fputcsv($output, $array);
}
Or an easier one:
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
fputcsv($output, $row);
}

Categories