Import JSON in MySQL DB from Import.io - php

I'm trying to import data from a JSON feed using PHP into a MySQL database.
I have the code below but am not getting anywhere with it.
I keep just getting Connected to Database but nothing is being pulled in from the JSON data.
The JSON data is being created from a feed using import.io.
Any help appreciated
JSON data here
<?php
$data = file_get_contents('https://query.import.io/store/connector/e18543ae-48d1-47d3-9dc7-c3d55cab2951/_query?_user=363ec2db-fb95-413f-9a20-3fe89acbf061&_apikey=HOXvwSMX4HlmqH123i5HeELV6BwKq%2BFRInTzXc4nfl5VtP0pJyChxMT9AEiu1Ozi0vWZmUB%2BKcSsxHz2ElHNAg%3D%3D&format=JSON&input/webpage/url=http%3A%2F%2Fsports.yahoo.com%2Fgolf%2Fpga%2Fleaderboard');
$array = json_decode($data, true);
$rows = array();
$index = 0;
foreach($array['results'] as $mydata)
{
print_r($mydata);
echo "<br>";
foreach($mydata as $key => $value)
{
print_r ($key);
print_r ($value);
echo $index;
echo "<br><br>";
$rows[] = "('" . $value . "')";
}
echo "<br>";
$index++;
}
echo "<br><br><br>";
print_r ($rows);
$values = implode(",", $rows);
echo "<br><br><br>";
print_r ($values);
$hostname = 'localhost'; // write the rest of your query
$username = 'username';
$password = 'password';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($values)");
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

First of here we have to fetch every row and then do another loop to fetch every value contained in that row, in this way we will obtain a 2D Array containing the data to format to put after in the db.
$i = 0;
foreach($array['results'] as $result){
foreach ($result as $key => $value)
$rows[$i][] = "'" . $value . "'";
$i++;
}
Then, here we format the data in order to fit our query that will be executed for every row fetched before.
try{
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
foreach ($rows as $row) {
$row = implode(",",$row); //making a string from an array with each item separated by comma
$query = "INSERT INTO import_io (total, round_1, round_2, round_3, round_4, thru, name/_source, name, today, name/_text, strokes) VALUES ($row)<br>";
$count = $dbh->exec($query);
}
$dbh = null;// close the database connection
}catch(PDOException $e){
echo $e->getMessage();
}

Related

MYSQL PHP PDO Fill table with database data

I want to give out a for every line in my database.
It seems that it is working but only returns the first column.
Note: There are values for the empty fields in database!
$columns = "Ticket, Last_Modified_Date, Requester";
Heres my code:
function getTicket($columns){
echo($columns);
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns);
foreach($rows as $row){
echo("<tr>");
foreach($col_names as $col_name){
if (!isset($row[$col_name])){
continue;
}
echo("<td>".$row[$col_name]."</td>");
}
echo("</tr>");
}
}
else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}
->fetch() returns only one value of the rows.
Use ->fetchAll() ( PHP Documentation ) if you want to return all of your results.
There are a couple of issues here, first you should use ->fetchall() which will return ALL the result rows in one hit into an array.
Second you are overwriting your $result statement handle with the row being returned by ->fetch
function getTicket($columns){
global $db_host, $db_name, $db_user, $db_pass;
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$result = $db->prepare("SELECT $columns FROM tickets");
if ($result->execute()){
echo("<b>Successfully!</b><br><br>");
// CHANGES HERE
$rows = $result->fetchall(PDO::FETCH_ASSOC);
$col_names = explode(',', $columns); //make array of csv
foreach($rows as $row){
foreach( $col_names as $col_name ) {
echo '<td>' . $row[$col_name] . '</td>';
}
}
}else{
echo("<b>FAILED!</b><br><br>");
}
$db = null;
}

PHP split a string and insert in MySQL

I am using AJAX to send an array of values to a PHP page that will insert the data into MySQL database. The problem is that I am not sure how to split the data into 5 different veriables and loop to insert into DB.
AJAX Request:
Array:
[".testimonial", 1119, 316, 1663, 608, "#header", 723, 66, 1663, 608]
Posting the array:
Sending Array Parameters using " ; " to split.
clicks
.testimonial;1119;316;1663;608;#header;723;66;1663;608
Source Sent:
clicks=.testimonial%3B1119%3B316%3B1663%3B608%3B%23header%3B723%3B66%3B1663%3B608
PHP Page
<?php
$clicks = $_GET["clicks"];
$clickArray = explode(";",$clicks);
$arrays = array_chunk($clickArray, 5);
foreach ($arrays as $array_num => $array) {
foreach ($array as $item_num => $item) {
echo "". $item . "<br/>";
}
}
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "clickmap";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (user_id, identifier_name, pos_x, pos_y, window_width, window_height, status)
VALUES ('1', '$postIdentifier', '$postPos_x', '$postPos_y','$postWindowWidth','$postWindowHeight', 'ok')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Current PHP Result:
.testimonial
1119
316
1663
608
#header
723
66
1663
608
New record created successfully
This should work, but using extract is usually not recommended as it can easily lead to bugs that are hard to debug.
$keys = array('postIdentifier', 'postPos_x', 'postPos_y','postWindowWidth','postWindowHeight');
foreach ($arrays as $array_num => $array) {
$values = array();
foreach ($array as $item_num => $item) {
$values[] = $item;
}
$data = array_combine($keys, $values);
extract($data); // now your variables are declared with the right values http://php.net/manual/en/function.extract.php
// .. run SQL insert here
}

PHP making a table extracting data out of sql database using pdo

I have a question about how I need to make a table with data from a database created in phpmyadmin using the pdo method. The connection to the database works and I got my data from a table in an array. But I need to make a table based on the data out of the table using a foreach loop.
<?php
include('connect.php');
try
{
$sql = 'select * from joke';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$output = 'There is a problem: '.$e->getMessage();
echo $output;
exit();
}
$aOrders = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$aOrders[] = $row;
}
var_dump($aOrders);
echo '<table>';
foreach($aOrders as $key => $value)
{
echo '<tr><td>'.$aOrders['id'].'</td><td>'.$aOrders['joketext'].'</td><td>'.$aOrders['jokeclou'].'</td><td>'.$aOrders['jokedate'].'</td></tr>';
};
echo '</table>';
?>
the 'id', 'joketext', 'jokeclou' and 'jokedate' are fields in my table and I want them to print it into a table.
In your foreach() you are trying to access the $aOrders array
echo '<tr><td>'.$aOrders['id'] ...
where you need to get the values in your => $values of foreach($aOrders as $key => $value)
echo '<tr><td>'.$value['id'].'</td><td>'.$value['joketext'].'</td><td>'.$value['jokec‌​lou'].'</td><td>'.$value['jokedate'].'</td></tr>';

Set cell to variable using PDO

I am trying to set a certain cell in a database to a variable in PDO. The code I am using now is:
$dbuser = "root";
$dbpass = "root";
$player = "ryr11";
//$player = $_GET["pname"];
try {
$conn = new PDO("mysql:host=localhost;dbname=users", $dbuser, $dbpass);
$stmt = $conn->prepare("SELECT * FROM players WHERE username = :player");
$stmt->execute(array("player" => $player));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
I want each column to have it's own variable, so I can echo the cell content. As of now, it is only showing it in an array.
echo $row['cell_name'];
fetchAll() returns an associative array.
while ($result = $stmt->fetch())
{
echo 'username : '. $result["username"].'<br />';
echo 'cell_name2 : '. $result["cell_name2"].'<br />';
echo 'cell_name3 : '. $result["cell_name3"].'<br />';
.....
...
etc
}
or you can use a html table style

Two Dimensional arrays and both indexes

I have data coming from a query and loading it into a 2 dimensional array inside a loop.
I have the below code but when it prints out the array the index is missing.
How do I load a 2 dimensional aray with the first index being the $id value and second index being the $UserEmail and then how would I loop through the array to pull out each index ($id, $UserEmail)?
//the query
$query = "select id, UserEmail from User";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$ue = $row['UserEmail'];
$id = $row['id'];
if (strpos($ue,','))
{
$UserArrayEmail = explode(',',$ue);
foreach ($UserEmailArray as $u)
{
$ArrayTerm[$id][] = $u;
}
}
}
//looping through the array and getting value from $id and $UserEmail
foreach( $ArrayTerm as $ArrayT ) {
print_r($ArrayT);
foreach( $ArrayT as $value ) {
echo $value . "<br/>";
}
}
Please help.
mysql_connect() is deprecated your solution should use PDO instead.
This is how it could be done with PDO and will fix the indexes:
//fetch array from query
try {
$dbh = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
} catch (PDOException $e) {
// db error handling
}
$sth = $dbh->prepare("select id, UserEmail from user");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
while($row = $sth->fetch())) {
$emails = $row['UserEmail'];
$id = $row['id'];
if (strpos($emails,',')) {
$UserEmailArray = explode(',',$emails);
foreach ($UserEmailArray as $email) {
$ArrayT[$id][] = $email;
}
}
}
//repeat the same but with PDO data with other loops
}
Additionally, storing a list of data (in your case emails) in a single db column is not great for db normalization.
You have no type safety (VARCHAR can containanything), no referential integrity, no way of actually processing the data with the db (in SELECTs, JOINs etc).
For the db, the list of email addresses is just a bunch of random characters.
The relational database model has a simple rule: one attribute, one value. So if you have multiple values, you have multiple rows. That's what you should fix first. You'll need another table named "user_email_addresses" or something.
With this new table it could be something like:
function html_escape($raw) {
return htmlentities($raw, ENT_COMPAT , 'utf-8');
}
function log_exceptions($exception) {
echo $exception->getMessage(), '<br />', $exception->getTraceAsString();
}
set_exception_handler('log_exceptions');
$database = new PDO( 'mysql:host=localhost;dbname=DB', 'USER', 'PASS', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
$user_emails = array();
$emails = $database->query('
SELECT user_id , email
FROM user_email_addresses');
foreach ($emails as $email)
$user_emails[ $email['user_id'] ][] = $email['email_address'];
//address list
foreach ($user_emails as $user_id => $email_addresses) {
echo 'User: ' . html_escape($user_id) . '<br />';
foreach ($email_addresses as $email_address)
echo html_escape($email_address) . '<br />';
echo '<br />';

Categories