how can i use _GET and _POST? - php

i tried to make my all of code as _GET in php at first. However, i want to include firstname in php. therefore, i just tried to make first name as _GET but it causes Null value. i created firstname as varchar in database. if i click button, i want to update firstname in database. how can i do this step?
it is part of my php
if($row['seatStatus'] == 1)
{
display("<td style='color:blue;'>Available</td></tr><tr>
<td>First Name: <input type='text' name='fname' id='fname'>
</td></tr></table>","\n" );
display("<div><input type='button' value='Booking seat'
onclick='update()'></div>","\n");
i give function update() in onclick. and i made function update() in html
function update() {
var sel = $("#pix option:selected").val();//check the value of sel
var url = "p1.php";//check the path of p.php
$.get(url,{'pix':sel},function(dataFromtheServer) {
$("#result1").html(dataFromtheServer);
});
}
and last one is about query and $_GET in PHP
$fields = $_GET['pix'];
$name = $_GET['fname'];
$sql1 = "UPDATE seat SET seatStatus=0, firstName = '".$name."'
WHERE seat_id = $fields";

In your update function you not get the value of first name then only it showing as null value.
Just get the value of first name:
function update()
{
var sel = $("#pix option:selected").val();
var fistName =$("#fname").val();
var url = "p1.php";
$.get(url,{'pix':sel,'fname':fistName},function(dataFromtheServer)
{
$("#result1").html(dataFromtheServer);
});
}

I think so: you should update this code use [http://api.jquery.com/jQuery.ajax/]:
function update() {
var sel = $("#pix option:selected").val();
var fname = $('#fname').val();
var url = "p1.php";
$.ajax({
url : url,
type : get,
data: { pix:sel, fname: fname },
success : function( response ) {
$("#result1").html(response);
}
});
}
This code is bad :
$sql1 = "UPDATE seat SET seatStatus=0, firstName = '".$name."'
WHERE seat_id = $fields";
Security Warning: This answer is not in line with security best practices. Escaping is inadequate to prevent SQL injection, use prepared statements instead. Use the strategy outlined below at your own risk. (Also, mysql_real_escape_string() was removed in PHP 7.)

Related

Insert Data mysql using Ajax and PHP

I am want insert data to MySQL Database using Ajax and PHP
My Ajax Code
$(function(){
$('#submit').click(function(){
var Name = $('#InputName').val();
var Email = $('#InputEmail').val();
var Phone = $('#InputPhone').val();
var Username = $('#InputUser').val();
var Status = $('#selectStatus').val();
//Ajax for add Dealer
$.ajax({
url : "../page/addnewDealer.php",
type : "POST",
async : false,
data :{
Submit:'adduser',
Name : Name,
Email:Email,
Phone:Phone,
UserName:Username,
Status:Status
},
success :function(result){
alert(result);
}
});
});
});
and PHP code is
if(isset($_POST['Submit'])=='adduser')
{
$pass= get_rand_id();
$time= get_currunt_Time();
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
$result = mysql_query($insertData);
}
It is a registration page when i am add a user using this program . program replies success massage but in database nothing happen
change
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('$_POST[Username]','$pass','$_POST[Status]','$_POST[Name]','$_POST[Phone]','$_POST[Email]','$time','$time')";
to
$insertData = "INSERT INTO tbl_dealer (dlrUsrnme,dlrPaswrd,isactive,contName,contPhone,contEmaill,lastUpdtTime,creationTime) VALUES('".$_POST[Username]."','".$pass."','".$_POST[Status]."','".$_POST[Name]."','".$_POST[Phone]."','".$_POST[Email]."','".$time."','".$time."')";
Add braces { } around your $_POST variables in the query. Also, check your spelling of your field names - is "contEmaill" correct? (Two 'l's).
You can simply take post data to a variable and append it to the sql query.

Parse JSON object created by a PDO statement

Here is my problem
I looked through Stak overflow and other websites but can't find an answer that solves my actual problem...
I call a php file from an AJAX request, my php file gets data from my db.
I'm making a pdo statement to get data from my db :
//initialize vars such as $db ...
$get = $db->prepare("SELECT * FROM myTable WHERE myTable_id=1");
$get->execute();
echo json_encode($get->fetchAll(PDO::FETCH_ASSOC));
//COLUMNS IN MY TABLE ARE ID, NAME, PHONE, INFO
so that object is returned to my ajax query
BUT I don't know how to fetch this object into my ajax/jquery statement to use its data...
Response from console :
[Object{id="1",name="myname",phone="8888888",info="information"}]
code...
success : function(response){
var id = '';
var name = '';
var phone = '';
var info = '';
}
please tell me how to parse, i tried json.parse(response), but can't display any data from this...
thanx
Do it like this
success : function(response){
var data = JSON.parse(response);
var id = data.id;
var name = data.name;
var phone = data.phone;
var info = data.info;
}
That should do the trick.

Insert data into mysql using ajax

I'm trying to insert data to mysql, tried everything but nothing worked
here is my code :
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#rating-btn").click( function(){
var teaching=$("#teaching").val;
var marking=$("#marks").val;
var helpfulness=$("#helpfulness").val;
var difficulty=$("#difficulty").val;
var grade=$("#grade").val;
var com=$("#com").val;
$.ajax({
type: "POST",
url:"db/ajax.php",
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&com="+com,
dataType: "dataString",
cache: "true",
success: function(msg,string,jqXHR){
$("#results").html(msg+string+jqXHR);
}
});
});
});
ajax.php
<?php
error_reporting(0);
require 'db/connect.php';
$teaching = $_POST['teaching'];
$teaching = mysql_real_escape_string($teaching);
$marking = $_POST['marking'];
$marking = mysql_real_escape_string($marking);
$helpfulness = $_POST['helpfulness'];
$helpfulness = mysql_real_escape_string($helpfulness);
$difficulty = $_POST['difficulty'];
$difficulty = mysql_real_escape_string($difficulty);
$grade = $_POST['grade'];
$grade = mysql_real_escape_string($grade);
$com= $_POST['com'];
$sql = "INSERT INTO ratings VALUES ( '', '{$teaching}', '{$marking}' ,'{$helpfulness}', '{$difficulty}' ,'{$grade}' , '2' , '{$com}')";
mysqli_query($sql);
?>
connect.php
<?php
$db= new mysqli('localhost','root','','instructors');
if($db->connect_errno){
die("we are having some problems");
}
?>
I tried to the sql code and it worked in the phpmyadmin page.
So what is missing that is preventing the data from going into the database?
UPDATE:
when i try to echo all the variables and thier values apears normally
i also tried to do this :
$sql = "INSERT INTO `ratings` VALUES ( '', '3.5', '2.5' ,'4.5', '2.5' ,'1' , '2' , 'hello how are you')";
it does not insert this values to the database
but when i put the same sql code in the phpmyadmin its adds a row perfectly
It seems, your Js-code has some missing paranthesis. >ou should replace "val" with the function call "val()"
var teaching=$("#teaching").val();
var marking=$("#marks").val();
var helpfulness=$("#helpfulness").val();
var difficulty=$("#difficulty").val();
var grade=$("#grade").val();
var com=$("#com").val();
Afterwards, you should get some values in PHP-land, which can be inserted.
Additionally, you are mixing procedural and OOP-code.
mysqli_query($sql);
... is at least missing the connection as first parameter. But since you saved an instance of mysqli_connection already in $db try replacing it with:
$db->query($sql);
What everyone said about mysql and mysqli. Plus you have to add the & between the vars.
data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
+"&difficulty="+difficulty+"&grade="+grade+"&comment="+comment,
fixed my problem by just using the object $db that i already created in connect.php in the ajax.php
instead of writing
query(&sql)
the solution is :
$db->query($sql);
thanks for everyone for the help.

Ajax, PHP, MySQL returning sql table

I have the following Ajax code to send information from an HTML form to a PHP file.
$(document).ready(function(){
$('#txt').load( '../../do_comment.php' );
});
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#user_name").val();
var comment = $("#user_comment").val();
var ID = '2'; //must change for each post
$.ajax({
type: "POST",
url: "../../do_comment.php",
data: {user_name:name, user_comment:comment, ID:ID},
success: function(){
$('#txt').load( '../../do_comment.php' );
},
error:function(e){alert("it failed");}
});
});
});
In my PHP file I declare the variables like this:
$name = $_POST[user_name];
$comment = $_POST[user_comment];
$ID = $_POST[ID];
And correctly populate my database with this:
if($_POST[user_comment] != Null) {
$sql = "INSERT INTO $table_name (post_ID, user_name, comments)
VALUES ('$ID','$name', '$comment')";
$result = #mysql_query($sql,$connection) or die(mysql_error());
}
The problem is none of the variables will echo any sort of value, and when I try to query the database it only works if I hard code the ID value in instead of using the variable.
$data = mysql_query("SELECT * FROM $table_name WHERE post_ID =
'".mysql_real_escape_string($ID)."'") or
die(mysql_error());
Use the following when gathering from $_GET/$_POST/$_REQUEST:
$name = $_POST['user_name'];
$comment = $_POST['user_comment'];
$ID = $_POST['ID'];
Notice the tics. Proper syntax is $_POST[''].
Have you checked the database to make sure the proper values are being inserted?
Also, if the post_id is an integer, don't use tics
SELECT * FROM table WHERE post_ID = 1234
NOTICE: do not use MySQL_*, it has been deprecated in PHP 5.5. Use MySQLi or PDO. Watch out for SQL injections as well, especially when using MySQL_*.

Saving to database via AJAX/jQuery, sending two variables

I have this problem that I have multiple fields that updates a database via an AJAX-call. The AJAX call looks like this:
$(".fresheditable").fresheditor("save", function (id, parsedHtml) {
$.ajax({
url: 'save.php',
type: 'POST',
data: {
id: id,
parsedHtml: parsedHtml
}
});
});
The ID value changes depending on what element is being edited. The problem is when the update gets sent to the save.php document. How do I only run the update with the specific ID?
See my save.php:
if($_POST['id']='link')
{
$link = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET linkname=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($link,$_SESSION['button'])))
{
echo 1;
}
}
//The next if-statement could look like this:
if($_POST['id']='contactperson')
{
$contactperson = $_POST['parsedHtml']; //get posted data
// query
$sql = "UPDATE buttons SET contactperson=? WHERE id=?";
$q = $conn->prepare($sql);
if ($q->execute(array($contactperson,$_SESSION['button'])))
{
echo 1;
}
}
If more than one ID is sent to the save.php say link and contactperson both if-statements are true and the update sets the same values because the parsedHtml variable.
Is there anything I can do in save.php that can prevent this? Somehow I need to associate the correct parsedHtml with the corresponding id.
The comparison operator in PHP (as well as in Javascript) is == and not =
if($_POST["id"]=="link")
Is it because you're using single equals in your IF tests, which assigns and returns true as a value exists? Not double-equals for comparison?
E.g.
if($_POST['id']=='link')
not
if($_POST['id']='link')
One thing you can use is data attribute i mean
<span item-data="some_id">data</span> now you can select in jquery, the specific item-data from your html to update.
Use else-if structure.
if($_POST['id']='link') {
}
else if($_POST['id']='contactperson') {
}

Categories