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

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']}'.

Related

How to use Insert query in PHP code

I do not understand what is going wrong with code. The result is get is "connected successfully success Query failed". I tried few combinations and I get the same result. Please help me in solving this. Thanks in advance.
<?php
$link = mysql_connect('localhost', 'root1', '')
or die('Could not connect: ' . mysql_error());
if ($link) {
echo 'connected successfully';
}
$l = mysql_select_db('vtflix', $link) or die ('Could not select the database');
if ($l) {
echo ' success';
}
/*$varCNAME = 'John';
$varCONTENT = '4';
$varVID = '1';*/
$sql = "INSERT INTO mpaa(C_Name, ContentRating, V_ID) VALUES ('Jon', 4, 3)";
mysql_query($sql, $link) or die("Query failed");
$que = "SELECT * FROM mpaa";
$query = mysql_query($que, $link);
if (!$query) {
echo 'query failed';
}
while ($sqlrow = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row = $sqlrow['C_Name'];
$nrow = $sqlrow['Content Rating'];
$mrow = $sqlrow['V_ID'];
echo "<br>" . $row . " " . $nrow . " " . $mrow . "<br>";
}
mysql_close($link);
?>
1.Don't use mysql_* library (deprecated from php5 onward + removed from php7) .Use mysqli_* OR PDO.
2.An example of mysqli_*(with your code)is given below:-
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>
Note:- To check php version (either on localhost or on live server) create a file with name phpInfo.php, and just write one line code in that file:-
<?php
phpinfo();
?>
Now run this file and you will get the current php version.
Like this:- https://eval.in/684551
Here it seems that you are using deprecated API of mysql_* .
1) Check your PHP version
<?php phpinfo();exit;//check version ?>
2) avoid the usage of mysql use mysqli or PDO
3) change your db connection string with this :
new Mysqlidb($hostname, $username, $pwd, $dbname);
example with you code
<?php
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>

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.

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."'");
?>

Insert xml into MySql using 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

Strange behaviour trying to detect errors selecting a database

I have the following code in php:
<?php
$con = mysql_connect("localhost","john","john");
mysql_select_db("data", $con);
if (!$mysql_select_db) {
die ('Cannot use data : ' . mysql_error());
}
$result = mysql_query("SELECT * FROM test where huss='hussein'");
while ($row = mysql_fetch_array($result)) {
echo "ADSDAD";
echo "<br />";
}
if (!$con) {
die('ERROR Could not connect: ' . mysql_error());
}
mysql_close($con);
?>
I was able to connect to the MySQL server, but I can't seem to select the relevant database.
Being printed is the hard-coded text Cannot use data :, but no MySQL error message follows it. If the MySQL connection had failed then I would have expected a MySQL error message to appear after the hard-coded text.
What am I doing wrong?
The problem's here:
mysql_select_db("data", $con);
if (!$mysql_select_db) {
die ('Cannot use data : ' . mysql_error());
}
You don't have a variable $mysql_select_db, and it doesn't magically map to the result of the last time you called mysql_select_db.
So, instead:
$result = mysql_select_db("data", $con);
if (!$result) {
die ('Cannot use data : ' . mysql_error());
}
Or:
if (!mysql_select_db("data", $con)) {
die ('Cannot use data : ' . mysql_error());
}

Categories