Insert xml into MySql using PHP - php

I am trying to import xml data into a mysql table. I have the below fields to be Imported:
reference
price
category
type
city
property
imgurl1
imgurl2
The problem is that the number of <imgurl>(url to image file) is not the same. Below is the code:
$conn = mysql_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname,$conn) or die( mysql_error() );
$xml = simplexml_load_file('http://astonpearlemail.net/feeds/feedsmall.xml');
$data = $fields = array();
foreach ($xml->xpath('listing') as $listing) {
$fields = array_keys((array)($listing));
$data[] = '("' . join('", "', (array)$listing) . '")';
}
$sql = "INSERT INTO ap_prop (" . join(', ', $fields) . ") VALUES\n" ;
$sql .= join (",\n", $data);
$result1 = mysql_query($sql,$conn);
echo "<pre>$sql</pre>"
Please suggest how I can import the varying number of imgurl.
Thanks in advance

Related

Why is it saying no database selected?

When trying to post data to the database it gives an error saying no database selected. But the content from the database is displaying on a table and select menu.
<?php
$con = mysqli_connect("localhost", "root", "","radian");
if(!$con)
{
exit("Couldn't connect: ".mysqli_connect_error());
}
mysqli_set_charset($con, "utf8");
$insert_data = "UPDATE enquiries
SET ResponseDate = '".$current_date."',
Response = '".$txtResponse."',
Enquiry_No = '".$_SESSION['ses_staff']
."' WHERE Enquiry_No = '".$txtStudentId."'";
$execute = mysql_query($insert_data) or die(mysql_error());
$output= '<h4 style="margin-left:1em;width:15em;color:red;"> Response successful!. </h4>';
}else{
$output= '<h4 style="margin-left:1em;width:15em;color:red;"> </h4>';
}
Your final code should be identical to:
<?php
$con = mysqli_connect("localhost", "root", "", "radian");
if (!$con) {
exit("Couldn't connect: " . mysqli_connect_error());
}
mysqli_set_charset($con, "utf8");
$insert_data = "UPDATE enquiries SET ResponseDate = '" . $current_date . "', Response = '" . $txtResponse . "',Enquiry_No = '" . $_SESSION['ses_staff'] . "' WHERE Enquiry_No = '" . $txtStudentId . "'";
$execute = mysqli_query($con, $insert_data) or die(mysqli_error($con));
$output = '<h4 style="margin-left:1em;
width:15em;
color:red;"> Response successful!. </h4>';
Changes made:
Remove all instances of mysql_* and replace with the correct mysqli_* function.
Remove the orphaned } else {.
Note: Officially mysql_* functions are deprecated. So no point using them. Use either mysqli_* or PDO.

Insert multiple results into database PHP

This part is for gathering my data through an API.
foreach($result['List'] as $feedback)
{
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
}
This part is the code that I used to insert into my results directly after retrieving them.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
mysql_select_db('dctdb3');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Only one data is being inserted into the database and it is the last data displayed.
I was wondering how I can change my code so that I can insert all the data at the same time and not repetitive?
Thank you for your help.
Put the insertion inside the loop. Otherwise, the variables just have the last values that were set in the last iteration of the loop.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dctdb3');
foreach($result['List'] as $feedback) {
$date = date_create();
$date_entered = $feedback['DateEntered'];
$time = preg_replace('/[^0-9]/','',$date_entered);
//$comment = $feedback['Text'];
$ListingId = $feedback['ListingId'];
$BuyNowPrice = $feedback['BuyNowPrice'];
$max_bid = $feedback['MaximumBidAmount'];
$SellerId = $feedback['SellerId'];
echo '<div>' . "Seller ID: $SellerId" . " has sold one $ListingId for " . '$' . "$BuyNowPrice" . '</div>';
echo "<div>Feedback created at " . $time . "</div>";
echo '<br>';
$sql = 'INSERT INTO tmfeedback '.
'(SellerId,ListingId,BuyNowPrice) '.
'VALUES ('.$SellerId.', '.$ListingId.', '.$BuyNowPrice.'))';
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
echo "Entered data successfully<br>";
mysql_close($conn);
Make sure your second block of code is inside your first block of code (place your second block above the right-curly-brace). Then it will occur for each iteration of the foreach loop (each result) and insert a record for each one.
You cannot insert array into database hence place the query inside a loop. This thread may help you alot.

PHP SQL query to print results in webpage

I am trying to get my PHP script to print all rows i have in my database in a neat order. Currently Im not getting anything. My table has 4 columns, Name, Address, Long and Lat, and 2 rows with data. The table is called Locations. I am using the following code but im not getting to to work:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
Here is a simple example using pdo instead of mysqli
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
and you can echo out the data and format it yourself using a for loop like so
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
If the names are correct, this would echo out your row ID and row CITY. Just change the names to your field names. If you want further assistance, feel free to ask.
However, if you want to stick with mysqli, give the following code a wirl.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
change fieldname to the field you want to display
EDIT: Paste the following code. It will echo out the number of rows. This will tell you if the query statement is correct.
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS);
$stmt = $pdo->query("SELECT Name, Address, Long, Lat FROM Locations");
echo $stmt->rowCount();
Fetch query result as associative array and use for each to print all results
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>

PHP and MySql update

I'm newbie in PHP sorry. How can i update a user defined var in user defined table with user defined value in MySql? I cant get it work.
<?PHP
$table = $_POST['table'];
$id = $_POST['id'];
$key = $_POST['key'];
$value = $_POST['value'];
$con = mysql_connect("mysql.serversfree.com","u105645000***","mf***") or ("Cannot connect!" . mysql_error());
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("u10564500***" , $con) or die ("could not load the database" . mysql_error());
/*$mysql = mysql_query("INSERT INTO $table ($key) VALUES ('".$value."');");*/
$sql = "UPDATE $table Set ".$key."='".$value."'";
?>
Why your code is not working
You're not launching the query.
No where clause
Without specifying any conditions, every record of the coulmn $key will be updated with $value.
Solution
Use this code:
<?PHP
$con = mysqli_connect("mysql.serversfree.com","u105645000***","mf***","u10564500***");
$table = mysqli_real_escape_string($con,$_POST['table']);
$id = mysqli_real_escape_string($con,$_POST['id']);
$key = mysqli_real_escape_string($con,$_POST['key']);
$value = mysqli_real_escape_string($con,$_POST['value']);
if (!$con){die('Could not connect: ' . mysqli_error($con));}
$sql = mysqli_query($con,"UPDATE ".$table." Set ".$key."='".$value."'");
?>

How to decode JSON in PHP and insert it into Mysql table?

I'm using the following code in PHP.
Its creating the file post.json, but inserting values into the table is not reflecting.
<?php
$input = file_get_contents('php://input');
logToFile("post.json",$input);
$json_a = json_decode($input,true);
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
mysql_query("INSERT INTO order_table (Table_id, Menu_Item_Name, Menu_Item_Price, Menu_Item_quantity) VALUES('$json_a[TableId]','$json_a[ItemName]','$json_a[ItemPrice]','$json_a[ItemQuantity]')");
function logToFile($filename,$msg)
{
$fd = fopen($filename,"a");
$str="[".date("Y/m/d h:i:s")."]".$msg;
fwrite($fd,$str."\n");
fclose($fd);
}
?>
Try to replace '$json_a[foo]' with '" . $json_a['foo'] . "' or '${json_a['foo']}'.

Categories