I have tried just about everything i can think of (and searched plenty of threads here on Stack)
I am using the following:
try {
$db = new PDO('mysql:host=localhost;dbname=data', 'user', 'pass');
}catch (PDOException $e){
exit('Database Error.');
}
$fileName="file.txt";
$query = <<<eof
LOAD DATA LOCAL INFILE '$fileName' INTO TABLE data FIELDS TERMINATED BY '|' LINES TERMINATED BY '\r\n' (email, ip, referalurl, date, firstname, lastname);
eof;
$db->query($query);
echo "success";
now in my file (yes im aware its a .txt) its formated like below:
email#gmail.com|IP.IP.IP.IP|yourdomain.com|"2013-12-22 12:03:29"|firstname|lastname
any suggestions would be great.. btw the database connection is successful but no data ever gets saved into mysql for some reason..
I decided to go with mysqlimport (bash)
Related
I am literally out of my mind now. I've been staring at the screen for god knows how many hours, and I am out of ideas. I've been trying to connect MS SQL to PHP for two weeks now; and I think I'm already crazy lol
I went to the manufacturer of the device and they don't know the solution as well, as they don't use PHP.
I have this error:
And this is my codes:
<?php
/*
Connection for sqlsrv
*/
try {
$conn = new PDO( 'sqlsrv:server=(localdb)\\v11.0;'
. 'AttachDBFileName=C:\\PROGRAMDATA\\TOUCHLINK TIME RECORDER 3\\TA3.mdf;Database=TA3');
$query = 'SELECT EmployeeNo, FirstName, MiddleName, LastName FROM TA3.dbo.Employees ORDER BY EmployeeNo ASC';
$stmt = $conn->query($query);
$stmt->execute();
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And here is my SQL Server:
And here's the path where TA3.mdf is:
C:\ProgramData\Touchlink Time Recorder 3\TA3.mdf
PDO initialization parameters are wrong, mssql server is a client-server database, so usually you have to specify the IP address, PORT and maybe other settings. The right way to connect must be something like this:
$conn = new PDO('sqlsrv:Server=localhost\\SQLEXPRESS;Database=MyDatabase', 'MyUsername', 'MyPassword');
I suggest to read more about it at
http://php.net/manual/en/ref.pdo-sqlsrv.connection.php (thanks #YourCommonSense)
I have a PHP script below that I'm running every hour using a cronjob. Sometimes this script runs without any errors and other times it throws a 504 Gateway Timeout.
Can someone please help to improve the execution and efficiency of this script? I believe it can be written cleaner, but not sure where to start.
This is on a shared server and I do not have much control over the settings. Max timeout is 120.
Cronjob:
curl www.mysite.com/apps/script.php
PHP script:
<?php
set_time_limit(500);
$databasehost = "localhost";
$databasename = "foodb";
$databasetable = "footable";
$databaseusername="foouser";
$databasepassword = "foopass";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "inventory.csv";
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$sql = "TRUNCATE TABLE $databasetable";
$command = $pdo->prepare($sql);
$command->execute();
echo "Removed records from $databasename.\n<br />";
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)."IGNORE 1 LINES");
echo "Loaded a total of $affectedRows records from this csv file.\n";
/****/
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$sql = $pdo->exec("
UPDATE wp37_pmxi_posts
JOIN wp37_postmeta USING (post_id)
JOIN inventoryImport ON wp37_pmxi_posts.unique_key = inventoryImport.sku
SET meta_value = inventoryImport.qty
WHERE meta_key = '_stock'");
echo "Updated $affectedRows records after the import.\n";
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
?>
Thanks for your time and I appreciate any help.
I had the exact same issue last week and even though I am on a VPS server with a full root access, I didn't want to mess about with the files in the etc/ folder or php.ini or any other PHP settings...
So I came up with my own solution..
Please note this solution and this answer intended to just give you and other people an idea of how you could solve this issue without fiddling with server settings...
The solution was quite simple actually...
First i created an extra column in the MYSQL database with a pre-defined value of 0. You can name it anything you want.
What I did next was basically LIMIT my SELECT to 100.
something like:
SELECT * FROM mytable WHERE newColumn=0 LIMIT 100
And then I did whatever i wanted with this 100 selected items and every time I did that i UPDATE the database and changed the newColumn=1
And I repeated the same process until there is no more data in the MYSQL database with newColumn=0.
once I reach this stage, I UPDATE the table again and reset the newColumn back to 0.
Note that I run the process above on cron job.
This way your PHP won't get killed as you are only selecting 100 rows from the MYSQL.
hope this helps.
I'm working on a Pastebin-esque project in my free time, and last night I solved an issue I've had for a couple of days. (see this thread) However, I managed to mess it all up when I tried to make the code fetch a second column, 'Title'.
Please read the hyperlinked thread and look at Odin's answer or see the code below.
How can I make that code fetch multiple columns?
The code:
viewpaste.php:
require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;
connection.php:
try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
Just in case you need a little bit more of an explanation of my project, I'm making a pastebin clone (from scratch) and am trying to make a page where a user can enter the id of whatever paste they're wanting to view in the URL and have my code grab all the title and paste data of that id. This should all be done with $_GET, and I had it solved until I realized I never got titles working, and here we are.
Thanks!
Just specify the column in the SELECT query
$result=retrieve("SELECT title, paste FROM pasteinfo WHERE id=?", array($getid));
$row=$result->fetch();
$paste=$row->paste;
$title=$row->title;
SQL agent (in SSMS) is exporting output.csv (from query). Then it moves this csv file (comma delimited) into another server, where I run php script, which is automatically importing (task scheduler) this csv file into mysql database (xampp - phpmyadmin).
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));
echo "Loaded a total of $affectedRows records from this csv file.\n";
I would like to add something like: if this value U_ScID exists dont import this value.
WHERE T3.U_CreateDate > DATEADD(hour,-12,GETDATE()-1)
AND NOT EXISTS (SELECT T5.U_ScID FROM [xxx].[dbo].[table] where T5.U_ScID = T0.U_ScId)
Do you have any idea, how should I do it?
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>