I want to insert a json object value in mysql database using php. The object is:
{"data":[{"code":"1234",name:"nike"},{"code":"1034",name:"relexo"}]}.
The database table name is product and the fields name are code and name. How to insert this?
quick explination on how you could read a JSON file and append it to a table in the database:
<?php
//connect to DB
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
mysql_select_db("product", $con);
//read the json file contents
$jsondata = file_get_contents('empdetails.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the product details
$code = $data[code];
$name = $data[name];
//insert into mysql table
$sql = "INSERT INTO product(code, name) VALUES('$code', $name)"
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
this should be enough to get you going
Related
I want to pull data from a txt file called domains.txt and insert the contents of the file into a database. Below is the code i wrote but is not working.Please help me
<?php
$conn = mysql_connect("localhost","root","");
if (!$conn) {
die("Could not connect: " . mysql_error());
}
mysql_select_db("modify_domains");
$file = fopen("domains.txt", "r");
// Read line by line until end of file
while (!feof($file)) {
// Make an array using comma as delimiter
$array = explode(",",fgets($file));
$domain_name=$array[0];
$reg_email=$array[1];
$tech_email=$array[2];
$billing_email=$array[3];
$admin_email=$array[4];
$password=$array[5];
$sql = "INSERT INTO tbl_domains (domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES('".$adomain_name"','".$reg_email."',".$tech_email.",".$billing_email.",".$admin_email.",".$password.")";
mysql_query($sql,$conn) or die("Could not connect: " . mysql_error());
// use mysql insert query here
}
?>
All text fields must be separated by single quotes (like '".$reg_email."') and don't forget the point to separate text field and vars.
The query should be like that:
$sql = "INSERT INTO tbl_domains
(domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
('".$adomain_name."','".$reg_email."','".$tech_email."','".$billing_email."','".$admin_email."','".$password."')";
All text fields must be separated with single quotes. Also you could write it like this:
$sql = "INSERT INTO tbl_domains
(domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
('$adomain_name','$reg_email','$tech_email','$billing_email','$admin_email','$password')";
I'm using PHP files to output JSON data from a MySQL database. My code works just fine when I'm only pulling about 50 rows, however my database contains over 12,000 rows. Does anyone know how I might go about pulling more data without my server returning the "White screen of death"? Lol. My current code is below:
<?php
//Create Database connection
$db = mysql_connect("localhost","username","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer limit 50", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customerphone'] = $row['customerphone'];
$row_array['customercity'] = $row['customercity'];
$row_array['customeraddress'] = $row['customeraddress'];
$row_array['lastupdate'] = $row['lastupdate'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
If the first 50 rows are coming well, the problem is probably with the data...
i think a malicious single quote or something
You can try different sets of data by using limit like so.
for example if you want to check next 50 and skip first 50 with limit
$result = mysql_query("select * from customer limit 50, 50", $db);
i think you should try in sets of 1 to 50 , 50 to 100 and then narrow down to next 10 and find out which set and then which row / record is giving problem and then search out a solution for json encoding the problem area.
You could output json data according to GET/POST parameter, by paginating the results in your sql table. E.g., if you want the rows from 50th to 100th, you could do something like this:
<?php
//Create Database connection
$mysqli = new mysqli("localhost", "username", "password", "dbname");
if ($mysqli->connect_errno) {
die('Could not connect to db: ' . $mysqli->connect_error);
}
// Get the page we are interested in
$page = $_REQUEST['page']; // E.g. 1
//Replace * in the query with the column names.
$result = $mysqli->query("SELECT * FROM customer LIMIT ".(50*$page).",50");
//Create an array
$json_response = array();
while ($row = $result->fetch_assoc()) {
//push the values in the array
array_push($json_response,$row);
}
echo json_encode($json_response);
// free result set
$result->close();
//Close the database connection
$mysqli->close();
?>
Can't quite figure this one out. Not posting to MySQL. Not getting errors, just not posting.
<?php
$con = mysql_connect("localhost","XXXX","XXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXX", $con);
for( $i = 1; $i <= $count; $i++ )
{
$newtest1 = $_POST['test1'.$i];
$newtest2 = $_POST['test2'.$i];
$newtest3 = $_POST['test3'.$i];
}
$sql="INSERT INTO database (test1,test2,test3) VALUES ('".$newtest1."','".$newtest2."','".$newtest3."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
?>
Tried ('$_POST[test1]') and (' . $_POST['test1'.$i] . ')
$sql="INSERT INTO database (test1,test2,test3) VALUES ('".$newtest1."','".$newtest2."','".$newtest3."')";
Here there is a "table" which you want to insert a data.
You may get the idea of using $sql wrong.
I'll try to explain it from an example photo: PHOTO
As you see i have a database called "test" and a table in it which im inserting my data.
You should use this code and connect to that database:
mysql_select_db("XXXX", $con); //to select "my" database (on the example) type "test" to "XXXX"
The "database" you wrote here:
$sql="INSERT INTO database (test1,test2,test3) VALUES ('".$newtest1."','".$newtest2."','".$newtest3."')";
must be changed to your selected database. In this case you just wrote "XXXX" to that.
So the final code is:
$sql="INSERT INTO XXXX (test1,test2,test3) VALUES ('".$newtest1."','".$newtest2."','".$newtest3."')";
I am trying to combine PHP and Javascript, so that I get my data from the db in psql. So far, I am able to obtain the column I need, and set an array equal to this data. And then I am equating a js array to this array. This can be seen in the following code:
<?php
// attempt a connection
$dbh = pg_connect("host=localhost dbname=db user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM dataset";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$arr = pg_fetch_all_columns($result, 1);
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here's the js part.
var data = <?php echo json_encode($arr); ?>;
I have a function, which adds a data point to the array. I can add it to "data" array in js, but how do I make it so that it reflects in the db?
Thanks in advance :)
I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.