ruzD ruzD - 1 month ago 7
JSON Question

Show JSON object from method POST in PHP language

I'm trying to retrieve a JSON object from a sql query of php file.

For this I make a html code with a form, action=queryProduct.php and method post.

HTML code:

<form action="queryProduct.php" method="post">
<input name="codigo" type="text" placeholder="codigo">
<input type="submit" value="TEST">
</form>


queryProduct.php:

<?php
session_start();

if(isset($_SESSION['username']) && $_SESSION['username'] <> ''){

include("functions.php");
include("tools.php");

$conn = Conectarse("localhost", "5432", "dbname", "dbuser", "dbpass");

$codigo = $_POST['codigo'];

echo $codigo;

$query = "SELECT * FROM produccion.ma_producto WHERE codigo={$codigo}";

$result = pg_query($conn, $query);

if (!$result) {
echo "Error query: " . pg_last_error($conn);
} else {
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
}

echo json_encode($result);

pg_close($conn);

} else{
?><p>La sesión no está activa, por favor ingrese <a href="login.php">aquí</a></p>
<?php
}?>


The idea is: it's make a JSON object from the query result and show the object with the browser:
echo json_encode($result);


Now It doesn't nothing :(

I have tested the sql query and it's working fine...

Answer

RTFM: http://php.net/pg_query

Return Values: A query result resource on success or FALSE on failure.

That result resource is NOT something you can json_encode(). You have to fetch result rows via that handle, put that into an array, and then encode that array.