I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>
Related
I have tried this code but receiving error.
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data = [];
foreach($row as $key) {
$data[] = [
'first_name' => $key['first_name'],
'last_name' => $key['last_name']
];
}
echo json_encode($data);
How can I json encode specific keys using php ?
I have solved..
$queryfetch = 'select * from table';
$result = mysqli_query($connection, $queryfetch);
$row = mysqli_fetch_assoc($result);
$data[] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name']
);
echo json_encode($data);
This code is working very well..
How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
I am stuck with ajax... I have a cart and it has gift vouchers,
i) the code checks for valid voucher and if its not valid then it should show message "invalid voucher".
ii) If voucher if valid and is set in db,then change the cart total using gift amount.
So I have set the message , but i dont know how to dislay it.And Using gift i have stored the new cart total ie gift_cart_total.In db, i have fields for cart_total,voucher , gift_cart_total.How can i remove my original cart div and show new div using gift_cart_total.
View:
<div class="giftvoucher">
<input type="text" name="gift_voucher_number" id="gift_voucher_number" placeholder="Voucher Number" value="" size=18>
<input type="text" name="gift_voucher_pin" id="gift_voucher_pin" placeholder="Voucher Pin" value=""size=18>
<input type="button" value="Apply" onclick="checkGiftVoucher()" id="apply_button">
</div>
<script type="text/javascript">
function checkGiftVoucher(){
var gift_voucher_number = $("#gift_voucher_number").val();
var gift_voucher_pin = $("#gift_voucher_pin").val();
$.ajax({
type: "POST",
url: "<?php echo base_url('cart/giftvalidate'); ?>",
data: {gift_voucher_number:gift_voucher_number,gift_voucher_pin:gift_voucher_pin} ,
success: function(data){
return false;
},
});
}
</script>
Controller:
public function giftvalidate(){
if(isset($_POST['gift_voucher_number']) && $_POST['gift_voucher_number'] != '' && isset($_POST['gift_voucher_pin']) && $_POST['gift_voucher_pin'] != ''){
$app21_url = APP21_URL;
$country_code = COUNTRY_CODE;
$gift_voucher_number = $_POST['gift_voucher_number'];
$gift_voucher_pin = $_POST['gift_voucher_pin'];
$result = $this->cart_model->checkValidGift($gift_voucher_number, $gift_voucher_pin, $app21_url, $country_code);
if($result['databool'] && !empty($result['dataValue'])){
$discount = $result['dataValue']['AvailableAmount'];
}else{
$gift_flash = $result['datamsg'];
}
}elseif(isset($_POST['gift_voucher_number']) && (empty($_POST['gift_voucher_pin']) || $_POST['gift_voucher_pin'] =='')){
$result['datamsg'] = "Please enter the gift voucher pin";
}
echo json_encode($result);
}
Model :
function checkValidGift($gift, $gift_pin, $app21_url, $country_code){
$returndata = array();
$dataValue = array();
$datamsg = '';
$databool = false;
$cartTotal = $this->getTotalCart();
$GVValid_url = some url here;
$headers = array(
"GET HTTP/1.1",
"Content-type: text/xml",
"Accept: Version_2.0"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GVValid_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 900);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$data = curl_exec($ch);
if (curl_errno($ch)) {
$result = 'cURL ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
$databool = false;
$datamsg = 'Gift Voucher & pin are not Valid';
}else if($gift='100038' && $gift_pin='7655'){
$gift='100038';
$AvailableAmount = '200';
if ($AvailableAmount > $cartTotal) {
$gift_cart_total = $cartTotal;
}else{
$gift_cart_total = $cartTotal-$AvailableAmount;
}
if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){
$user_type = 'Guest';
$user_id = $this->session->userdata('__ci_last_regenerate');
}else{
$user_type = 'Member';
$user_id = $this->session->userdata('s_uid');
}
$insertData = array(
'user_id' => $user_id,
'gift_id' => $gift,
'pin' => $gift_pin,
'gift_amount' => $AvailableAmount,
'gift_cart_total' =>$gift_cart_total
);
$table = 'cart_mast';
$sql = "SELECT * FROM $table WHERE user_id = '{$user_id}'";
$query = $this->db->query($sql);
if($query->num_rows() != 0){
$carts = $query->result_array();
foreach ($carts as $row) {
$this->db->where('user_id', $user_id);
$this->db->update($table, $insertData);
//echo $this->db->last_query(); exit;
}
}else{
$this->db->insert($table, $insertData);
}
$dataValue = array(
'giftId' => $gift,
'AvailableAmount' => $AvailableAmount,
'gift_cart_total' => $gift_cart_total
);
$databool = true;
$datamsg = '';
}
else{
$xml = new SimpleXMLElement($data);
if(count($xml) <= 2 && !empty($xml->ErrorCode)){
$databool = false;
$datamsg = 'The voucher has expired';
}else{
$VoucherNumber = (int)($xml->VoucherNumber);
$gift_pin = $pin;
$ExpiryDate = (int)($xml->ExpiryDate);
$AvailableAmount = (int)($xml->AvailableAmount);
$AvailableAmount = number_format($AvailableAmount, 2);
$user_id = $this->session->userdata('session_id');
$table = 'gift_voucher';
$sql = "SELECT * FROM $table WHERE user_id = '{$user_id}'";
$query = $this->db->query($sql);
$insertData = array(
'user_id' => $user_id,
'gift_id' => $VoucherNumber,
'pin' => $gift_pin,
'amount' => $AvailableAmount
);
if($query->num_rows() != 0){
$carts = $query->result_array();
foreach ($carts as $row) {
$this->db->delete($table, array('user_id' => $user_id));
$this->db->insert($table, $insertData);
}
}else{
$this->db->insert($table, $insertData);
}
$giftId = $this->db->insert_id();
$dataValue = array(
'giftId' => $giftId,
'VoucherNumber' => (!empty($ss_id))? $ss_id:$VoucherNumber,
'AvailableAmount' => $AvailableAmount
);
$databool = true;
$datamsg = '';
}
}
curl_close($ch);
$returndata['databool'] = $databool;
$returndata['datamsg'] = $datamsg;
$returndata['dataValue'] = $dataValue;
return $returndata;
}
ise .html() to replace whole html of the div or use append() to append to the div
success: function(data){
$("id or class of the div where you want to display the message").html(data);
return false;
},
since you have only one response, change this
echo json_encode($result);
to
echo $result['datamsg'];
or
use a variable and echo here instead of array
My problem now when I click on the picture on my page, for the first time it will display. But for the second time it will display fail. This process will start by sending the data to ajax, then ajax(prosess.js) will send it to the php page(process1.php).
When I remove the code in blockquote ($query = "SELECT ...") it will run, but if not, it will display fail.
process1.php
<?php
include 'session.php';
include 'connection.php';
if(isset($_POST['dataS'])) {
$table = $_POST['table'];
$concat = "";
$serial = $_POST['dataS'];
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row) {
$prodName = $row['prodName'];
$quanProd = 1;
$priceProd = $_POST['total'] + $row['salePrice'];
if($table == "") {
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
$priceProd = number_format((float)$priceProd, 2, '.', '');
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "1",
"concat" => $concat,
"quantity" => $quanProd,
"price" => $priceProd,
)
);
}
else {
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "0",
)
);
}
}
?>
process.js
$(document).ready(
function() {
$("body").on("click","#product .add",
function(e) {
var total = document.getElementById("total").value;
var table = document.getElementById('table-list').innerHTML;
table = (table.trim) ? table.trim() : table.replace(/^\s+/,'');
var serial = $(this).attr('id');
var totalQ = document.getElementById("totalQ").value;
if(total == "")
total = 0;
else
total = parseFloat(total);
if(totalQ == "")
totalQ = 0;
else
totalQ = parseInt(totalQ);
var dataS = serial;
e.preventDefault();
$.ajax({
type : "POST",
url : "process1.php",
crossDomain: true,
data : {dataS : dataS, table : table, total : total},
dataType : 'json',
})
.done(function(html) {
if(html.success == 1) {
console.log('done: %o', html);
$("#table-list").html(html.concat).show();
document.getElementById('totalQuantity').innerHTML = html.quantity;
document.getElementById("total").value = html.price;
document.getElementById("payment").value = html.price;
document.getElementById('totalQ').value = html.quantity;
document.getElementById('title').innerHTML = html.price;
document.getElementById('input').value='';
$("#input").focus();
}
else {
alert("Wrong serial number!");
document.getElementById('input').value='';
$("#input").focus();
}
})
.fail(function(html) {
console.info('fail: %o', html);
alert("fail");
});
return false;
});
});
connection.php
<?php
$conn = mysqli_connect('localhost','root','','rds');
?>
your query is wrong:try this
$query = "SELECT prodName FROM product WHERE prodName = '".$item."'";
According to your pictures, your problem is that your database connection isn't correct. When you execute the first request it won't do any database interaction (because off the blocknotes). The second request you will send table data, which will perform a query. So the first request will succeed, while the second request will give you an error on your mysqli ($conn) object.
if($table == "") {
//Database interaction
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
//No database interaction because of the blocknotes
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
Check your the username, password and database name. I'm pretty sure you used something wrong here. As mentioned in your connection.php file you don't use a password. Are you sure the user root doens't have a password? Can you access the database with a MySQL administration tool like phpMyAdmin?
JS file this deletes by button the Event
buttons: {
save : function() {
calEvent.start = new Date(startField.val());
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.body = bodyField.val();
$calendar.weekCalendar("updateEvent", calEvent);
$dialogContent.dialog("close");
},
"delete" : function() {
calEvent.id = id;
$.post("events.php?action=del&id="+calEvent.id);
$calendar.weekCalendar("removeEvent", calEvent.id);
$dialogContent.dialog("close");
},
cancel : function() {
$dialogContent.dialog("close");
}
}
}).show();
PHP File
if($action == 'save')
{
$title = $_REQUEST['title'];
$body = $_REQUEST['body'];
$start_time = (int)$_REQUEST['start'];
$start_time = $start_time + 60*60;
$end_time = (int)$_REQUEST['end'];
$end_time = $end_time + 60*60;
$start = date('c',$start_time);
$end = date('c',$end_time);
$sql = "INSERT INTO meeting_rooms_calendar(title,body,start,end) VALUES ('$title','$body','$start','$end')";
$result = mysql_query($sql, $link);
}
elseif ($action == 'del')
{
$del = "DELETE FROM `agenda`.`meeting_rooms_calendar` WHERE `meeting_rooms_calendar`.`id` = VALUES ('$id')";
$result = mysql_query($del, $link);
}
else
{
$sql= "SELECT id, title, body,
DATE_FORMAT(start, '%Y-%m-%dT%H:%i' ) AS startTime, DATE_FORMAT(end, '%Y-%m-%dT%H:%i' ) AS endTime
FROM meeting_rooms_calendar
ORDER BY start DESC";
$result = mysql_query($sql, $link);
This wont delete from database, what am I doing wrong to delete it from database?