How to solve this message Access denied for user 'dbtsorder'#'localhost' (using password: YES) this message appear only online on localhost work fine
i try to load in file from csv file and this message appear only where this code is
database connection:
$host="localhost";
$user="dbtsorder";
$password="M#07765729s";
$db="tsorder";
$conn=mysqli_connect($host,$user,$password,$db);
mysqli_query($conn,"SET NAMES utf8");
mysqli_set_charset($conn,'utf8')
/*************************************/
Load in file code:
if(isset($_POST['submit'])){
$link = realpath('/var/www/order/projectmanagment/');
$checklist = $link.'checklist.csv';
$username=$_SESSION['username'];
$query=mysqli_query($conn,"select* from tbl_user where db_username='$username'")or die(mysqli_error($conn));
$res=mysqli_fetch_array($query);
$fname=$res['db_fname'];
$lname=$res['db_lname'];
$name=$res['db_fname'].' '.$res['db_lname'];
$projectname=$_POST['dep'];
$location=$_POST['cname'];
$psd=$_POST['txt_psd'];
$pdd=$_POST['txt_pdd'];
$past=$_POST['txt_past'];
$padd=$_POST['txt_padd'];
$duration=$_POST['duration'];
$aduration=$_POST['txt_aduration'];
$pnote=$_POST['txt_pnote'];
$transferredto=$_POST['txt_transferredto'];
$client=$_POST['txt_client'];
$cpercentage=$_POST['txt_cpercentage'];
$epercentage=$_POST['txt_epercentage'];
$mpercentage=$_POST['txt_mpercentage'];
$sum=$cpercentage+$epercentage+$mpercentage;
if($projectname=="" || $location=="" || $psd=="" || $pdd=="" || $client=="" ){
echo"Enter All Information.";
}
else{
if($sum==100){
$_SESSION['projectname']=$projectname;
$sql=mysqli_query($conn,"INSERT INTO tbl_project(db_projectname,db_location,db_transferredto,db_psd,db_pdd,db_duration,db_past,db_padd,db_aduration,db_pnote,db_user,db_client,db_cpercentage,db_epercentage,db_mpercentage)VALUES('$projectname','$location','$transferredto','$psd','$pdd','$duration','$past','$padd','$aduration','$pnote','$name','$client','$cpercentage','$epercentage','$mpercentage')")or die(mysqli_error($conn));
$import=mysqli_query($conn,"LOAD DATA INFILE '$checklist' INTO TABLE tbl_checklist FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' set db_projectname='$projectname' ")or die(mysqli_error($conn));
header("location:allproject.php?msg=2");
}else{echo"Percentage should be equal to 100";}}
}
You can use this code to read csv file and insert data into database
$row=1;
if (($handle = fopen("test.csv", "r"))!== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
$row++;
if($row>2)
{
if($data[0]!="")
{
//write your inset query
}
}
}
fclose($handle);
}
user this code this will work for you,
$data[0] is the first column, for second use $data[1] etc.
So by looking into my Crystalball the issue seems to be with your Permissions.
In mySql you'll have the choice to whitelist certain clients, i suggest you take a read from http://dev.mysql.com/doc/refman/5.7/en/create-user.html to understand how your users work
The next step would be to read the following to learn more about the meaning of permissions http://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html
What's the output of "SHOW GRANTS FOR dbtsorder"
Error is clearly showing that there is a connection problem, please check wheather dbtsorder user has access of tsorder or not. If not then first give this user access to particular database.
Related
I am working on a PHP/MySQL project, it must verify the following tasks:
-> The user uploads multiple large CSV files at a time with the same column names (X,Y,Z) in MySQL tables
-> The web app must perform an arithmetic operation between each csv file's column
-> The user can download the csv files after the operation as Excel files
For the upload part, i need to find a way to auto generate a table in the database for each csv file uploaded -instead of creating it in advance-, because the user should be able to upload as many files as he wants.
i tried to set a while loop that contains a create table, the loop goes from 0 to $var which is the number of csv files the user wishes to upload, however it doesnt add any table, here's the code for that part :
$con= getdb();
$var=$_GET["quantity"];
mysql_query("set $i=0;
while $i<`".$var."` do
create table `couche".$var."` ( X float NOT NULL,Y float NOT NULL,Z float NOT NULL);
set $i= $i+1;
end while");
}
Hi you can use the following way to achieve it :
<?php
//database connection details
$link = mysqli_connect('localhost','root','password','db_name') or die('Could not connect to MySQL');
// path where your CSV file is located
define('CSV_PATH','/var/www/html/skerp_scripts/');
// Name of your CSV file
$csv_file = CSV_PATH . "importItems.csv";
if (($handle = fopen($csv_file, "r")) !== FALSE) {
$header = true; //If there is a header in first row then set it to true
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
if($header == true){
/* Here you can perform checks whether all the column are as expected
for Eg: in CSV1 : id, firstname, lastname, age
in CSV2 : firstname, age ,id
Than you can tell the user that there is a misatch
*/
$header = false;
continue;
}
$column1 = $data[0];
$column2 = $data[1];
$column3 = $data[2];
$calculation = $column1 * $column3;
$result = mysqli_query($link, "INSERT INTO table_name (column1, column2, column3)" VALUES($column1, $column2, $calculation));
}
}
echo "File data successfully imported to database!!";
mysqli_close($connect);
I have a text file with 700,000 lines of login attempts some of which are successful but mainly - not. Here is an example:
login attempt 2 to server IP as user_name - password failed
login attempt 3 to server IP as user_name - password failed
login attempt 4 to server IP as user_name - **successful**
login attempt 5 to server IP as user_name - password failed
login attempt 6 to server IP as user_name - **successful**
and so on. How can I delete all lines that do not end with 'successful" word?
pseud-ocode:
convert all lines to separate arrays with each word as an array element
to write something like this (pseudocode):
while(line_number <= 700000) {
$all_occurrences .= (end($array) == 'successful') ? whole_line : '';
}
so only these will remain:
> login attempt 4 to server IP as user_name - **successful** login
> attempt 6 to server IP as user_name - **successful**
Any thoughts?
Thank you!
The best thing is to read the files line by line so you don't run into memory constraints.
Solution 1:
<?php
$if = '/tmp/login.attempts';
$of = '/tmp/login.attempts.purged';
$ifh = fopen($if, 'r');
$ofh = fopen($of, 'w');
while(($line = fgets($ifh)) !== false) {
if(preg_match('/successful/', $line)) {
fwrite($ofh, $line);
}
}
fclose($ifh);
fclose($ofh);
?>
Or if you want to use arrays like your sudo code.
Solution 2:
<?php
$if = '/tmp/login.attempts';
$contents = file_get_contents($if);
$all_attempts = explode("\n", $contents);
$successful_attempts = array();
foreach($all_attempts as $attempt) {
if(preg_match('/successful/', $attempt)) {
$successful_attempts[] = sprintf("%s", $attempt);
}
}
// The successful_attempts array contains all your entries
//print_r($successful_attempts);
?>
I recently built a web app which allows teachers to give grades to students and a lot of other stuff. Right now I'm adding a feature that gives the teacher the option to upload an excel/csv file with all the grades to the different students. My code seems fine however there are some issues with it and I can't figure out why. What happens is I get a bunch of blank records on my 'avaliacoes' table when I should only be getting 2 records.
How my excel looks :
1 (row) : naluno, uc, tipo, nota
2 (row) : r2011251, BD, exame, 15
3 (row) : r2011223, BD, exame, 16
(the first row isn't accounted for when inserting into the table)
My HTML code for the form (inside Diretor-Curso.php) :
<form class="form-group" action="lancarnota3.php" method="post" enctype="multipart/form-data">
<label class="control-label" for="uc">Enviar Ficheiro Excel/CSV com notas</label>
<br>
<input id="fileSelect" type="file" name="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<br>
<input type="submit" class="btn btn-default botao2" name="Submeter" value="Submeter"></button>
</form>
My PHP page (lancarnota3.php) which handles the upload :
<?php
if(isset($_POST["Submeter"]))
{
$conn = mysqli_connect("localhost", "root", "", "teste");
$conn->set_charset("utf8");
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($_FILES["file"]["tmp_name"], "r");
$count = 0;
while (($emapData = fgetcsv($file, 1000, ",")) !== FALSE)
{
$count++;
if($count>1){
$sql = "INSERT into avaliacoes (naluno, uc, tipo, nota) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysqli_query($conn, $sql);
}
}
fclose($file);
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas2'); </script>";
}
else
{
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas6'); </script>";
}
}
// close connection
mysqli_close($conn);
?>
Any idea how to make it work?
Are you sure that your data file doesn't contain empty line? Check the MySQL general log to see which queries were executed. I expect you will see the queries inserting the blank records in the log.
You could simply add a condition before the INSERT to check that you are trying to insert "non-empty" data, or perform additional validation to ensure that the data is indeed complete.
This was a silly one, so basically I had to change the comma (",") to a semi colon (";") because the csv was separating everything like that for some reason. and now it works perfectly. oh well hope this helps anyone :)
In one of my application, users can upload CSV file (| separated fields), after uploading I am storing all the content of file in temporary table (I truncate this table every time for new upload so that it contains the current file data). After that I am iterating over each and every row of that table, and performs some database operation as per the business logic.
The following code will illustrate this:
if(isset($_POST['btn_uploadcsv']))
{
$filename = $_FILES["csvupload"]["name"];
$uploads_dir = 'csvs'; //csv files...
$tmp_name = $_FILES["csvupload"]["tmp_name"];
$name = time();
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$csvpath = "$uploads_dir/$name";
$row = 0;
$emptysql = "TRUNCATE TABLE `temp`";
$connector->query($emptysql);
if (($handle = fopen($csvpath, "r")) !== FALSE) {
$str_ins = "";
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
/*
* Here I am getting the column values to be store in the
* the table, using INSERT command
*/
unset($data);
}
fclose($handle);
}
/*Here I am selecting above stored data using SELECT statement */
for($j=0;$j<count($allrecords);$j++)
{
echo "In the loop";
/*If I use echo statement for debugging it is working fine*/
//set_time_limit(300);
/* I have tried this also but it is not working*/
if(!empty($allrecords[$j]['catid']))
{
// Here is my business logic which mailny deals with
// conditional DB operation
}
echo "Iteration done.";
/*If I use echo statement for debugging it is working fine*/
}
}
The problem is when I execute aboe script on server it is giving server timeout error. But when I test above script on my localhost, is is working fine.
Also as mentioned in the code, if I use echo statements for debugging, then it is working fine, and when I remove that it starts giving connection timeout problem.
I have tried set_time_limit(300), set_time_limit(0), but none of them seems to work.
Any idea, how can I resolve the above problem.
-- Many thanks for your time.
Edit:
I have checked that, files are uploading on the server.
set_time_limit
change to
ini_set("max_execution_time",300);
When max_execution_time is not set in php.ini set_time_limit valid.
I have resolved the issue using flush, to send intermediate output to the browser, while the query is executing in the background.
This is how I modified the code:
for($j=0;$j<count($allrecords);$j++)
{
/*At the end of each iteration, I have added the following code*/
echo " ";
flush();
}
Thanks to the contributors over this link PHP: Possible to trickle-output to browser while waiting for database query to execute?, from where I got inspiration.
Hello i'm trying to import data from a .csv file into mysql table. Below is the script i'm working with. After running it, only print_r($_FILES) was executed, and it didnt insert into the data base.
<?php session_start(); ?>
<?php require('includes/dbconnect.php'); ?>
<?php require 'includes/header.inc.php'; ?>
<?php
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['csv_file']['name']; //Acquire the name of the file
$chk_ext = explode(".",$fname);
$filename = $_FILES['csv_file']['tmp_name'];
$handle = fopen($filename, "r"); //Open the file for readability
while (($data = fgetcsv($handle,1000, ",")) !== FALSE)
{
$sql = "INSERT into biodata (student_number, fname, lname, level) values('$data[0]','$data[1]','$data[2]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
print_r($_FILES) ;
?>
Your query has problem.
Its expecting 4 columns (as you specified in column list) but you supllied only 3 columns.
$sql = "INSERT into biodata (student_number, fname, lname, level) values('$data[0]','$data[1]','$data[2]')";
First of all check whether file was opened successfully:
$handle = fopen($filename, "r");
if( !$handle){
die( 'Cannot open file fore reading');
}
That's actually only place you're not handling correctly (hope you have error reporting turned on, because this could only be problem with fgetcsv() and error report would be crucial).
Once you've worked out how to access the uploaded file, you could also look into using LOAD DATA INFILE. If you use the LOCAL keyword (LOAD DATA LOCAL INFILE), that should work even on shared hosting. For some examples, see: http://dev.mysql.com/doc/refman/5.0/en/load-data.html
This has the benefit of being much, much faster than large numbers of INSERTs, which is especially relevant for large CSV files. Plus, it's quite easy to use.