I have this bit of code here:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = $_POST['name'];
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($con, $sql)
or die("Error: ".mysql_error());
mysqli_close($con);
?>
DB.php is my database settings. I call a query to it on page load and it connects and pulls data fine, so I know it's not an issue there. I also don't get any errors. I get a status code 200 OK on the post.
Here's the ajax post:
var name = $('#name').val();
var amount = $('#amount').val();
var timPaid = $('#timPaid').val();
var rennyPaid = $('#rennyPaid').val();
var data = $('#newSubmissionForm').serialize();
$.ajax({
url: 'insert.php',
data: data,
type: 'post',
success: function()
{
window.location.href = '';
}
});
Does it have something to do with me serializing it?
I hope this is enough info. Thanks!
mysql_query requires first parameter as query and second parameter as connection object (optional)
change this
$result = mysql_query($con, $sql);
to
$result = mysql_query($sql, $con);
Also you used mysql for connection and query but you used mysqli to close the connection.
You have likely just switched the $sql and $con statement. in mysql_query $sql should be the first parameter. It's easy to forget, since mysqli_query should have $con as the first. :/
php die() statement is the same as exit, and will end the script with status 200. Likely you DO get an error in the output. Try viewing it in e.g developer console (Chrome)
check in internet explorer which code is generated
(inspect element)
add to the beginning of your session php file
<?php
echo '<pre>';
var_dump($_POST);
die();
?>
This will show the values that are sent to the database.
Related
I want to update/edit my user form, but when I click the "edit" button, I'm not getting the expected results. It should display the new data, but It displays the old data instead.
coding:
<?php
include"errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$Date= $_REQUEST["Date"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$query = "select * from requestform";
$result2= $conn->query($query) or die ($conn->error ."\n");
$row_result =mysqli_fetch_assoc($result2);
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'",$conn->affected_rows);
$result_update=mysqli_fetch_assoc($result);
header("Location:requestform3.php");
?>
output:
try it:
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID=$wardID ");
in where wardID='???' Must retrieve the data before it changes. i mean "4f" not "med".
you can add a textbok in your post form :
<input type="hidden" id="original_wardID" value="<?php echo $wardID?>" />
in your php code add :
$ori_wardID=$_REQUEST['original_wardID'];
then change your sql :
UPDATE requestform SET wardID='$wardID',RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$ori_wardID'
"UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'"
change to
"UPDATE requestform SET RequestName='".$RequestName."',Department='".$Department."',Position='".$Position."',Date='".$Date."',TypeOfRequest='".$TypeOfRequest."',PleaseSpecify='".$PleaseSpecify."',DateRequire='".$DateRequire."',DateReturn='".$DateReturn."' where wardID=".$wardID
or like this demo code
$db_sql="select id ,uid,regdate from `newtable` where id=?";
$stmt=$mysqli->prepare($db_sql);//
$stmt->bind_param("i",$id);// i int d double s string b blob
$result = $stmt->execute();
but I guess use pdo will be better
You are not using if ($_SERVER['REQUEST_METHOD'] == 'POST'){//save database} or if (isset $_POST['edit']){//save database} for the edit button in order to save data when edit button is clicked.
Plus you are using Date in your UPDATE query (Date =). DATE is also as a native function used in MYSQL, you need to change it. In case you changed it to DateChanged use prepared statement it helps your code to be more readable.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$stmt = $conn->prepare("UPDATE requestform SET RequestName=?,
Department=?, Position=?, DateChanged=?, TypeOfRequest=?,
PleaseSpecify=?, DateRequire=?, DateReturn=? WHERE wardID=?");
$stmt->bind_param("sssssssss", $RequestName, $Department,
$Position, $DateChanged, $TypeOfRequest, $PleaseSpecify,
$DateRequire, $wardID);
$stmt->execute();
$stmt->close();
$conn->close();
}
i had found my answer. after i redo back my coding using the old template
here are the code.
<?php
// to connect with the database system
include "errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$DateRequest = $_REQUEST["DateRequest"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die (mysql_error()."\n");
$query = "select * from requestform" ;
$result = $conn->query($query) or die (mysql_error()."\n".$query);
$row_result=mysqli_fetch_assoc($result);
mysqli_select_db($conn,"misadmin")or die (mysql_error(). "\n");
//to update the data
$update="update requestform SET
RequestName='$RequestName' ,Department='$Department' ,Position='$Position' ,DateRequest='$DateRequest' ,TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify' ,DateRequire='$DateRequire' ,DateReturn='$DateReturn' where wardID='$wardID'";
$rowinsert=$conn->query($update);
header("Location:requestform3.php");
?>
thanks for those who gave the suggestions.I had learnt a lot from you all.
im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.
Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";
You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}
More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}
You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.
i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?
This one has got me stumped. When I try to save something to the database that contains an apostrophe ('), it will save the sence up until then and after that it does not not. For example;
Say I am trying to save this: Report details Tim Cook's changes at Apple, for better or worse ยป
It saves: Report details Tim Cook
It saves to the database fine but only everything before the '
My code:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Any help as to why it might not be saving properly? I have tried mysql_real_escape_string but (if I am using it correctly) that does not seem to work.
Side note: What is the best way to secure the form above from attacks?
Update It is also doing it for " as well.
You need to call mysql_real_escape_string() after connecting to your database:
if(isset($_POST['submit']))
{
global $db, $db_table_prefix;
$origRLTitle = $_POST['RLTitle'];
$origRLURL = $_POST['RLURL'];
$origRLUserID = $_POST['user-id'];
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db("sf") or die(mysql_error());
$RLTitle = mysql_real_escape_string($origRLTitle);
$RLURL = mysql_real_escape_string($origRLURL);
$RLUserID = mysql_real_escape_string($origRLUserID);
if(strlen($RLTitle)>0 && strlen($RLURL)>0 && strlen($RLUserID)>0)
{
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
echo "Saved";
}
}
Change
mysql_query("INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')");
to
$query = "INSERT INTO `ReadLater` (Title, URL, User_ID) VALUES ('".$RLTitle."', '".$RLURL."', '".$RLUserID."')";
echo $query;
mysql_query($query);
And check out the actual query you are sending, easy to spot the problems then :)
I have some jQuery that when you click the save button it triggers a function to grab the HTML matching a selector and post the HTML to save_report.php:
function saveReport() {
$.post('save_report.php', function(data) {
$('.report').html(data);
});
}
$('.save').click(function () {
saveReport();
});
In save_report.php I want to know how i can then save that string to my db.
$report = $_POST['']; # <-- not sure how to post
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports (id, report) VALUES('', $report) ")
or die(mysql_error());
How do I retrieve the POST value in my php file?
Thanks
Couple of things wrong here... The posted code doesn't actually post any data, and the post and html functions are called incorrectly.
So, first I'll grab the html from the .report selector, and store it in a variable. Then I'll post it providing a variable name of 'report'. I added a simple callback that alerts what the web server sends back, which you can remove or change.
function saveReport() {
var data = $('.report').html();
$.post('save_report.php', {'report':data}, function(response) { alert(response); });
}
$('.save').click(function () { saveReport(); });
In your PHP, you would be looking for $_POST['report'] which is how I named the data being posted.
You're not sanitizing any of the input, so basically any random hacker could take over your entire database with SQL injection. At a minimum, after getting $_POST['report'], run it through the mysql_real_escape_string() function.
Most likely you need to change your jQuery code to
function saveReport() {
$.post('save_report.php', {report: $('.report').html(data)} );
}
and php to
$report = $_POST['report']; **<-- not sure how to post**
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports
(id, report) VALUES('', '".mysql_real_escape_string($report)."' ) ")
or die(mysql_error());
Please don't forget to escape the HTML before you put it in your insert query. What you're doing has the potential to go very wrong very fast. I've modified your save_report.php code to fit Fosco's answer. I am now passing the 'optional' $link parameter to all of the mysql_* functions because in general it is a best practice to do so. I've also added some escaping of the value before it is used in your INSERT query; It is important to pass the $link parameter to the mysql_real_escape_string() function so it can properly escape the value.
$report = $_POST['report'];
$link = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database", $link) or die(mysql_error());
$report = mysql_real_escape_string($report, $link);
mysql_query("INSERT INTO reports (id, report) VALUES('', '{$report}')", $link)
or die(mysql_error());