i am really new in explode and implode. I want to explode data from my database and enter the value to array so i can pass it to my HTML page with json_encode
This is my PHP file
<?php
session_start();
include "config.php";
$zzz = array();
$pass = array();
$idacara=mysql_real_escape_string($_GET["id"]);
$mysql = ("select kategori from acara where id_acara='$idacara'");
$result=mysql_query($mysql);
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$temp = explode(",",$row['kategori']);
$count = count($temp);
for($i=0;$i<$count;$i++)
{
$zzz=$pass[$i];
}
$fetchkategori[] = array
(
'kategori' => $zzz
);
}
}
mysql_close($con);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
This is my Ajax in HTML File
var arrKategori=new Array();
$.ajax({
url: host+'/skripsi3/phpmobile/kategori.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
if (arrKategori.indexOf(item.idkat)<0)
{
$("fieldset").append('<input type="radio" name="radiokategori" class="required" id="'+item.idkat+'" value="'+item.idkat+'" required><label for="'+item.idkat+'">'+item.kategori+'</label>').trigger("create");
arrKategori.push(item.idkat);
}
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
Thank You Before and Have a nice day :D
Well, first of all, do not use mysql_* functions. Instead use use mysqli_* or PDO functions.
You have to declare $fetchkategori[] outside the first if block in following way
$fetchkategori = array();
After that inside while loop, store the array in the following way.
$fetchkategori[] = array
(
'kategori' => $zzz
);
Your code will work.
Here is a complete solution using mysqli
config.php
$mysqli = new mysqli('mysql_hostname', 'mysql_username', 'mysql_password', 'mysql_database');
PHP file
<?php
session_start();
include "config.php";
$zzz = array();
$pass = array();
$fetchkategori = array();
$idacara=$_GET["id"];
//preparing query
$stmt = $mysqli->prepare("select kategori from acara where id_acara=?");
$stmt->bind_param('i', $idacara);
$stmt->execute();
$stmt->store_result();//add this line
$stmt->bind_result($kategori);
if ($stmt->num_rows>0)
{
while ($stmt->fetch())
{
$temp = $kategori;
$count = count($temp);
for($i=0;$i<$count;$i++)
{
$zzz=$pass[$i];
}
$fetchkategori[] = array
(
'kategori' => $zzz
);
}
}
mysqli_close($mysqli);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
Related
I'm working on a live search and i need to transfer php data to ajax using json, but the problem is i can't pass an array contain 2 or more identical values, this is the php code:
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
}
}
}
}
?>
And this is the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data){
$('#feedback').html(json_data.name);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
So, if my array contain 2 or more identical names ajax wont get any data back, I hope someone have an answer.
You should create array with all results in your search function and then in ajax response loop results to get all names and print it separated by comma.
Search function
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
$results = []; //<!---
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json; //<!---
}
}
}
echo json_encode($results); //<!---
}
}
?>
Ajax
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var names = [];
$.each(json_data, function(index, element) {
names.push(element.name)
})
$('#feedback').html(names.join(','));
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Change this:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
To:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json[] = array('img' => $img, 'name' => $name, 'username' => $username);
}
echo json_encode($json);
Inside your response for jQuery, retrieve your json data by looping it. Make sure to use var obj = jQuery.parseJSON( json_data ); before looping
I am passing the $place variable to a query in listplace.php using a ajax call. The ajax call works perfectly in php1.php code, but the $place value is not passed over the query. Please help!
listplace.php too works perfectly but when i try to pass $place in where condition it fails.
php1.php code
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
listplace.php
<?php
//connect to the mysql
$db = #mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
#mysql_select_db('test', $db) or die("Could not select database");
$place = $_POST['place'];
$sql = #mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r['product_name'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
?>
An improvement will be to start using prepared statements. This is just an addition to Exprator's answer
This will prevent SQL injection attacks.
$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
$place = $_POST['place'];//posted variable
if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false
$stmt->bind_param("s", $place); //bind the posted variable
$stmt->execute(); //execute query
$stmt->bind_result($product_name);//bind the result from query securely
$rows = array();//create result array
while ($stmt->fetch()) {//start loop
$rows[] = $product_name;//grab everything in array
}
if (count($rows)) {//check for number
echo json_encode(['option'=> $rows]);
} else {
echo json_encode(['option'=> false]);
}
change this line
data: {place: '<?= $_GET['place'] ?>'},
to
data: {place: '<?= $_GET["place"] ?>'},
I want to return multiple records instead of just 1 row.
JSON now returns only 1 row and I guess I need to add a while loop but not sure the right way to code it.
.js
function getq() {
var q = $("#q").val();
$.post(
'getq.php',
{q: q},
function(data) {
console.log(data);
}, "json"
);
}
getq.php
$q = $_POST['q'];
include("connect.php");
$sql = ("SELECT xxx FROM yyy WHERE zzz = $q");
if ($results=mysqli_query($db,$sql)) {
$result = $results->fetch_assoc();
echo json_encode($result);
}
EDIT:
I created the same case as yours on my pc, I used this javascript:
$.post('getq.php', {q: q}, function(data) {
console.log(data);
}
);
And this php (getq.php) file:
<?php
// Create connection
$mysqli = new mysqli( "localhost", "user", "passw", "db");
$q = $_POST['q'];
if ($results = $mysqli->query("SELECT xxx FROM yyy WHERE zzz = $q", MYSQLI_USE_RESULT)) {
$result_set = mysqli_fetch_all($results,MYSQLI_ASSOC);
echo json_encode($result_set);
$results->close();
}
?>
source: W3Schools
I've got a php file containing.
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
};
echo json_encode($name);
?>
ok can anyone tell me if there is anything wrong with this code. Any ideas on how this data would be displayed.
I could also do with some help at the other end what sort of jquery could would I use to read this data and how would it look, I'm very new to web design and don't know much jquery or how the ajax command would deal with this information.
Edit:
Current Jquery script
$.ajax({
url: "test.php"'
type: "post",
data: data,
datatype: "json",
success: function(result){
console.log(result["$name"]);
},
error: function(){
alert("error");
}
});
This is the code I've got to display some of the information in console, but I get nothing back, I get a data undefined message in console. Could really do with the help. Very new to json and jquery and php and webdesign as a whole. Thanks.
First of all, there shouldn't be ; after while loop.
$sampleArray = array();
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
array_push($sampleArray, array('name'=> $name, 'color' => $color, 'link'=>$link));
}
echo json_encode($sampleArray);
In your JQUERY/Javascript, something like this, in AJAX success:
response( $.map( data, function( item ) {
return {
name: item.name,
color: item.color,
link: item.link
}
}));
json_encode take one value parameter if you wanna encode multiple value you need to put them in an array
There is an example with your code
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
$result = array();
$i = 0;
while ($row = mysqli_fetch_array($grabCars)){
$result[$i]['name'] = $row["Name"];
$result[$i]['color'] = $row["Color"];
$result[$i]['link'] = $row["Link"];
$i++;
}
echo json_encode($result);
?>
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);