Copy data from Salesforce - PHP toolkit and curl - php

I need some help here. I am working on an export from Salesforce to MySQL database.
I may be choosing the wrong path here as I am a novice in both. What I have right now is a simple php query to our Salesforce. The query right now just echos the results to HTML. What I need to do is have this script connect to a MySQL database and add or update the records in the database.
Using the Salesforce PHP Toolkit my connection and query is this simple bit. (Appologies for the ugly inline html.
$query = "SELECT Id, FirstName, Random_Last_Initial__c, Created_Date__c, Building_Zip_Code__c from Lead";
$queryResult = $mySforceConnection->query($query);
$records = $queryResult->records;
foreach ($records as $record) {
$sObject = new SObject($record);
echo "<ul style='list-style:none;'>";
echo "<li>Id = ".$sObject->Id;
echo "</li><li>First Name = ".$sObject->fields->FirstName;
echo "</li><li>Initial = ".$sObject->fields->Random_Last_Initial__c;
echo "</li><li>Date Created = ".$sObject->fields->Created_Date__c;
echo "</li><li>Zip = ".$sObject->fields->Building_Zip_Code__c;
echo "</li></ul>";
}
All of that is fine, i just need to dump the results into the database.
Thanks!

Should work
$dbh = New PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
foreach ($records AS $record)
{
$sObject = New SObject($record);
$stmt = $dbh->prepare ("INSERT INTO tablename SET sObjectId = :sid, firstName = :firstName, initial = :initial, createdDate = :created, zipCode = :zipcode");
$stmt -> bindParam(':sid', $sObject->Id);
$stmt -> bindParam(':firstName', $sObject->fields->FirstName);
$stmt -> bindParam(':initial', $sObject->fields->Random_Last_Initial__c);
$stmt -> bindParam(':created', $sObject->fields->Created_Date__c);
$stmt -> bindParam(':zipcode', $sObject->fields->Building_Zip_Code__c);
$stmt -> execute();
}
Just fill out your database settings, table name, and column names as appropriate

Related

How to return a plain object rather than an array of object [duplicate]

I have the following script which is good IMO for returning many rows from the database because of the "foreach" section.
How do I optimize this, if I know I will always only get 1 row from the database. If I know I will only ever get 1 row from the database, I don't see why I need the foreach loop, but I don't know how to change the code.
$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetchAll();
foreach( $result as $row ) {
echo $row["figure"];
}
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
example (ty northkildonan):
$id = 4;
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.
You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.
Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.
Did you try:
$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;
You could try this for a database SELECT query based on user input using PDO:
$param = $_GET['username'];
$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();
$result = $query -> fetch();
print_r($result);
If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php
how about using limit 0,1 for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.
$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;

Can't insert into sqlite3 database using PHP

I have a high scores table for a game hosted on this webhost. I'm using PHP with sqlite pdo extensions to have access to the database. I can't seem to figure out what is happening to the database, as the query is not being inserted into the database. I know that the
database is working and can be read from as I can get results out of the
database. I get no output on the webpage saying something is wrong.
Additionally, I've tried a couple of differint methods of sending the query like with $dbConn->query("Select * from something;");.
include_once("Includes/connectDB.php");
$level = $_POST['level'];
$name = $_POST['name'];
$score = $_POST['score'];
$salvage = $_POST['salvage'];
$asteroids = $_POST['asteroids'];
$diff = $_POST['diff'];
if(($level > 0) and ($level <= 5))
{
// make sure table exists
$tbName = getHiS_Tb_Name($level);
// insert data
$sql = "Insert into $tbName (NAME, SCORE, SALVAGE_COLLECTED, ASTEROIDS_DESTROYED, DIFFICULTY)
Values(:name , :score, :salvage, :asteroids, :diff);";
try{
$stmt = $dbConn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':score', $score);
$stmt->bindParam(':salvage', $salvage);
$stmt->bindParam(':asteroids', $asteroids);
$stmt->bindParam(':diff', $diff);
$stmt->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
}

Dynamical fetching from database - PHP

Simple problem.
I want to fetch data from database in array without knowing databse indexes. Like dynamic fetching. Let's say I want to fetch two columns from dbase named "name" and "lastname", but echo it using array without database indexes. Like shown in code below:
$sql = mysql_query("SELECT name, lastname FROM employees WHERE id = '1'");
$nameX=array();
while ($myrow = mysql_fetch_array($sql))
{
$nameX=$myrow;
}
foreach ($nameX as $bla)
{
echo $bla;
}
After this code is run it will echo:
JonJonSnowSnow
for the Jon Snow in database as name and lastname.
Little help?
It didn't seem to me a good practice, just relay your model consistency on a dynamic fetching. However I think it could be done using PDO (what is, by the way, a better to implement data acess).
This code probably will help you:
$pdo = new PDO("host;dbname", "user", "pass");
$sql = "SELECT name, lastname FROM employees WHERE id = :id;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
if($stmt) {
while(($row = $stmt->fetch(PDO::FETCH_OBJ)) !== false) {
foreach ($row as $key => $value) {
echo($value);
}
}
}

Can't get a prepared statement to print in php

I'm trying to get to grips with mysqli but finding it a struggle compared to the now depreciated mysql. So far with the old methods I've been able to get information back about my tables in an associative array. I'm trying to form a prepared statement and echo the id number back. I would also like to be able to print the whole sql statement that has been binded, but seen as I can't even echo the id number from a single SELECT statement, it is out of the question at the moment.
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?"
$statement = $db -> prepare($sql);
$statement -> bind_param("s", "Emma");
$statement -> execute();
$statement -> bind_result($id, $name);
$output = $statement -> fetch();
echo $output -> $id . " " . $name;
I seem to be getting lost at the line bind_result. I figured if statement is an object, then I should be able to echo them in the form I have devised? When I refresh my page I just get nothing. I have 2 entries in my table and 1 of them does have the name string that is used above.
You think too complex. Just try this:
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?";
$statement = $db->prepare($sql);
$statement->bind_param("s", "Emma");
$statement->execute();
$statement->bind_result($id, $name);
while ($statement->fetch()) {
echo $id . " " . $name;
}
The bind_result() methods takes care that for each $statement->fetch() you execute you get fresh values in the variables $id and $name.
You should take a look at the good documentation of those methods.

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories