PDO insert from one DB to another - php

I am trying to use PDO to read a SQLite DB and then insert into MYSQL.
The read is working and in the foreach I can echo out the SQLite data BUT when it comes to inserting into the new DB nothing logged and no data inserted at all.
try
{
$db = new PDO('sqlite:' . $passedFile);
$dbup = new PDO("mysql:host=localhost;port=8889;dbname=TestDB", "dbuser", "password");
//select all lines from the sqlite DB
$result = $db->query('SELECT * FROM TestDB');
foreach($result as $row)
{
$dbup->exec("INSERT INTO TestDB ('field1','field2','field3') VALUES ('" . $row['field1'] . "','" . $row['field2'] . "','" .$row['field3'] . "')");
}
// close the database connection
$db = NULL;
$dbup = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}

As idea, instead of using $dbup->exec($mysqlQuery)
try $dbup->exec($mysqlQuery) or die(print_r($dbup->errorInfo(), true));

Related

PHP PDO return a empty array the next day

I use php with PDO to manage a database with mysql. When I run the server I can read and insert data in the tables of my database, everything is correct. But, the next day I use my script, my code return a empty Array when I read and don't insert any data. Furthermore, my script don't throw any exception when does that, and I don't understand why.
I run my database connection with this code:
try {
$this->dataBase = new PDO('mysql:dbname=' . $this->dbName . ';host=' .
$this->host . ';port=' . $this->port,
$this->user, $this->pass);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
I get the data from my database with the code:
try {
$sql = $this->dataBase->prepare("SELECT username FROM teachers");
$sql->execute();
$result = $sql->fetchAll();
return $result;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$this->reconnect();
}
I do something wrong?

PHP file not pulling in .txt files anymore

I have a func.php file that grabs three .txt files from my server and inputs the data into a table in a MySQL database. I recently upgraded my PHP to 5.4 from 5.3 and this has caused an issue where it doesn't pull in the .txt files anymore but just deletes the table. In the update_training_db function, it runs empty_table but not move_file and load_csv. This code was working in 5.3 but I am not sure why it isn't grabbing the text files anymore. Can anyone help?
The whole PHP script consists of 4 functions as seen in the whole code. empty_table, move_file, load_csv, and update_training_db to execute everything.
The Problem:
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}
Whole file:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn_training = 'mysql:dbname=training;host=127.0.0.1';
$user = 'training';
$password = 'training';
try {
$dbt = new PDO($dsn_training, $user, $password);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
function empty_table($dbconn, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconn->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function move_file($filename){
$source ="/public_html/b3/" . $filename;
$dest = "/public_html/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
function move_files(){
try {
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
//echo json_encode($return);
}
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}

Amfphp Service Browser Not Displaying MySQL Result

I am developing my first project using Amfphp and am writing my first simple Service. Here is my getData method:
public function getData() {
// Connect to the database using PHP Data Objects (PDO).
try {
$pdo = new PDO('mysql:host=localhost;port=8889;dbname=amf_test', 'root', 'root');
} catch (PDOException $e) {
print "Connection Error!: " . $e->getMessage() . "<br/>";
die();
}
// Set an Error Handling mode.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully\n";
// Retrieve all rows.
$tsql = 'SELECT * FROM authors_aut';
$stmt = $pdo->prepare($tsql);
$stmt->execute();
// Echo the SQL Error Code
echo "SQL Error code: " . $pdo->errorCode() . "\n";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row_count = $stmt->rowCount();
echo $row_count.' rows selected' . "\n";
foreach ($pdo->query($tsql) AS $row) {
$id_aut = $row['id_aut'];
$fname_aut = $row['fname_aut'];
printf("Data: %s (%s) <br />", $id_aut, $fname_aut);
}
// Close the database connection
$stmt = null;
$dbh = null;
// Return the array.
return $results;
}
When I go to the Amfphp Back Office Service Browser, select my getData method and call it I get my comments but no data. Before I added my echo and printf lines I didn't the Service Browser returned nothing leaving me thinking my Service was not working (it still may not be!). My comments appear to show that I have successfully selected the data from the MySQL database but is it being returned?
I welcome your thoughts.
Chris

how to connect ( pull data ) from one server to ( insert into - create table ) another server using pdo in php-mysql , possibly fetch ?

Can anyone please tell me how could I fix this code below ? so that I can pull data from host1 (database x , table 1 ) to create table in host2 ( database dx, table2 ),
What am I missing here ? someone tell me to use prepare then fetch array then insert into table2 , can any one show me , how to ?
here's my code
<?php
echo 'Database Connection <br>';
$hostname = "host1";
$hostname1 = "host2";
$username = "myname";
$password = "mypassword";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=x", $username, $password);
echo "Connected to database x<br>"; // check for connection
$dbup = new PDO("mysql:host=$hostname1;dbname=dx", $username, $password);
echo "Connected to database dx<br>"; // check for connection
/*** The SQL SELECT statement ***/
$sql = $dbh->query("select name, choices from table1")or die(print_r($dbh->errorInfo(), true));
$sql1 = $dhup->query("CREATE TABLE api(
`name` VARCHAR(40) NOT NULL,
`choices` VARCHAR(255) NOT NULL )")or die(print_r($dbh->errorInfo(), true));
foreach ($sql as $row)
{
$dbup->exec("insert into table2('name','choices') values('" . $row['name'] . "','" . $row['choices'] . "')") or die(print_r($dbup->errorInfo(), true));
}
// /*** close the database connection ***/
$dbh = null;
$dbup = null;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
Thanks
I noticed you're not consistently spelling "dbup" the same way.
In:
$dbup = new PDO...
You used d'B'up.
In:
$dhup->query("CREATE TABLE...
You used d'H'up.
Maybe this is a simple case of a typographical error?

php - Add Script Not working

I'm having a problem with my update script. Basically I enter values into textboxes and when I click on 'Add' these values get added to the database.
At the moment it is allowing me to enter intergers and these getting added to the database but when I try to add text it doesn't. The database field types are set to varchar(20) and this is my PHP code:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
Please let me know what I am doing wrong! :)
Change the sql query line to:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
The thing is you are not escaping strings with quotes. Like 'someText'
You need to enclose your fields into quotes.
Put the text as such
$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
Or try this:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";

Categories