php json_encode echoes true - php

I have a code to make a query over my db, and get back the response and put them in fields over my html. I want to send the response via JSON, then create the fields using that information. But when I echo my json_encode($json_output) I only get a [true].
If anyone can explain me why I'll be appreciated.
Javascritp code:
$($cadView).find('#cadForm').on('submit', function(e){
e.preventDefault();
var str = $('#srBar').val();
if(str == ""){
alert("Campo de busca vazio.");
}else{
$.post($('#cadForm').attr('action'), {q : str}, function(data){
alert(data);
});
}
PHP code:
<?php
$q = $_POST['q'];
require('connect.php');
$i = 0;
$sql="SELECT `_nome`, `_endereco`, `_telefone`, `_imgstring`, `_dtAcesso`, `_descricao`, `_fkIdUser` FROM `tbvisitante` WHERE _nome = ?";
$stmt= $conn->prepare($sql);
$stmt->bind_param('s', $q);
if ($stmt){
$stmt->execute();
$stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);
while ($row = $stmt->fetch()){
$json_output[] = $row;
echo json_encode($json_output);
}
}
mysqli_close($conn);
?>

http://php.net/manual/en/mysqli-stmt.fetch.php
mysqli_stmt::fetch returns null or a boolean. You are binding the result to variables, those are what you're supposed to use.
Otherwise you may look into get_result instead of fetch.

Related

Fill a HTML select element with php, json and MySQL

With below function I get data from the database:
public function cargarPaises(){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "select idPais, nombre from paises";
$statement = $conexion->prepare($sql);
$statement->execute();
return $statement;
}
Then in this other file I call the function "cargarPaises":
<?php
require_once('../Modelo/class.conexion.php');
require_once('../Modelo/class.consultas.php');
$consultas = new Consultas();
$datos = $consultas->cargarPaises();
if (count($datos) > 0) {
while ($result = $datos->fetch(PDO::FETCH_ASSOC)) {
//printf ("%s (%s)\n", $result["idPais"], $result["nombre"]);echo"<br>";
//return $result;
//$nombre=$result['nombre'];
//$idPais=$result['idPais'];
//echo "<option value=".$idPais.">".$nombre."</option>\n";
//echo json_encode($result,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
echo json_encode($result);
}
}else{
return "No hay opciones en la BD";
}
?>
Now when I try to use the code in a jquery file:
$('#email').click(function(event) {
$.get('Controlador/cargarPaises.php', function(data) {
console.log(data);
});
});
I got the below in console (google chrome), All 427 records from my database (I am showing only 10):
echo json_encode($result); i got in console
{"idPais":"1","nombre":"Mexico"}
{"idPais":"3","nombre":"Albania"}
{"idPais":"4","nombre":"Alemania"}
{"idPais":"5","nombre":"Andorra"}
{"idPais":"6","nombre":"Angola"}
{"idPais":"7","nombre":"Antigua y barbuda"}
{"idPais":"8","nombre":"Antillas holandesas"}
{"idPais":"10","nombre":"Argelia"}
Now the question is how can I "play" with the variable "data" to fill a select HTML element.
First of all, you have a bug in your cargarPaises file. You're echoing a json encoding of the object for each row - you probably actually want to return an array of objects as a single json result. You're also returning a string for an error rather than an object that would let you know that. And finally, you're getting the count of a PDO statement, rather than the rowCount. Something like this would be better:
if ($datos->rowCount() > 0) {
echo json_encode($datos->fetchAll(PDO::FETCH_ASSOC));
} else {
echo json_encode(array());
}
I'd probably also modify your .get call for a start to explicitly state you're fetching json, and then add something like the following to build up the options:
$.get('Controlador/cargarPaises.php', function(data) {
$.each(data, function(idx, opt) {
$('#myselect').append('<option value="' + opt.idPais + '">' + opt.nombre + '</option>');
});
}, 'json');
public function cargarPaises(){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "select idPais, nombre from paises where 1"; //changed
$statement = $conexion->prepare($sql);
return $statement->fetchAll(PDO::FETCH_ASSOC); //changed
}
And the second file
require_once('../Modelo/class.conexion.php');
require_once('../Modelo/class.consultas.php');
$consultas = new Consultas();
$datos = $consultas->cargarPaises();
$results = (count($datos) > 0) ? $datos : array("error"=>"No hay opciones en la BD");
echo json_encode($results);

Angularjs getting result of post query

I'm making search in BD MySQL, but I can't get result I need. This is php code
$mass = json_decode(file_get_contents('php://input'), true);
foreach ($mass as $mass_item) {
if($mass_item['name']=="Наименование" && isset($mass_item['val']))
$exp=$mass_item['val'];
}
$query = "SELECT * FROM Companies WHERE LOWER(name) RLIKE
LOWER('".$exp."') ";
$result = mysql_query($query) or die();
while($row=mysql_fetch_array($result)){
echo json_encode($row);
}
This is an angular code
`
$http.post("search.php", value).then(function success (response) {
console.log(response);
console.log(response.data);
},function error (response){
console.log(response.data);
}
);`
As a result in console I see empty row "". But if I add one more echo before or in while, like echo $row['name'] in console will be all
expected result. I need to get query in json format to work with it. Please help.
you are trying to echo every row, change php code to something like that:
$resultJson = [];
while($row=mysql_fetch_array($result)){
$resultJson[] = $row;
}
echo json_encode($resultJson);
die;

autoComplete do not shows all data

I appplied autoComplete function to search box but when i key in some value in the search box, it always gv me the same result.
I realized i did not loop through the database, that's why i keep getting the same result.
I changed my query so that i can get what i want but the result still the same.
here is my ajax for autocomplete, and i'm not sure is it the right way to do it? But the search function is working except it do not display all the data.
function autoComplete(){
$('#keywords').autocomplete({
source: 'autoComplete.php',
minLength : 3,
select: function(event, ui) {
console.log(ui);
$('#chosenEvent').append(ui.item.value + "\n");
}
});
Here is the php code
<?php
// include the file for the database connection
include_once("database_conn_getOffers.php");
function autoC($conn){
$sql = "select eventTitle from te_events_special_offers eventTitle ORDER BY eventTitle";
$rsOffer = mysqli_query($conn, $sql);
//$offer = mysqli_fetch_all($rsOffer, MYSQLI_ASSOC);
$titles = array();
while($title = mysqli_fetch_assoc($rsOffer)){
$titles[] = $title;
}
foreach ($titles as $title)
return json_encode($title);
}
echo autoC($conn)
?>
Here is the link that i refer to click here
Thanks for your help!
So now, i changed the ajax method with the following code and it works but i still have no idea what wrong with my previous ajax code.
I also modified the php code by remove the foreach and added implode method
$.ajax({
method :"get",
url :"autoComplete.php"
})
.done(function(data, status, jqxhr){
var eventList;
console.log(data);
eventList = data.split(',');
$("#keywords").autocomplete({
minLength :2 ,
source : eventList,
select: function(event,ui){
console.log(ui);
}
//end autocompoete
});
});
Please try first to have results to encode, then we'll used them. Run this code along no other one at the same time, and tell us what you get (I assumed that you have columns ID + TITLE, if not, correct the code before using). Also, you original query seems weird -> $sql = "SELECT eventTitle FROM te_events_special_offers eventTitle ORDER BY eventTitle"; /* check bold part of it */
Plus : you should really think about prepared statements and error_reporting
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT idTitle, eventTitle FROM te_events_special_offers ORDER BY eventTitle "; /* check names used here and adapt to yours */
$stmt = $mysqli->prepare($query);
$results = $stmt->execute();
$stmt->bind_result($idTitle, $eventTitle);
$stmt->store_result();
if ($stmt->num_rows > 0) {
$events = array();
$event = array();
while($stmt->fetch()){
echo"[ $idTitle -> $eventTitle ]<br />";
$event["id"] = "$idTitle";
$event["title"] = "$eventTitle";
array_push($events, $event);
}
}
else
{ echo"[ no data ]"; }
print_r($events);
echo json_encode($events);
?>

return tables rows in json and print

I am trying to return ajax response in json, but when I print it in log it gives null even tables has rows,
my php code is:
if(isset($_GET['proid'])){
$projid = $_GET['proid'];
include(db.php);
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
}
ajax :
$.ajax({
url : 'getRecStudy.php',
type : 'GET',
data : {proid:study},
success : function(data) {
$('#tbody').empty();
$("#tbody").append(data);
console.log(data);
}
});
whats wrong?
I find no issue in your code except varibales. You need to debug the code in php file
if(isset($_GET['proid'])){
echo $_GET['proid'] . " is proid";
$projid = $_GET['proid'];
include(db.php);
echo "db connected";
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
echo "result fetched";
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
echo "inside while";
}
echo json_encode($dataarray);
print_r($dataarray);
exit;
}
after all this hit http://yourdomain.com/yourfile.php?proid=correctvalue
You will get the bug.
use parseJSON method in success function like this
var obj = jQuery.parseJSON( data );
alert( obj.name ); // For example name is a key

POST variable from SELECT into sql query to output to an INPUT

Using Chain SELECT works great from SELECT to SELECT, I'm trying to do SELECT to INPUT.
My mainpage.php
<label>Manufacturer</label>
<select>My Select statement is here</select>
<label>Model</label>
<select name="modelname">My Select statement is fed from the select above</select>
<label>Rating</label>
<input name="rating"></input>
This is the jQuery I have in the <head> section on the mainpage.php
<script>
$(document).ready(function(){
$("select#modelname").change(function(){
var id = $("select#modelname option:selected").attr('value');
$.post("assets/configs/getdata.php", {id:id}, function(data){
$("input[name='rating']").html(data);
console.log(data);
});
});
});
</script>
and finally the getdata.php
<?php
include "db.php";
$modelid = $_POST[id];
$sql = "SELECT EfficiencyRating FROM AllModels WHERE ModelID = '$modelid' ";
$res = odbc_exec($cnn, $sql);
while ($row = odbc_fetch_array($res)) {
$row_array[] = $row['EfficiencyRating'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Using the console log when this message is returned, how can I fix this?
HP Warning: array_push() expects parameter 1 to be array, null given in assets\configs\getdata.php on line 12
Try with this.
$res = odbc_exec($cnn, $sql);
$return_arr = array();
while ($row = odbc_fetch_array($res)) {
$return_arr[] = $row['EfficiencyRating'];
}
echo json_encode($return_arr);
JS Part
// Slightly modify the Request
$.post("assets/configs/getdata.php", {id:id}, function(data){
// JSON Object
console.log(data);
$("input[name='rating']").val(data);
}, 'json');
You need to declare $return_arr before the while statement. Also, I personally feel what you are doing is just not right. The proper way would be this...
$res = odbc_exec($cnn, $sql);
$return_arr = array(); //<----------- Here
while ($row = odbc_fetch_array($res)) {
array_push($return_arr,$row['EfficiencyRating']);
}
echo json_encode($return_arr);

Categories