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;
Related
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);
?>
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
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.
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);
I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??
//JAVASCRIPT makes a request
function profiles(){
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text");
}
function fillProfileCombo(res) {
alert(res);
}
//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows:
//RETURN PROFILE LIST
else if (!strcmp($opType, "getProfileList")){ //no param is coming
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$profiles = mysql_query(" SELECT DISTINCT profileName FROM `map_locations` ");
$row = mysql_fetch_array($profiles);
/*while() {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
*/
//$data = array();
//$row = mysql_fetch_assoc($profiles)
/*while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}*/
if ($row){
echo $row;
} else {
echo "ERROR occured";
}
}
//PROBLEM:
//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..
//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..
function fillProfileCombo(res) {
alert(res[0]); // does not work..
}
I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.
// PHP
$res = array();
while ($row = mysql_fetch_array($profiles)) {
$res[] = $row['profileName'];
}
header('Content-type: application/json');
echo json_encode($res);
// JavaScript
$.post('dbConn.php', { opType:"getProfileList" }, function(data) {
alert(data.length + " profiles returned");
}, "json");
Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like this:
//PHP
$data = array();
while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}
if ($data){
echo json_encode($data);
} else {
echo $data;
}
//JS
function profiles(){
//$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
}
function fillProfileCombo(data) {
alert(data[1].profileName);
}