Ajax, PHP, MySQL returning sql table - php

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_*.

Related

Ajax request dataType json

I'm having troubles displaying a value in an input field. I did this in the past, and I haven't got a clue where my code goes wrong.
I have an input field with id="input" and a button with id="button". This is my jquery code:
$("#button").click(function() {
var uid = <?php echo $user['uid']; ?>;
$.ajax({
url: "php/fetchUserData.php",
method: "POST",
data: {
uid: uid
},
dataType: "json",
success: function(text) {
$("#input).val(text.bedrijfsnaam);
}
});
});
And here is the code on of the php/fetchUserData.php file:
<?php
include_once 'dbc.php';
if($_POST){
$uid = $_POST['uid'];
$sql = "SELECT * FROM users WHERE uid = '$uid'";
$query = mysqli_query($dbc, $sql);
$result = mysqli_fetch_assoc($query);
echo json_encode($result);
}
?>
UPDATE:
var_dump($result) does displays the associative array.
console.log(text) gives no result.
if I change dataType to text and echo out $result['bedrijfsnaam'] instead of json_encode($result) all goed well. The problem is that I want to load more than just the bedrijfsnaam (= company name).
UPDATE 2:
If I use the very same code but with another table in the database it does works. I really don't have a clue what can be the problem here...
I've been searching what could be the matter with the users table, and I notice cardinality is 0, although there are 4 rows in the table. In the other tables of the database, the cardinality value represents the number of rows. Could that have anything to do with this problem?
UPDATE 3:
Instead of the query:
$sql = "SELECT * FROM users WHERE uid = '$uid'";
I tried:
$sql = "SELECT bedrijfsnaam FROM users WHERE uid = '$uid'";
And it worked! Then I started adding column names, and all went well until a certain column: land (meaning country) a varchar column just like many others in the table.
What could be the reason this particular column causes the error to happen?
I know this became a phpmyadmin question instead of a php or jquery question. Should the question be moved to the sql part of the forum?
Assuming this is your actual code, your issue is likely stemming from not actually referencing and updating a field.
Something like this should be what you need:
$("#input").val(text.bedrijfsnaam)
I don't know anything about PHP and I don't think it matters. I think you got most part right. In success of your ajax request, set the text value of the input field.
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$("id='button'").text(text.bedrijfsnaam);
}
});
$.ajax({
url:"php/fetchUserData.php",
method: "POST",
data:{uid:uid},
dataType:"json",
success:function(text){
$('#input').val(text[0]);
}
});
hmtl maybe better works than .val
You're wrong with your jquery selection of your div: you're missing an " in your code.
hope it will work

how can i use _GET and _POST?

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.)

Ajax post to php to update mysql

I've built an admin page for my site, that contains numerous forms that save, update, delete data into different tables in my database.
Currently i have one PHP file for each function that does the mysql query according to my ajax post command. which is getting a bit out of control.
for example i have a file for saving a new category
$cataddname = $_POST['name'];
$area = $_POST['area'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "INSERT INTO clet_faq_category (id, name, nickname, area) VALUES ('', '$cataddname', '$shortname', '$area')";
mysqli_query($db_connect, $update_category);
my save new category command posts to this file:
then i have a file that saves a category edit:
$cataddname = $_POST['name'];
$area = $_POST['area'];
$id = $_POST['cid'];
$shortname = preg_replace('/\s+/', '_', $cataddname);
$update_category = "UPDATE clet_faq_category SET name='$cataddname', nickname='$shortname', area='$area' WHERE id = '$id'";
mysqli_query($db_connect, $update_category);
And another one to delete a category:
$c_id = $_POST['delete_id'];
$sql_del = "DELETE FROM clet_faq_category WHERE id = '$c_id'";
$del_question = mysqli_query( $db_connect, $sql_del );
then i have an jQuery ajax call that calls the page:
function newcat(){
var id = "answer";
tinymce.execCommand('mceRemoveEditor', true, id);
var category = document.getElementById('newcategory').value;
var area = document.getElementById('area').value;
var dataString = 'name=' + category + '&area=' + area;
$.ajax({
type: "post",
url: "newcat.php?area_id=" + areaid,
data : {
'name': category,
'area': area,
'query' : query
},
cache: false,
success: function(html){
$('#category_table').html(html);
$('#cat-form').text("Category Saved");
}
});
return false;
}
And When you look at them it's pretty much the same thing it's just a mysql query running.
What i'm trying to do is streamline this a little bit, i thought about passing the entire query via ajax to my php file, but that's not an option as anyone that can see my js file will be able to figure out all my queries and table names, and all they need to do is post a query to my php page and damage my entire DB.
so my question is, is there a way to do this in a smarter way maybe creating php functions inside the same file, that has category_delete(), category_add(), category_edit() on the same file and using ajax target each one of those categories, at least all my functions and queries will be on the same spot not in multiple separate files if you know what i mean.
You can do like this create a separate class which perform options for insert delete and update. and on your ajax page call these function like this
$func = new CUD();
switch($_POST['action'])
{
case 'delete':
$func->delete($values..)
case 'update':
$func->update($values..)
case 'delete':
$func->insert($values..)
}
You can have to send extra parameter in ajax as action, this parameter specifies the action
in php
switch($_POST['action'])
{
case 'delete':
.....
}

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.

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.

Categories