Ajax mysql duplicate entry - mysql

before i post this i already looked up for my problem. so here it is
I'm using ajax to get a value using post. but it appears that when i insert it to my database it produces duplicate entry. here's my ajax code
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'Test App',
},
function (receiverUserIds) {
$.each(receiverUserIds.to, function (i, v) {
// console.log(receiverUserIds.request + " " + v);
$.ajax({
url: '<?php echo $config["base_url"]; ?>/main/saverequestinfo/?signed_request=<?php echo $_REQUEST["signed_request"]; ?>',
data: {
request_id: receiverUserIds.request,
receiver_id: v
},
type: 'POST',
success: function (d) {
console.log(receiverUserIds.request + " " + v);
}
});
});
}
//http://developers.facebook.com/docs/reference/dialogs/requests/
);
this is the code called by ajax
function saverequestinfo() {
$data = array(
'inv_user_id' => 1,
'inv_request_id' => $_POST['request_id'],
'inv_user_fbid' => $this->fb->getUser(),
'inv_receiver_fbid' => $_POST['receiver_id'],
'inv_liked' => fb_isLiked($this->fb)
);
$this->main->insertrequest('invitedfriends', $data);
}
and this is my model:
function insertrequest($tbl_name, $data) {
$date = date('Y-m-d H:i:s');
$qry = "INSERT INTO `".$tbl_name."` (";
$c = count($data);
$cc = 0;
$f = "";
$fv = "";
foreach($data as $i=>$v) {
$f .= $i;
$fv .= "'".$v."'";
if($cc<$c-1) {
$f .= ",";
$fv .= ",";
}
$cc++;
}
$qry .= $f.") VALUES(".$fv.")";
if ($this->conn->query($qry) !== TRUE) {
echo $this->conn->error;
die();
}
$this->conn->query($qry);
}

Related

Morris.js setData doesn't work, unless I do this

I'm graphing data based on database results and getting the data via ajax. The graph is supposed to redraw based on the query using jquery setData. I've asked other programmers at work and still can't figure it out.
php code
if(isset($_POST['data'])){
$data = $_POST['data'];
$data = json_decode($data);
$query = "SELECT * FROM bad_errors WHERE rel = '$data' LIMIT 20";
$result = $db->query($query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$chart_data .= "{ month:'".$month."', website:".$row["rel"].", code:".$row["code"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
$data = json_encode($chart_data);
echo $data;
}
jquery code
let barChart = Morris.Bar({
element : 'chart',
data:[],
xkey:'month',
ykeys:['website', 'code'],
labels:['website', 'code'],
hideHover:'auto',
stacked:true
});
let json = JSON.stringify(rel);
$.ajax({
url: "ajax-php/morris-data.php",
type: "POST",
data: {data: json},
dataType:"json",
success: function (data) {
//data variable only redraws the graph if data looks like this -
data = [
{ month:'Mar', website:38, code:547}, {
month:'Mar', website:38, code:584}, { month:'Mar', website:38,
code:500}, { month:'Mar', website:38, code:564}, { month:'Mar',
website:38, code:500},
]
barChart.setData(data); // but not here via ajax success
},
});
I was processing the data wrong in php
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$data[] = array(
'month' => $month,
'website' => $row['rel'],
'code' => $row['code']
);
}
$data = json_encode($data);
echo $data;

Json return value show from Angular Js

Angular Js Script
this.http.post(url, body, options)
.subscribe((data) =>
{
if(data.status === 200)
{
this.hideForm = true;
this.sendNotification(console.log(data.meesage));
}
});
PHP Code
How to get json_encode success message through this.sendNotification()
$sql = "INSERT INTO eastcost_school_room(school_room_name, created) VALUES(:name, Now())";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record ' . $name . ' was added to the database'));
}
map the response before subscribing
this.http.post(url, body, options)
.map((res:Response) => res.json());
.subscribe((data) =>
{
if(data.status === 200)
{
this.hideForm = true;
this.sendNotification(console.log(data.meesage));
}
});
Php code
$sql = "INSERT INTO eastcost_school_room(school_room_name, created) VALUES(:name, Now())";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$response["success"] = 1;
$response["message"] = 'Congratulations the record ' . $name . ' was added to the database';
// echoing JSON response
echo json_encode($response);
Post method in the api service class
Service
insert(parameters): Observable<any> {
return this.http.post('url', body, {
headers: headers
})
.map((res: any) => res.json())
}
And subscribe the response from your class
this.service.insert(parameters)
.subscribe(
response => {
console.log(response);
if (response.success == "1") {
console.log("Successfull login");
}
else {
alert(" Invalid user");
}
},
error => {
alert(error);
}
);

Auto display results using json

Currently i'm using json to auto display my reuslt, but i got error say json_encode(): type is unsupported, encoded as null, and i think my problem is view, when i choose in name in dropdown i gives an error json_encode(): type is unsupported, encoded
Model
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
echo $row['address'];
}
}
return $result;
}
Controller
function address() {
$name=$this->input->post('name');
$this->load->model('default/M_profile');
$data['address'] = $this->M_vendor->get_address($name);
$this->output->set_output(json_encode($data));
//echo $data;
return;
}
in view i use dropdown.
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url();?>admin/profile/address",
method: "POST",
data: {profile: add},
success: function(add) {
$('#address').val(add);
}
})
});
});
<select name="test">....</select>
You have a lots of errors:
1.In ajax it should be type:'POST'.Not method:'POST'.
2.In controller it should be $this->input->post('profile')
3.In model just return your data using result_array().
MODEL:
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
return $result->result_array();
}
}
}
Controller:
function address() {
$name=$this->input->post('profile');
$this->load->model('default/M_profile');
$data = $this->M_vendor->get_address($name);
echo json_encode($data);
}
View:(Ajax):
<script type="text/javascript">
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url('admin/profile/address');?>",
type: "POST",
data: {profile: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
alert(data[0].address);
}
})
});
});
</script>
<select name="test">....</select>
I hope it helps you a lot.
you are echoing the result instead of returning
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
$result[] = $row['address'];
}
}
return $result;
}

Data form models is not shown in controller even if exist (Yii 2.0.6)

I have this peace of code in my controller where I want to echo on the screen the JSON result for the data in the model:
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => $dataProvider->models
]);
}
So $dataProvider actually is not empty and it contains the data (which can be seen from var_dump() command), but the data are not returned as I'm expecting.
Even $dataProvider->getCount() is returning that there are two entries. This is the output that I got: http://prntscr.com/8hcel9.
I'm interested in showing the dataProvider part, where the items in array should not be empty.
You need to convert the object to array
try this way :
use yii\helpers\ArrayHelper;
......
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => ArrayHelper::toArray($dataProvider->models), // object to Array
]);
}
This has not much to do with Yii. It's just a PHP problem. You can solve it like this (according to this):
echo "<pre>";
echo json_encode([
"searchModel" => json_readable_encode($searchModel),
"getCount" => $dataProvider->getCount(),
"dataProvider" => json_readable_encode($dataProvider->models)
]);
echo "</pre>";
function json_readable_encode($in, $indent = 0, $from_array = false) {
$_myself = __FUNCTION__;
$_escape = function ($str) {
return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
};
$out = '';
foreach ($in as $key => $value) {
$out .= str_repeat("\t", $indent + 1);
$out .= "\"" . $_escape((string)$key) . "\": ";
if (is_object($value) || is_array($value)) {
$out .= "\n";
$out .= $_myself($value, $indent + 1);
} elseif (is_bool($value)) {
$out .= $value ? 'true' : 'false';
} elseif (is_null($value)) {
$out .= 'null';
} elseif (is_string($value)) {
$out .= "\"" . $_escape($value) . "\"";
} else {
$out .= $value;
}
$out .= ",\n";
}
if (!empty($out)) {
$out = substr($out, 0, -2);
}
$out = str_repeat("\t", $indent) . "{\n" . $out;
$out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;
}

Convert MySQL to pdo statement with json

I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>