data insertion into database using json - php

trying to insert data using json. code executed and each case a blank row is getting inserted instead of the specific given value into the table.. help me to correct this.. the code is given below.
<?php
header('Content-Type: application/json');
include('dbconnect.php');
$json = isset($_POST['submit']) ? $_POST['submit'] : "";
$new = json_decode($json, true);
$sql="INSERT INTO emp(name,address,vicechancellor)
values
('".$new['name']."','".$new['address']."','".$new['vicechancellor']."')";
$res = mysqli_query($con,$sql);
if($res)
{
echo "created ";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>

Related

How to run .ktr transformations in PHP

I developed the following API in PHP / HTML:
I need the result of the select option to serve input to the following ETL transformation:
I used "RJ" as an example in the query. But I need this result to come from the API. What step can I use to recover this data?
Is the reverse process possible? Can I make the result of this transformation available (which is an excel worksheet) for the user to download?
Edit 1: That's how I get the form results. It's a simple PHP code.
<?php
$conexaobd = new ConexaoBD;
$conexao = $conexaobd->conectarAoBD();
$buscar=$_POST['buscar'];
$sql = "SELECT p.id_projeto, p.municipio, p.estado, p.nome FROM projeto p WHERE p.estado LIKE '%".$buscar."%' ORDER BY p.id_projeto";
$resultado_query = mysqli_query($conexao, $sql);
if (!$resultado_query) {
echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);
}
if (!$linha = $resultado_query->fetch_array(MYSQLI_ASSOC)){
echo "<h3>Nenhum registro encontrado.</h3>";
} else {
while($linha = $resultado_query->fetch_array(MYSQLI_ASSOC)){
$id = $linha['id_projeto'];
$municipio = $linha['municipio'];
$estado = $linha['estado'];
$nome = $linha['nome'];
echo "<h2><strong>ID do projeto: </strong>".#$id."</h2>";
echo "<br/>";
echo "<strong>MunicĂ­pio: </strong>".#$municipio;
echo "<br/>";
echo "<strong>Estado: </strong>".#$estado;
echo "<br/>";
echo "<strong>Nome do projeto: </strong>".#$nome;
echo "<br/>";
}
}
?>

Loop through a session variable with an array value

Is there any way to loop a session variable with an array value to insert into the database?
$list_application which where I store the array value
You will see in my code that I've directly insert the $list_application and it returns an Array when I printed it out.
if(isset($_POST['submit'])) {
include('includes/dbconn.php');
$list_application = $_SESSION['LIST_APPS'];
$currUser= getenv("username");
$get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'$list_application', '$list_application','$currUser')";
if($conn->query($get_data) === TRUE ) {
include('includes/dbconn.php');
} else {
echo "Error: " . $get_data. "<br>" . $conn->error;
}
$conn->close();
header('location: summary.php');
}
if I understood your question correctly, then what yyou need is to implode the array to a string that would match the insert:
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
and in you code, notice I changed the INSERT a bit:
if(isset($_POST['submit'])) { include('includes/dbconn.php');
$list_application = implode("','", $_SESSION['LIST_APPS']) ;
$currUser= getenv("username"); $get_data = "INSERT INTO technologyresults(examdate, technology, prof, eid) VALUES(CURDATE(),'".$list_application. "','$currUser')"; if($conn->query($get_data) === TRUE ) { include('includes/dbconn.php'); } else { echo "Error: " . $get_data. "<br>" . $conn->error; } $conn->close(); header('location: summary.php'); }

How to save data to a database from file_get_html($url)?

I can't save data to database from file_get_html($url) function. My script is showing data nicely by scraping from a url. But I can't save the showed data to a database. It shows error between object and array. I can't even show data by array index. Such as $value[0]. Here is my code sample:
$con=mysqli_connect("localhost","root","","crawler");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
require 'simple_html_dom.php';
$url = "http://www.realestate.com.au/sold/in-perth/list-1";
//Address Collection
$html = file_get_html($url);
foreach ($html->find("h2") as $key => $value){
echo $value."<br>";
$result = mysqli_query($con,"INSERT INTO data (info) VALUES ('$value')");
if (!$result){
echo "Error!<br>";
}
}
mysqli_close($con);
?>
Try this and let me know if it works:
$con=mysqli_connect("localhost","root","","crawler");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
require 'simple_html_dom.php';
$url = "http://www.realestate.com.au/sold/in-perth/list-1";
//Address Collection
$html = file_get_html($url);
foreach ($html->find("h2") as $key => $value){
echo $value."<br>";
}
$value = base64_encode($value);
$result = mysqli_query($con,"INSERT INTO data (info) VALUES ('$value')");
if (!$result){
echo "Error!<br>";
}
mysqli_close($con);
?>
$value need convert to a string before write to DB. You can show array or object use
echo '<pre>';
print_r($value);
echo '</pre>';
or
var_dump($value)

Grabbing data from steamapi (json) and importing it to mysql

I can't quite figure out how to import data from remote json (steamapi) into MySql.
<?php
$con = mysql_connect("localhost","XXXXXXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXXXXXXXXXXX");
mysql_select_db('XXXXXXXXXXXXXXXXX',$con);
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXXXXXXXXXX&steamids=76561198033811393";
$json = file_get_contents($url);
$result = json_decode($json);
foreach($result as $key => $value)
{
if($value)
{
mysql_query("INSERT INTO steam (steamid,
communityvisibilitystate,
profilestate)
VALUES ($value->steamid,
$value->communityvisibilitystate,
$value->profilestate)");
}
mysql_close($con);
}
?>
Steam JSON Image(click for full size):
You can read each player using $data->response->players, it will be assigned to $player where then, you can directly access their object like $player->steamid. See below example:
$data = json_decode($json);
foreach($data->response->players as $player)
{
echo $player->steamid, "\n\n";
}
I also suggest you change your query like this:
$query = sprintf("INSERT INTO steam (steamid,
communityvisibilitystate,
profilestate) VALUES ('%s','%s','%s')",
mysql_real_escape_string($player->steamid),
mysql_real_escape_string($player->communityvisibilitystate),
mysql_real_escape_string($player->profilestate));
To prevent any further issues like broken strings or injections.
Resulting code for the SQL part would be:
// Build the query
$query = sprintf("INSERT INTO steam (steamid,
communityvisibilitystate,
profilestate) VALUES ('%s','%s','%s')",
mysql_real_escape_string($player->steamid),
mysql_real_escape_string($player->communityvisibilitystate),
mysql_real_escape_string($player->profilestate));
// Perform Query
$insert = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$insert)
{
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query . "\n";
echo "------------------\n";
}
Given your actual code it would look like this:
<?php
$con = mysql_connect("localhost","XXXXXXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXXXXXXXXXXX");
mysql_select_db('XXXXXXXXXXXXXXXXX',$con);
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXXXXXXXXXX&steamids=76561198033811393";
$json = file_get_contents($url);
$data = json_decode($json);
foreach($data->response->players as $player)
{
// Build the query
$query = sprintf("INSERT INTO steam (steamid,
communityvisibilitystate,
profilestate) VALUES ('%s','%s','%s')",
mysql_real_escape_string($player->steamid),
mysql_real_escape_string($player->communityvisibilitystate),
mysql_real_escape_string($player->profilestate));
// Perform Query
$insert = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$insert)
{
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query . "\n";
echo "------------------\n";
}
}
mysql_close($con);
Use this
<?php
$id = $_GET['id'];
$key = 'xxx';
$link = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&steamids=76561198033811393&format=json');
$myarray = json_decode($link, true);
$result = $myarray['response']['players'][0];
echo $result->steamid;
?>
if you get more then one result use foreach format given below
$result = $myarray['response']['players'];
foreach($result as $key => $value)
{
echo $value->steamid."<br>";
}

Printing result of mySQL query with INNER JOIN

I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}

Categories