my post doesn't insert in my database - php

I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..

In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);

I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html

If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}

Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);

Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.

Related

AJAX not working, success function is working?

the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.

ajax call not working properly in php

in the below code I am passing ipdno as a param, and then I am getting the response from server for that this is my code.
php
$('#print').click(function(){
var ipdNo = $('#hid_ipd_id').val();
var param = "ipdNo="+ipdNo;
alert("Param: "+param);
$.ajax({
url: "ipd_bill_print.php", //The url where the server req would we made.
async: true,
type: "POST", //The type which you want to use: GET/POST
data: param, //The variables which are going.
dataType: "html",
success: function(data){
//alert("Result: "+data+"\nRefreshing page... ");
if(data=='success'){
alert("Record updated succcessfully!");
location.reload(true);
}else{
alert("Record could not be updated!");
}
}
});
});
In this code I want to indicate the success when there are some rows, otherwise it should indicate the failure.
ipd_bill_print.php
<?php
require_once("db/include.php");
$ipd_no = $_POST['ipd_no'];
$token = "Empty";
try{
$dbh = getConnection();
$flag = true;
$sql = "SELECT ipd_reg_no
FROM ipd_bill
WHERE ipd_reg_no = ?";
$sth = $dbh->prepare($sql);
$sth->bindParam(1,$ipd_no);
$row = $sth->fetch(PDO::FETCH_ASSOC);
echo $row;
if($row >==0)
$flag = false;
if($flag)
echo "success";
else{
$dbh->rollback();
echo "fail";
}
//echo "\n FLAG: $flag \n";
$dbh->commit();
}catch(PDOException $e){
print($e);
try{
$dbh->rollback();
}catch(PDOException $e){
die($e->getMessage());
}
}
else{ //if ends here..
echo "Outside if...";
}
In JavaScript code you have provided the ipdNo as the AJAX parameter, but in the PHP file you try to access an undefined key named ipd_no through $_POST. I also recommend to change the AJAX dataType from "html" to the "text", because you are just echoing some plain text in the PHP file.
In the PHP file, in order to use the PDO::commit or PDO::rollBack, you need to first invoke PDO::beginTransaction.
Before calling PDOStatement::fetch, you need to execute your statement through PDOStatement::execute.
In the if statement you need to change the syntactically wrong statement of $row >==0 to something like $row!==false && count($row)>0. Finally, consider that you don't have any matching if statement for you last else statement, where you commented //if ends here.., However; It just maybe not visible in you code snippet.
In addition, you are better to always check the returning result from any method call or function invoke.

Check if cell number exists in database

i want to check if the cell number a user is trying to enter already exists.
But the code below always calls this "Cell Number in use",
what im i doing wrong? Still starting with php.
<?php
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
This should work:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = (isset($_POST["cell"])?
$_POST["cell"] : null);
$query=mysql_query("SELECT * from users where cell='$cell' LIMIT 1");
$find=mysql_num_rows($query);
die($find);
}
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
So if you send "data" to the script it'll look for results, output the count, and exit.
If not, it'll display the rest of the page.
Also note how I put a LIMIT 1 there, just a little performance optimization, since you only want to know if the data is there or not.
Edit: This is a better approach in terms of performance and security:
<?php
if(isset($_POST['cell'])) {
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query = mysql_query("SELECT COUNT(*) AS number from users where cell='".mysql_real_escape_string($cell)."' LIMIT 1");
$find = mysql_result($query, 0);
die($find);
}
?>
I see your post url is:
url:"formpost"
if js code and the php in the same file, the return data of ajax will be whole html and javascript instead of just "echo $find;"; of course your data will never be 0;
First thing to do is to see what is the value of data returned. That will give you some idea where the problem is. Also, it is better to use count() than to get all rows just so you can do mysql_num_rows().
SELECT COUNT(*) from users where cell='$cell'
will return the number of rows with cell that equals $cell. Interpret that result and then echo what you need. Also check if query was successful (handle errors). If the $_POST['cell'] is not set there is no reason to query the database for cell number that is null, just return desired value immediately. You also got comments that you are vulnerable to sql injections so you should consider fixing that too.
if you are receiving the result from the same page in your ajax call its as if you have browsed to the page so the returned content will include everything on the page including your javascript. Try either using a different page as the ajax target or doing somthing like this:
<?php
if(isset($_POST["cell"]))
{
mysql_connect("localhost", "root", "password", "users");
mysql_select_db("users");
$cell = $_POST["cell"];
$query=mysql_query("SELECT * from users where cell='$cell' ");
$find=mysql_num_rows($query);
echo $find;
}
else
{
?>
<script>
$(document).ready(function(){
$("#Cell").blur(function(){
$("#Status_Cell").show();
$("#Status_Cell").html("checking...");
var cell = $("#Cell").val();
$.ajax({
type:"post",
url:"formpost",
data:"cell="+cell,
success:function(data){
if(data==0){
$("#Status_Cell").html("Cell Number available");
}
else{
$("#Status_Cell").html("Cell Number in use");
}
}
});
});
});
</script>
<?php } ?>
Which should mean that the javascript is only written out if you dont have a post value.

JQuery AJAX update a textbox on another textbox textchanged

I would like to update my input text type (id="textbox2") when i typed something at another input text type (id="textbox1").
Here's my initial code:
$("#textbox1").keyup(function(){
$.ajax({
type: "POST",
url: "idgetter.php",
data: 'id='+$("#textbox1").val(),
success: function(n) {
$('#textbox2').val(n);
},
error: function(n) {
$('#textbox2').val(n);
}
});
});
And my idgetter.php :
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) return "none";
else{
$r = mysql_fetch_array($q);
return $r["name"];
Long story short, this did not work, any idea why?
In idgetter.php, Instead of returning using return give
echo "none";
and
echo $r["name"];
You should try echo instead of return:
your code would be like this:
include("inc/conn.php");
$q = mysql_query("SELECT name FROM jurnalis WHERE userid = '".$_POST['id']."'")or trigger_error("SQL", E_USER_ERROR);
if(mysql_num_rows($q)<=0) echo "none";
else{
$r = mysql_fetch_array($q);
echo $r["name"];
Think there are a few amends needed in your php:
change return to echo (like stated in the other answers)
change your if statement to
if(mysql_num_rows($q)==0){
echo 'none';
}else{
$r = mysql_fetch_assoc($q);
echo $r['name'];
}
That should do it hopefully. Also as an FYI its worth trying to avoid adding $_POST[''] items to SQL statements directly, as its prone to SQL injection breaches.

AJAX does not recognize json array

Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>
you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.
Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.
I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);

Categories