PHP:unable to echo a variable from DB - php

I'm writing a chat script but I have problem with echo some variables!
I have written this piece of code in chat.php to show the messages:
<?php
session_start();
$id=$_GET['id'];
if(isset($id)){
global $id;
global $qs;
global $answerer;
global $sp;
global $name;
include('config.php');
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$id=$conn->quote(htmlentities($id));
$find=$conn->prepare("SELECT * FROM qs WHERE id=:id");
$find->bindParam(':id',$id);
$find->execute();
if($rows=$find->fetch(PDO::FETCH_ASSOC)){
$qs=$rows['question'];
$answerer=$rows['answerer'];
}
$answerer=explode("(",$answerer);
$ansgiver=$conn->prepare("SELECT * FROM ruhani WHERE name=:answerer");
$ansgiver->bindParam(':answerer',$answerer[0]);
$ansgiver->execute();
if($row=$ansgiver->fetch(PDO::FETCH_ASSOC)){
$name=$row['username'];
$avatar=$row['avatar'];
$sp=$row['sp'];
}
class chat {
public function fetchMessage() {
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$ans=$conn->prepare("SELECT answere FROM ans WHERE q_id=:id ");
$ans->bindParam(':id',$id);
$ans->execute();
}
public function throwMessage($id, $text,$sayer){
include('config.php');
global $id;
$conn=new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$send=$conn->prepare("INSERT INTO ans(q_id,answere,sayer) VALUES(:q_id,:text,:sayer) ");
$send->bindParam(':q_id',$id);
$send->bindParam(':text',$text);
$send->bindParam(':sayer',$sayer);
$send->execute();
}
}
$chat = new chat();
?>
<!DOCTYPE html>
<head>
<title>Example Title</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style/style.css" media="screen, projection" />
<script src="js/jquery-1.6.3.min.js"></script>
<script src="js/chat.js"></script>
</head>
<body>
<div class="all">
<div class="env">
<span><?php echo $name ?>|<?php echo $sp ?></span>
<span>Hi,Can I help you?</span><br>
<span>me:<?php echo $qs ?></span>
<div class="messages"></div>
</div>
<textarea name="ask_ans" class="ask_ans" id="ask_ans" placeholder="Please write here!"></textarea><br>
<input type="submit" class="submit" name="submit" value="send" />
<input type="hidden" id="hidden" value=<? echo $id ?> />
<input type="hidden" id="hidden2" value=<? echo $_SESSION['$username'] ?> />
</div>
</body>
<?php
}
?>
and this code for Ajax part(chat.js):
var chat = { }
chat.fetchMessage=function (){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'fetch'},
cache:false,
success: function(data){
$(".all .env .messages").html(data)
}
});
}
chat.throwMessage=function (id,message,sayer){
if($.trim(message).length != 0 ){
$.ajax({
url:"send.php",
type: 'POST',
data: {method : 'throw' , id : id , message : message , sayer : sayer },
cache:false,
success: function(data){
chat.fetchMessage();
$(".ask_ans").val('');
}
});
}
}
chat.entry=$(".all .submit");
chat.entry.bind('click',function (evt){
evt.preventDefault();
chat.throwMessage($("#hidden").val(),$(".ask_ans").val(),$("#hidden2").val());
});
chat.interval=setInterval(chat.fetchMessage(),5000);
chat.fetchMessage()
And this is send.php:
<?php
require('chat.php');
if (isset($_POST['method']) and !empty($_POST['method'])){
$chat =new chat();
$method =trim($_POST['method']);
if ($method === 'fetch'){
$messages=$chat->fetchMessage();
if (!empty($messages)){
while($r=$messages->fetch(PDO::FETCH_ASSOC)){
$sayer=$r['sayer'];
if($sayer===$starter){
?>
<span class="text" style="float:left"><? echo $r['answere'] ?></span>
<?php
}else{
?>
<span class="text" style="float:right"><? echo $r['answere'] ?></span>
<?php
}
}
}
}else if ($method === 'throw'){
$message=trim(htmlentities($_POST['message']));
$id=trim(htmlentities($_POST['id']));
$sayer=trim(htmlentities($_POST['sayer']));
if(!empty($message) and !empty($id) and !empty($sayer)){
$chat->throwMessage($id,$message,$sayer);
}
}
}
?>
I am getting an error:
Undefined index:id
My problem is that I can't echo $qs,$name,$sp in chat.php.
Can anyone understand the wrong part of my code?

After long time I checked my code,I understand the problem:)
As you see I'm using PDO::quote() and it puts ' ' over the word.So that When I was exploding the variable here:$answerer=explode("(",$answerer);,it couldn't find the correct word to search in DB and didn't echo the variable.
And now I have deleted PDO::quote() and my code is working correct.:-)

Related

Without refresh the page how to display the values from database using ajax/jQuery

After inserting data into the database through jQuery/ajax, while fetching values from database without refresh the page how to display the database values using codeigniter?
This is my code:
Script:
<script>
$(document).ready(function(){
$("#personal-info").submit(function(e){
e.preventDefault();
var suppid = $("#suppid").val();
var proid = $("#proid").val();
var custid = $("#custid").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Profile_cntrl/buyer_communication",
data: {suppid:suppid,proid:proid,custid:custid,message:message},
success:function(data)
{
alert('SUCCESS!!');
},
error:function()
{
alert('fail');
}
});
});
});
</script>
Controller:
public function buyer_communication() {
$result1 = $this->Profile_model->fetch_Data($product_id);
$Userid = $this->session->userdata('id');
$result3 = $this->session->userdata('tt');
$data4 = array(
'message' => $this->input->post('message'),
'supplier_id' => $this->input->post('suppid'),
'product_id' => $this->input->post('proid'),
'Customer_id' => $this->input->post('custid'),
'From' => $result3,
);
$this->Profile_model->buyer_insert($data4);
redirect('welcome/buyermessageview?id=' . $product_id);
}
Model:
function buyer_insert($data4) {
$this->db->insert('communication', $data4);
return ($this->db->affected_rows() != 1) ? false : true;
}
Form:
<form class="form-horizontal" method="POST" id="personal-info" role="form" action="#">
<div class="panel-footer">
<div class="input-group">
<input type ="hidden" name="suppid" id="suppid" value="<?php echo $row->supplier_id; ?>" class="form-control" />
<input type ="hidden" name="proid" id="proid" value="<?php echo $row->product_id; ?>" class="form-control" />
<input type ="hidden" name="custid" id="custid" value="<?php echo $row->Customer_id; ?>" class="form-control" />
<input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>
<!--<input type="submit" name="submit-p" id="submit-p" value="send" class="btn btn-primary btn-sm" >-->
</span>
</div>
</div>
</form>
#Maruthi Prasad here is the code.. [IN CODE IGNITER]
HTML view code with jquery script
views\profile_view.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div id="load_data">
</div>
<form method="post" id="personal-info">
<input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
<button type="submit" class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function(){
loaddata();
data_submit();
});
function loaddata(){
$.getJSON('<?php echo base_url();?>'+'index.php/Profile_cntrl/get_data',function(data){
for(var i in data){
var show = '<div>';
show += '<h5 style="background:#ccc;padding:10px;border-radius:10px;">'+data[i].message+'</h5>';
show += '</div>';
$("#load_data").append(show);
}
});
}
function data_submit(){
$("#personal-info").submit(function(e){
e.preventDefault();
var formdata = $(this).serialize();
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/Profile_cntrl/insert_data',
data:formdata,
success:function(data){
var res = JSON.parse(data);
if(res.Status == 'true'){
//console.log(res.report);
$("#load_data").empty();
loaddata()
}else{
alert(res.report);
}
}
});
});
}
</script>
</body>
</html>
CONTROLLER CODE:
controllers\Profile_cntrl.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
class Profile_cntrl extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('profile_model');
$this->load->helper(array('url','html','form'));
}
public function index()
{
$this->load->view('profile_view');
}
public function get_data(){
$query = $this->profile_model->buyer_communication();
echo json_encode($query);
}
public function insert_data(){
$arr = array(
'message'=>$this->input->post('message')
);
$sql = $this->profile_model->buyer_insert($arr);
$op = "data insert id :".$this->db->insert_id();
if($sql == true){
$reponse = array(
'Status'=>'true',
'report'=>$op
);
echo json_encode($reponse);
}
else
{
$op = "Failed to insert data";
$reponse = array(
'Status'=>'false',
'report'=>$op
);
echo json_encode($reponse);
}
}
}
?>
Model code:
models\Profile_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Profile_model extends CI_model {
public function buyer_communication(){
$sql = $this->db->get('communication');
$sql = $sql->result_array();
return $sql;
}
public function buyer_insert($arr){
return $query = $this->db->insert('communication',$arr);
}
}
?>
Feel free to ask questions

How to convert this php normal code to codeigniter mvc

I need help to convert this code to codeigniter MVC
i have 2 file php
index.php for viewer and cari_barang.php for model
i have problem with file controller, I dont know how to get value post with ajax.
this my PHP code index.php
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$("#barang").keyup(function() {
var kode = $('#barang').val();
$.ajax({
type : "POST",
data : "kode="+kode,
url : "cari_barang.php",
dataType: "json",
success: function(data){
$("#namabarang").val(data.namabarang);
$("#hargabeli").val(data.hargabeli);
}
});
});
});
</script>
</head>
<body>
<div class="demo" style="width: 450px;">
<div>
<p>Kode Barang : <input type="text" id="barang" value="0001"></p>
<p>Nama Barang : <input type="text" id="namabarang" size="50" disabled></p>
<p>Harga Beli : <input type="text" id="hargabeli" size="15" align="right" disabled></p>
</div>
</div>
</body>
</html>
this code for cari_barang.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("barang");
$kode = $_POST['kode'];
$sql = mysql_query("select * from tbbarang where kodebarang='$kode'");
$row = mysql_num_rows($sql);
if($row>0){
$r = mysql_fetch_array($sql);
$data['namabarang'] = $r['namabarang'];
$data['hargabeli'] = $r['hargabeli'];
echo json_encode($data);
}else{
$data['namabarang'] = '';
$data['hargabeli'] = '';
echo json_encode($data);
}
?>
thanks before
have a look on codeigniter website http://www.codeigniter.com/userguide3/ hope you will find your solution.
if you convert your above code to codeigniter then its only a view file of codeigniter.
thanks all for answer,my problem solved with this code
Model :
public function get($kode)
{
$this->db->where('kodebarang',$kode);
$query = $this->db->get('tbbarang');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data['namabarang'] = $row->namabarang;
$data['hargabeli'] = $row->hargabeli;
echo json_encode($data);
}
} else {
$data['namabarang'] = '';
$data['hargabeli'] = '';
echo json_encode($data);
}
}
Controller :
public function view()
{
$this->load->model('m_barang');
$kode = $this->input->post('kode');
//#$kode = $_POST['kode'];
$data = $this->m_barang->get($kode);
}
View :
<html>
<head>
<script type='text/javascript' src='<?php echo base_url("jquery-1.11.2.js");?>'></script>
<script type='text/javascript' src='<?php echo base_url("jquery.autocomplete.js");?>'></script>
<!-- <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<link rel="stylesheet" href="main.css" type="text/css" /> -->
<script type="text/javascript">
$(document).ready(function() {
$("#barang").keyup(function() {
var kode = $('#barang').val();
$.ajax({
type : "POST",
data : "kode="+kode,
url : "<?=base_url('barang/view')?>",
dataType: "json",
success: function(data){
$("#namabarang").val(data.namabarang); //$r['namabarang']
$("#hargabeli").val(data.hargabeli); //$r['hargabeli']
}
});
});
});
</script>
</head>
<body>
<div class="demo" style="width: 450px;">
<div>
<p>Kode Barang : <input type="text" id="barang" value=""></p>
<p>Nama Barang : <input type="text" id="namabarang" size="50" disabled></p>
<p>Harga Beli : <input type="text" id="hargabeli" size="15" align="right" disabled></p>
</div>
</div>
<p class="footer" ><?php echo base_url();?></p>
<p class="footer" ><?php echo site_url();?></p>
<p class="footer" ><?php echo base_url('barang/view');?></p>
</body>
</html>

how to push notification on all user in database with php

this is my file php use jquery to send text from view to send_message.php based only for one id. i want change this code become send text from view to send_message.php to all id registered. you can see this code
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"]; ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php } ?>
<?php
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
this code send input from "txt_message" to user based id and "gcm_regid" so one txt_message for one id, but i try to send same txt_message for multiple id. help me, thank yuo

php code send notification to all devices GCM

I need a little help to send notification to all devices at once.
I know array need to be used for that but can't get the idea. A little hint will also work
DB table design
id gcm_regid name email created_at
Currently i have to fill out the form for all the devices and send notification one by one.
PHP code:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
EDIT: Or can anyone tell me how do i use checkbox for select all "id"s?

php, connecting to database using mysql_connect() problem, how to?

i am using some php and ajax to make a call to a database and i get this error: Warning: mysql_query() [function.mysql-query]: A link to the server could not be established... and Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
now from what i read looks like i need to create a database connection first, and the problem is that i am.
I am using require_once ('db_connect.php'); at the begining:
<?php
define("HOST", "localhost");
define("DBUSER", "123");
define("PASS", "123");
define("DB", "123");
$prefix = "";
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die('Could not connect !<br />Please contact the site\'s administrator.');
$db = mysql_select_db(DB) or die('Could not connect to database !<br />Please contact the site\'s administrator.');
?>
My script looks something like this (ignore any missing or broken html):
<?php
session_start();
require_once ('db_connect.php'); // include the database connection
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<html>
<head>
</head>
<body>
<div id="wrap">
<script type="text/javascript">
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var com_type = 1;
var email = $("#email").val();
var comment = $("#comment").val();
var post_id = $("#post_id").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&post_id=' + post_id;
if(name=='' || email=='' || comment=='')
{
alert('Please Give Valide Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('email').value='';
document.getElementById('name').value='';
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<div id="main">
<ol id="update" class="timeline">
<?php
$sql=mysql_query("select * from comments where post_id_fk='$post_id'");
while($row=mysql_fetch_array($sql))
{
$name=$row['com_name'];
$com_type=$row['com_type'];
$email=$row['com_email'];
$comment_dis=$row['com_dis'];
$lowercase = strtolower($email);
$image = md5( $lowercase );
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=<?php echo $image; ?>" class="com_img">
<span class="com_name"> <?php echo $name; ?><?php echo $com_type; ?></span> <br />My Comment</li>
<?php
}
?>
</ol>
<div id="flash" align="left" ></div>
<div style="margin-left:100px">
<form action="#" method="post">
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>"/>
<input type="text" name="title" id="name"/><span class="titles">Name</span><span class="star">*</span><br />
<input type="text" name="email" id="email"/><span class="titles">Email</span><span class="star">*</span><br />
<textarea name="comment" id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
</div>
</div>
</body>
</html>
the connectajax.php :
<?php
if($_POST)
{
$name=$_POST['name'];
$name=mysql_real_escape_string($name);
$com_type=$_POST['com_type'];
$name=mysql_real_escape_string($com_type);
$email=$_POST['email'];
$email=mysql_real_escape_string($email);
$comment=$_POST['comment'];
$comment=mysql_real_escape_string($comment);
$post_id=$_POST['post_id'];
$post_id=mysql_real_escape_string($post_id);
$lowercase = strtolower($email);
$image = md5( $lowercase );
mysql_query("insert into comment(com_name,com_type,come_email,com_dis) values ('$name','$com_type','$email','$comment_dis','$post_id')");
}
?>
<li class="box">
<img src="http://www.gravatar.com/avatar.php?gravatar_id=
<?php echo $image; ?>"/>
<?php echo $name;?><br />
<?php echo $comment; ?>
</li>
any idea?
thanks
You didn't require_once the db_connect.php script in your connectajax.php script (unless you omitted that line when copying the code in).
Sounds to me as though your mysql service is down. Try reloading it. If that doesn't work, maybe try connecting to a mysql database on another server, to see if maybe it's not the mysql service's fault.
Check if you have given proper access rights to Mysql database...
that will resolve this issue

Categories