I really wonder that how someone adding records to my existing blog comment table. I am using my own custom blog script where user add comment on any particular blog. I have a separate comment table with blog id. I have tried several CAPTCHA technique but nothing works. I am using PDO for mysql. I am also doing JavaScript validation before submitting the form. I am not sure if he/she is real people or some bots are doing that. Within 1 hour thousands of records being added.
I am posing my code below. Can someone help me please?
<?php
if(isset($_POST['user_comment']))
{
if ($_SESSION['answer'] == $_POST['answer'] )
{
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$web = $website;
$comment = addslashes(nl2br($_POST['comment_text']));
$comment =strip_tags($comment);
$id = $article_id;
$ref = $_SERVER["HTTP_REFERER"];
$userip = $_SERVER['REMOTE_ADDR'];
$useragent = $_SERVER['HTTP_USER_AGENT'];
$submit_date = date('Y-m-d H:i:s');
if ((($name) && ($email) && ($comment))) {
$conn = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$sql = "INSERT INTO blog_comments (user,email,website,message,date,storyid,userip,useragent,block) VALUES (:user,:email,:website,:message,:date,:storyid,:userip,:useragent,:block)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$name, ':email'=>$email, ':website'=>$website, ':message'=>$title, ':date'=>$submit_date, ':storyid'=>$id, ':userip'=>$userip, ':useragent'=>$useragent,':block'=>'1'));
}
}
else
{
?>
<tr><td>
<p style="text-align:center; color:#CC0000; font-size:14px; font-weight:bold; padding-bottom:10px;">Wrong Answer! Please try again!!</p>
</td>
</tr>
<?php
}
}
?>
THIS IS MY CAPTCHA CODE:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
THIS IS JS VALIDATION:
<script type="text/javascript" language="javascript">
function validate()
{
if( document.getElementById( "name" ).value == ""){
alert("Please enter your name.");
document.getElementById( "name" ).focus();
return false;
}
if( document.getElementById( "email" ).value == ""){
alert("Please enter Your email ID.");
document.getElementById( "email" ).focus();
return false;
}
if( document.getElementById( "comment_text" ).value == ""){
alert("Please enter your comment.");
document.getElementById( "comment_text" ).focus();
return false;
}
if( document.getElementById( "answer" ).value == ""){
alert("Please solve this math.");
document.getElementById("answer").focus();
return false;
}
}
</script>
THIS IS MY FORM:
<form action="" method="POST" onSubmit="return validate();">
<table cellpadding="5" cellspacing="5" width="100%">
<tr><td colspan="3">
<input type="hidden" name="id" value="<? print($id);?>">
</td></tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Name</td>
<td style="width:260px;"><input type="text" name="name" id="name" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your E-mail</td>
<td style="width:260px;"><input type="text" name="email" id="email" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Website</td>
<td style="width:260px;"><input type="text" name="website" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Optional</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Comment</td>
<td style="width:260px;"><textarea name="comment_text" id="comment_text" style="width:250px; height:100px;"></textarea></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">What's <?php echo $math; ?> = </td>
<td style="width:260px;"><input type="text" name="answer" id="answer" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td colspan="3" style="text-align:center;">
<input type="submit" class="submit" value="Submit" name="user_comment">
</td></tr>
</table>
</form>
I would suggest you to select from db previous record of a user with posted email and compare the content or the date with posted data. If the content is the same or date range is very small, than show approving message for posting or do something like that.
Your Captcha is not very safe. Any Bot can give you the answere.
What's <?php echo $math; ?> =
This will only shown as Text What's x + y = answer is z.
Every Bot and every self written Javascript can fill all requireds fields and get the "question" and fill it in the answer field.
And i guess that if you hit F5 in your browser after you post a comment, the php script will also save it in your DB, because the answer in your session is not deleted after one try.
Try to print an image with the question instead of a text and delete the answer in your Session after first try.
This should solve the problem.
After all I have found the solution myself. Now I am showing the last commented date time instead of CAPTCHA and asking user to input that value as it is in input box. All captcha techniques failed whereas this technique works perfectly and i am not getting spam any more.
Thanks you so much to all you experts for giving your valuable suggestions.
Related
I designed a form to submit to a database. but when submitted the form returns blank and reload the form. I will be glad if you guys can help with my project work.
I am a php beginner now. I am trying to work on a school project. Where the html form will query the php form
I uploaded the files then trying the form I keep seeing a returned blank page without the form proceeding to the next page but returns blank
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="50%" valign="top">
<?php if ($curr_user['balance2'] != 0) { ?>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="head"><img src="images/i_qt_text.png" width="220" height="27" /></td>
</tr>
<tr>
<td style="border:#000080 1px solid; padding:5px;"><form id="form1" name="form1" method="post" action="" autocomplete="off">
<table width="100%" border="0" cellspacing="1">
<?php if($error_msg != "") { ?>
<tr>
<td colspan="2" class="error_msg"><?php echo $error_msg; ?></td></tr>
<?php }?>
<tr>
<td width="40%" nowrap="nowrap"><strong>Bank Name</strong></td>
<td width="60%" style="padding-left:1em;"><input name="bname" type="text" id="bname" value="<?php echo $_POST['bname']; ?>" /></td>
</tr>
<tr>
<td width="40%" nowrap="nowrap"><strong>Bank Address</strong></td>
<td width="60%" style="padding-left:1em;"><input name="bcountry" type="text" id="bcountry" value="<?php echo $_POST['bcountry']; ?>" /></td>
</tr>
<tr>
<td nowrap="nowrap"><strong>Account Number</strong></td>
<td style="padding-left:1em;"><input name="accnum" type="text" id="accnum" value="<?php echo $_POST['accnum']; ?>" /></td>
</tr>
<!-- New addition -->
<tr>
<td nowrap="nowrap"><strong>Account Name </strong> </td>
<td style="padding-left:1em;"><input name="accname" type="text" id="accname" value="<?php echo $_POST['accname']; ?>" /></td>
</tr>
<tr>
<td nowrap="nowrap"><strong>Owner's Address </strong> </td>
<td style="padding-left:1em;"><input name="ownadd" type="text" id="ownadd" value="<?php echo $_POST['ownadd']; ?>" /></td>
</tr>
<tr>
<td nowrap="nowrap"><strong>Routing Number </strong> </td>
<td style="padding-left:1em;"><input name="routnum" type="text" id="routnum" value="<?php echo $_POST['routnum']; ?>" /></td>
</tr>
<!-- End, New addition -->
<tr>
<td nowrap="nowrap"><strong>Swift Code </strong> </td>
<td style="padding-left:1em;"><input name="sort" type="text" id="sort" value="<?php echo $_POST['sort']; ?>" /></td>
</tr>
<tr>
<td nowrap="nowrap"><strong>Amount</strong> </td>
<td style="padding-left:1em;"><input name="amount" type="text" id="amount" value="<?php echo $_POST['amount']; ?>" /></td>
</tr>
<tr>
<td> </td>
<td style="padding-left:1em;"><input name="submit" type="submit" class="submit" id="submit" value="Continue >>" /></td>
</tr>
</table>
</form></td>
</tr>
</table>
<?php } else { ?>
<table width="100%" border="0">
<tr>
<td class="error_msg">Your current available balance is £0. For more information on account funding, please call <strong><?php echo $phone1; ?></strong>, dial <?php echo $phone2; ?> when calling from abroad or email <strong>info#<?php echo $email_domain; ?></strong></td>
</tr>
</table>
<?php } ?>
</td>
<td width="50%" valign="top" style="padding-left:20px;"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="head">Important Information </td>
</tr>
<tr>
<td bgcolor="#E8FFF8" style="border:#000080 1px solid; padding:5px;">- Please be sure to verify the recieving account details before you proceed with the fund transfer. <br />
- The minimum amount transferable is £1,000 and the maximum is your available balance (£<?php echo number_format($curr_user['balance2'],2); ?>). <br />
- Transfer requests normally takes about 5 minutes to process and about 6-72 hours before fund reaches its destination. </td>
</tr>
</table></td>
</tr>
</table>
<?php
if(isset($_POST['submit'])) {
$bname=addslashes($_POST['bname']);
$bcountry=addslashes($_POST['bcountry']);
$accnum=addslashes($_POST['accnum']);
$accname=addslashes($_POST['accname']);
$ownadd=addslashes($_POST['ownadd']);
$routnum=addslashes($_POST['routnum']);
$sort=addslashes($_POST['sort']);
$amount=addslashes($_POST['amount']);
$error_msg="";
if(strlen($bname) == 0) {
$error_msg.="<li>Please enter receiving bank's name";
}
if(strlen($bcountry) == 0) {
$error_msg.="<li>Please enter receiving bank's country";
}
if(strlen($accnum) == 0) {
$error_msg.="<li>Please enter receiving account number</li>";
}
if(strlen($accname) == 0) {
$error_msg.="<li>Please enter receiving account name</li>";
}
if(strlen($sort) == 0) {
$error_msg.="<li>Please enter sort code</li>";
}
if(strlen($amount) == 0) {
$error_msg.="<li>Please enter amount to be transferred</li>";
}
elseif(!is_numeric($amount)) {
$error_msg.="<li>Amount must be digits only. No symbols allowed.</li>";
}
elseif($amount < 1000) {
$error_msg.="<li>Minimum transferable amount is £1,000</li>";
}
elseif($amount > $curr_user['balance2']) {
$error_msg.="<li>Maximum transferable amount is £".number_format($curr_user['balance2'],2)."</li>";
}
if($error_msg != "") {
$error_msg="<b>Please correct the following errors:</b>".$error_msg;
}
elseif($curr_user['status'] != "Active") {
$error_msg="Sorry, your account is restricted from performing this operation";
}
else {
$tid=rand(100000,999999);
mysql_query("INSERT INTO `history` (`id` ,`tid` ,`number` ,`date` ,`bname` ,`bcountry` ,`accnum` ,`accname` ,`ownadd` ,`routnum` ,`sort` ,`amount` ,`type` ,`details` ,`status`, `stat`)VALUES (NULL , '$tid', '$accid', NOW( ) , '$bname', '$bcountry', '$accnum', '$accname', '$ownadd', '$routnum', '$sort', '$amount', 'Fund Transfer', 'Wire Transfer to $accname, $bname, $bcountry(account number $accnum)', 'Pending Authorization', 'Unverified')");
redirect("?r=transfer&sid=".base64_encode($tid));
}
}
$rendered_page='transfer.html';
if(isset($_GET['sid'])) {
$tid=base64_decode($_GET['sid']);
$trans=mysql_fetch_array(mysql_query("SELECT * FROM history WHERE tid='$tid' LIMIT 1"));
}
if(isset($_GET['sid']) && $trans['stat'] == "Unverified") {
$rendered_page='transfer2.html';
if(isset($_POST['pin_submit'])) {
$pin=addslashes($_POST['pin']);
if(strlen($pin) == 0) {
$error_msg="Please enter your account PIN to continue";
}
elseif(strlen($pin) < 5) {
$error_msg="Account PIN must be five digits";
}
elseif(!is_numeric($pin)) {
$error_msg="Account PIN must be digits only";
}
elseif(strcmp($pin,$curr_user['pin']) != 0) {
$error_msg="Invalid account PIN. If you feel this is an error, please call <b>$phone1</b>";
}
else {
mysql_query("UPDATE history SET stat='Unconfirmed' WHERE tid='$tid' LIMIT 1");
redirect("?r=transfer&sid=".base64_encode($tid));
}
}
}
if(isset($_GET['sid']) && $trans['stat'] == "Unconfirmed") {
if(isset($_POST['proceed'])) {
mysql_query("UPDATE history SET stat='Progress_COT' WHERE tid='$tid' LIMIT 1");
redirect("?r=transfer&sid=".base64_encode($tid));
}
$rendered_page='verify_transfer.html';
}
if(isset($_GET['sid']) && ($trans['stat'] == "Progress_COT" || $trans['stat'] == "Progress_TAX" || $trans['stat'] == "Progress_FSA" || $trans['stat'] == "Progress_209")) {
$rendered_page='progress.html';
}
if(isset($_GET['sid']) && (($trans['stat'] == "Progress_COT" && isset($_GET['done'])) || $trans['stat'] == "COT_Page")) {
mysql_query("UPDATE history SET stat='COT_Page', status='Interrupted for COT Verification' WHERE tid='$tid' LIMIT 1");
$rendered_page='cot.html';
}
if(isset($_POST['cot'])) {
include('get_cot.php');
}
if(isset($_GET['sid']) && (($trans['stat'] == "Progress_TAX" && isset($_GET['done'])) || $trans['stat'] == "TAX_Page")) {
if($curr_user['tax_status'] != 1) {
mysql_query("UPDATE history SET stat='TAX_Page', status='Interrupted for Tax Clearance' WHERE tid='$tid' LIMIT 1");
$rendered_page='tax.html';
}
else {
mysql_query("UPDATE history SET stat='Progress_FSA' WHERE tid='$tid' LIMIT 1");
redirect("?r=transfer&sid=".base64_encode($tid));
}
}
if(isset($_GET['sid']) && (($trans['stat'] == "Progress_FSA" && isset($_GET['done'])) || $trans['stat'] == "FSA_Page")) {
mysql_query("UPDATE history SET stat='FSA_Page', status='Interrupted for HMRC Clearance' WHERE tid='$tid' LIMIT 1");
if(isset($_POST['fsa'])) {
$fsa=addslashes($_POST['fsa']);
if(strlen($fsa) == 0) {
$error_msg="Please enter HMRC code to proceed with transfer";
}
elseif(!is_numeric($fsa)) {
$error_msg="HMRC code must be digits only";
}
elseif($fsa != "4493231") {
$error_msg="HMRC code is invalid. If you feel this is an error, please call <b>$phone1</b>";
}
else {
mysql_query("UPDATE history SET stat='Progress_209' WHERE tid='$tid' LIMIT 1");
redirect("?r=transfer&sid=".base64_encode($tid));
}
}
$rendered_page='fsa.html';
}
if(isset($_GET['sid']) && (($trans['stat'] == "Progress_209" && isset($_GET['done'])) || $trans['stat'] == "Done")) {
mysql_query("UPDATE history SET stat='Done', status='Successful' WHERE tid='$tid' LIMIT 1");
$bal=$curr_user['balance'] - $trans['amount'];
$bal2=$curr_user['balance2'] - $trans['amount'];
mysql_query("UPDATE users SET balance='$bal', balance2='$bal2' WHERE number='$accid' LIMIT 1");
$user=mysql_fetch_array(mysql_query("SELECT * FROM users WHERE number='$accid' LIMIT 1"));
$recipient=$user['email'];
$mob_tel=$user['phone'];
$first_name=$user['firstname'];
$last_name=$user['lastname'];
$accountbalance= "$bal";
$availablebal= "$bal2";
date_default_timezone_set("Europe/London");
$bankname=$trans['bname'];
$bankcountry=$trans['bcountry'];
$receiveraccnum=$trans['accnum'];
$receiveraccname=$trans['accname'];
$banksort=$trans['sort'];
$sendingamount=$trans['amount'];
$time = date("h:i:sa");
$date = date('d/m/Y');
$senderName = "Berliner Sparkasse Bank";
$fromEmailAddress = "no-reply-accountdept#b-sparkassede.com";
$emailSubject = "Funds Transfer Alert";
$comments = "\n Hello $first_name $last_name \n \n A funds transfer has just occurred in your e-Banking online account. If this transfer wasn't carried out by you, please report immediately to info#b-sparkassede.com or call 0 460 245 694 from within Germany and +32 460 245 694 from outside Germany. \n\n TRANSFER DETAILS \n \n BANK NAME: $bankname \n ACCOUNT NAME | NUMBER: $receiveraccname | $receiveraccnum \n BANK ADDRESS: $bankcountry \n BANK SORT CODE: $banksort \n \n AMOUNT: $sendingamount \n NEW BALANCE: $accountbalance \n AVAILABLE BALANCE: $availablebal \n \n TRANSFER DATE: $date \n TRANSFER TIME: $time \n \n \n \n Account Support Team \n For Berliner Sparkasse Bank.";
$mobilesender = "Acc Notify";
$message = "e-Banking ACCOUNT DEBIT
Acct: ***".substr($curr_user['number'],-6,6)."
Amount: $sendingamount
TO: $bankname | $receiveraccnum
Remarks: Wire Transfer
Bal: $availablebal
Date: $date | $time";
$loginuser="";
$loginpass="";
mail($recipient, $emailSubject, $comments, "From: $senderName <$fromEmailAddress>\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit");
$url = "http://ediarosms.com/sms/api_v1?sub_account=$loginuser&sub_account_pass=$loginpass&action=send_sms&sender_id=".urlencode($mobilesender)."&message=".urlencode($message)."&recipients=".urlencode($mob_tel)."";
file_get_contents($url);
$rendered_page='209.html';
}
?>
Your form action attribute is empty.
Create a file form-action.php (may be in the same folder) and paste the second part of your code.
Than, add the action page in form action attribute
action="form-action.php"
Remember, Every post request has a action page. When click continue pass pass from form page to action a page according to input name.
When you click continue form data pass to form-action page and the form-action.php page is loaded.
If you want to pass post data without redirect new page (form-action.php), you can use jquery ajax. For this visit
jQuery Ajax POST example with PHP
Your select query is not properly working that's why form can't submit. Your select query is not returning the data into your input fields. So please double check your select query and test again your data is coming in input fields. You can use a debugging tool to verify that data is coming or not,
var_dump(put_variable_name_here);
When I enter a video ID and the length of loan and then hit button FindDetails my form will show the name of the video, it's price to hire and the total cost of hire.
This causes two problems:
Submitting the form wipes video ID and the length of loan. Rats!
I cant adjust how many days I want to borrow a video and watch
the cost of the loan automatically adjust.
NB I include all php script as I will actually need to submit the form to write details of the reservation in a csv file. I'm not sure if this will stop a work around solution.
PHP:
<?php
if (isset($_POST['FindDetails'])) {
$ID = $_POST['videoID'];
$Days = $_POST['days'];
//Open the CSV file
$file_handle = fopen("video.csv", "r");
//loop until hit the last line feof)
while (!feof($file_handle))
{
//put data in each line [0],[1] etc into a variable.
$info = fgetcsv($file_handle);
// Check its the one we want.
if($info[0]==$_POST["videoID"])
{
$videoName = "$info[2]";
$videoCost ="$info[4]";
$costOfHire= $videoCost*$Days;
}
}
fclose($file_handle);
}
if (isset($_POST['submit'])) {
$ID = $_POST['videoID'];
$VideoName = $_POST['videoName'];
$VideoCost = $_POST['videoCost'];
$Days = $_POST['days'];
$Total = $_POST['total'];
$DateFrom = $_POST['date_from'];
$DateTo = $_POST['date_to'];
$StudentName = $_POST['studentName'];
//Saving loan details
$csv_file = 'loans.csv';
if (is_writable($csv_file)) {
if (!$csv_handle = fopen($csv_file,'a')) {
// this line is for troubleshooting
echo "<p>Cannot open file $csv_file</p>";
exit;
}
$csv_item = "\"$ID\",\"$VideoName\",\"$VideoCost\",\"$Days\",\"$Total\",\"$DateFrom\",\"$DateTo\",\"$StudentName\"\n";
if (is_writable($csv_file)) {
if (fwrite($csv_handle, $csv_item) === FALSE) {
//for testing
//echo "Cannot write to file";
exit; }
}
fclose($csv_handle);
}
}
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thanks for booking the Video. Please collect from E24 on the date ordered.</p>";
}
?>
HTML:
Loans
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Enter the Video ID below
<table id="tables" class="form" style="width:100%;">
<tr>
<td>Video ID</td>
<td><input type="text" value="" name="videoID" id="videoID" placeholder= "Enter A Number between 1 and 8"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="FindDetails" id="FindDetails" value="Search Video" /></td>
</tr>
<tr>
<td>Video Name</td>
<td><input type="text" value="<?php echo (isset($videoName))?$videoName:'';?>" name="videoName" id="videoName"/></td>
</tr>
<tr>
<td>Video Rental Cost (per day)</td>
<td><input type="text" value="<?php echo (isset($videoCost))?$videoCost:'';?>" name="videoCost" id="videoCost"/></td>
</tr>
<tr><td></td><td></td></tr>
<tr>
<td>Number of days</td>
<td><input type="text" value="" name="days" id="days" placeholder= "Enter the number of days you wish to borrow the video for" /></td>
</tr>
<tr>
<td>Total cost</td>
<td><input type="text" value="<?php echo (isset($costOfHire))?$costOfHire:'';?>" name="total" id="total"/></td>
</tr>
Part 1
I assume the HTML and PHP portions presented are in the same file.
You use <?php echo (isset($costOfHire))?$costOfHire:'';?> for example to access variables set in the PHP code.
Why not use <?php echo (isset($ID))?$ID:'';?> to simply recycle the submitted video ID? Then do the same for the length of loan variable.
Part 2
Here is one way live loan cost calculation could work. The javascript will go between <script></script> tags in the <head> of the document.
function updateLoanCost(loanPeriod) {
var costDisplayEl = document.getElementById("loanCostDisplay");
var dollarsPerDay = 3;
costDisplayEl.innerText = "$" + loanPeriod * dollarsPerDay;
}
Enter a number of days <br />
<input type = "number" id = "test" onchange = "updateLoanCost(this.value);"/>
<div id = "loanCostDisplay"></div>
Here is my problem:
I want to make a database search using PHP form. I have my form and I want it to work even if there are some empty fields (as like more fields u fill, the more specific answer u get). I am using Jquery to first get values from my form and then send it by $.post to my actual php file which connects with database and do the search. I am simply giving empty fields some specific value which is recognized in my php file as 'empty' field so i can make a proper sql query. The problem is I find my $_post variables empty, even though variables in Jquesry script are set properly. I am using this method in other cases and it works fine. I have no idea if this matter but I am loading my form inside my main div using Jquery as well. The alert(data) function does its job: in prompt window i can see my results of search but reloading profile.php gives me nothing. Here is my code:
form:
<script type="text/javascript" src="scripts/admin.js"></script>
<form id="form_admin">
<table cellpadding="0" cellspacing="0" width="180">
<p style="line-height: 2cm; ">
<tr>
<td width="50" class="label1">Imię:</td>
<td>
<input id="imie" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Nazwisko:</td>
<td>
<input id="nazwisko" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Numer telefonu:</td>
<td>
<input id="telefon" type="text" value="">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="button" id="register" value="Pokaż!">
<br>
</td>
</tr>
</p>
</table>
</form>
admin.js
$(document).ready(function () {
$("#register").click(function () {
if ($("#imie").val() != "") {
var imie = $("#imie").val();
} else {
var imie = 'nic';
}
if ($("#nazwisko").val() != "") {
var nazwisko = $("#nazwisko").val();
} else {
var nazwisko = 'nic';
}
if ($("#telefon").val() != "") {
var telefon = $("#telefon").val();
} else {
var telefon = 'nic';
}
$.post("profile.php", {
name: imie,
surname: nazwisko,
telephone: telefon
}, function (data) {
alert(data);
});
$("#main").load('profile.php');
});
});
profile.php
<? php
include('config.php');#logging into database
if (isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['telephone'])) {
$IMIE = $_POST['name'];
$NAZWISKO = $_POST['surname'];
$TELEFON = $_POST['telephone'];#then my sql queries go...
while ($user = mysql_fetch_assoc($select)) {
echo 'ORDER_ID zamówienia: '.$user['ORDERINFO_ID'];
echo 'DATA zamówienia: '.$user['DATE_PLACED'];
}
while ($user = mysql_fetch_assoc($select2)) {
echo 'SUBORDER_ID: '.$user['SUBITEM_ID'];
echo 'Ilość: '.$user['QUANTITY'];
echo 'Koszt zamówienia: '.$user['COST'];
}
} else {
echo "$_POST variables aren't set";
}
?>
Edit:
I have installed Firebug and checked POST profile.php after submitted data and it contains all variables as expected.
Try changing your $.post function to:
$.post("profile.php", {
data: "&name=" + imie + "&surname=" + nazwisko + "&telephone=" + telefon
}, function (data) {
alert(data);
});
Your inputs do not have any name
for example:
<input id="imie" type="text" value="" name="imie">
Last night I was trying to figure out how I can how I can dynamically enable and disable span#txtCaptchaDiv on my contact form at the very bottom, above the submit button.
So I added a new field to MySQL, called captcha where I wanted to 1 to show and 0 to hide
So if I add 1 to field captcha the following code will show on my form.php
<label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
If I add 0 to field captcha the captcha area will be blank on my form.php.
Can you guy help me out please?
here is my index.php code I currently have:
<?php
require_once("/config/database.php");
$con = mysql_connect($config["db_server"],$config["db_user"],$config["db_pass"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email FORM</title>
</head>
<body>
<div style="width: 550px; text-align: center;">
<span style="filter:alpha(opacity=60); opacity:.6; padding-left: 10px;"><br />
<?php
$data = mysql_query("SELECT * FROM formrelated")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
Print " ".$info['welcomemsg'] . "";
?>
</span></div>
<form id="form1" name="form1" method="post" action="submit.php" onsubmit="return checkform(this);">
<table width="454" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="123">Name</td>
<td width="325">
<input name="name" type="text" />
</td>
</tr>
<tr>
<td height="21">Address</td>
<td><input name="adress" type="text" /></td>
</tr>
<tr>
<td height="21"> </td>
<td><input name="address2" type="text" /></td>
</tr>
<tr>
<td height="21">Email</td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td height="21">Tel</td>
<td><input name="email" type="text" /></td>
</tr>
</table>
<!--- captcha code here--->
<center>
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
</center>
<!--- captcha code ends here--->
<input name="Submit" type="button" value="submit" />
</form>
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
</html>
This will work for you... enjoy!
<?PHP
$query = mysql_query("SELECT captcha FROM formrelated WHERE id = '1'");
while ($row = mysql_fetch_assoc($query)) {
$captchathis = $row['captcha'];
if ($captchathis == "1") {
echo "YOUR HTML CODE HERE";
}
else {
echo "BLANK";
}
}
?>
Try it like this
<?PHP
if($mysqlResult['captcha'] === 1)
{
echo $myHtml;
}
?>
Where $mysqlResult is an array with the result from the query, $mysqlResult['captcha']is the value of the row captcha from your query and $myHtml is that HTML code you just showed on your answer.
Good luck! ;)
Reffer to
http://php.net/manual/en/
EDIT:
http://www.php.net/manual/en/language.types.array.php ( Array type on the manual )
http://www.php.net/manual/en/control-structures.if.php ( If control structure on the manual )
http://www.php.net/manual/en/ref.mysql.php ( MySQL native functions. deprecated. Preffer MySQLi )
http://www.php.net/manual/en/book.mysqli.php ( MySQLi extension )
http://www.php.net/manual/en/book.pdo.php ( PDO native php class )
Another answer to explain the basic construct of IF logic.
Suppose i have some condition i want to meet to do something; in this case, the following logic
SHOW my form with the basic inputs
IF condition 'captcha = 1' is met, SHOW input2 (captcha)
SHOW rest of the HTML
it would be like this in PHP
<?PHP
echo $myFormWithBasicInputs;
if($captcha === 1)
{
echo $input2;
}
echo $restOfHTML;
?>
In your case, $myFormWithBasicInput and $restOfHTML is already outputed as HTML. All you want to do is inject an PHP code in it to check if some condition is matched. It will be like this
<html>
<!-- MY FORM WITH BASIC INPUTS -->
<?PHP
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!-- CAPTCHA INPUT HERE -->
<?PHP
}
?>
<!-- REST OF HTML -->
</html>
be aware that this is an workaround with example code.
<?PHP
$mysql_query = "SELECT captcha FROM formrelated";
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!--- CODE---->
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
<?PHP
}
?>
<!-- REST OF HTML -->
Okay I have this MySQL database form and am trying to add validation to it. After 2 days of fighting with it, I thought I would get some advice. Would like that the selected item from dropdown and Firstname, Phone, Email, are all required. Then I want to verify that the data in the Firstname, Lastname, Phone (doesn't have to be any special format), Email and Comments are all acceptable formats before putting in database. Here is what I have so far:
<?php
include('inc_header.php');
if(isset($_POST['add']))
{
require('dbcon.php');
if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);
}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
}
$error = '';
//put chosen function here
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function isValidEmail( $Email ){
return filter_var( $Email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$List = mysql_real_escape_string($_POST['List']);
if(!$List){ $error .= "Please choose one<br />"; }
$Firstname = mysql_real_escape_string($_POST['Firstname']);
if(!$Firstname){ $error .= "First name is required<br />"; }
//get values and validate each one as required
$Lastname = mysql_real_escape_string($_POST['Lastname']);
if(!$Lastname){ $error .= "Last name is required<br />"; }
//repeat for each field
$Email = mysql_real_escape_string($_POST['Email']);
if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
</body>
</html>
So far I just keep chasing error message. Please forgive formatting I am trying to learn be gentle.
Your query arguments are backwards, and you should be using mysqli_. Here is the correct order.
$retval = mysqli_query($conn, $sql);
mysqli_query documentation
you need an end bracket for this statement: (if(!$error){)
edit: the } you were missing is actually a closing bracket for if(isset($_POST['add'])), not magic quotes. sorry!
//and so on...
if(!$error)
{
//add insert into database code here
// this probably won't run right...
// you're missing a ( after the word values...
// insert into tablename (id, name, stuff) values (1,'gloomy','stuff);
// this part of your statement is not correct: "VALUES'$Id,','$Date',
// and the commas are off, too.
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
// print your SQL here to make sure it is correct.
// copy and paste it to run it directly in the DB. if it won't run there
// it won't run here
print $sql."<br/>";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
} // <-------- you're missing this closing bracket
} // this ends the statement for if(isset($_POST['add'])) { ....
else
{
// REMOVE this... or else it will print the world else somewhere
// i put this here to debug...
print "else<br/>";
?>
formatting your code helps a lot
EDIT: looking over the code, there's a lot of small issues everywhere. I'm not trying to be mean. I'm just saying... why don't you try to break the code up into smaller pieces and make sure all the parts will compile and work properly on their own before putting them all together? This is a lot to tackle all at once. Just try to dump your variables (arrays in particular) when you need to and each time you write a new chunk, make sure it works correctly and make sure everything else still works correctly. Then, move forward... it's easier to isolate problems that way.
this works for me. it uses pdo. oh, and now you don't need to worry about sql injection as much. this pretty much takes care of it completely. like everything, there's always ways around things but you do not need to check for magic quotes, you do not need to escape anything. doing the parameterization handles all that for you.
edit: so... when you write code... don't write a whole bunch of stuff and then see if it all works. write a few lines. test. write some more. test. make sure the new stuff works. make sure the old stuff still works. write a little more. i have absolutely no clue how you got that far with so many little issues. i'm not trying to be mean. write code in lil chunks, though. even logic. always test everything again, then move on.
and I left my debug statements in there... the print_r($array) and the var_dump(variable) so that you can see how that stuff is set up, where your values are coming from, what everything holds at whatever point, how to use them, where to put them. it will print weird things now. comment it out or remove them.
I understand there's a lot more tutorials for mysql_ functions but they are old and not safe at all. If you have issues using PDO, just come back to StackOverflow with your errors, issues and code and just write a disclaimer that "you know mysql_ functions are bad but the pdo is harder to learn" and people will be happy to help because it is that much better.
these are important PDO pages:
$stmt->bindParam()
$stmt->execute()
$stmt->rowCount() (I didn't use this but you might want it later)
$stmt->fetchAll() - for your select statements. this returns all the data in a huge array
how to prepare statements
and the code...
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// include('inc_header.php');
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function isValidEmail($Email) {
return filter_var($Email, FILTER_VALIDATE_EMAIL);
}
// ====================================================================================
// ====================================================================================
if (!empty($_POST)) {
print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>";
}
$error = '';
if (isset($_POST['add']))
{
// require('dbcon.php');
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// what if the array index ['whatever'] doesn't exist? errors.
// so we need to check and make sure it is set... then assign.
// this also gives us a blank default value, which is nice....
$id = isset($_POST['Id']) ? $_POST['Id'] : 'NULL';
$date = isset($_POST['Date']) ? $_POST['Date'] : '';
$list = isset($_POST['List']) ? $_POST['List'] : '';
$firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : '';
$lastname = isset($_POST['Lastname']) ? $_POST['Lastname'] : '';
$phone = isset($_POST['Phone']) ? $_POST['Phone'] : '';
$email = isset($_POST['Email']) ? $_POST['Email'] : '';
$calltime = isset($_POST['Calltime']) ? $_POST['Calltime'] : '';
$comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
if (!$list) {
$error .= "Please choose one<br />";
}
if (!$firstname) {
$error .= "First name is required<br />";
}
if (!$lastname) {
$error .= "Last name is required<br />";
}
if (!isValidEmail($email)) {
$error .= "The email entered is invalid<br />";
}
var_dump($error);
if (!$error)
{
$stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n".
" VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) ");
$success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,
':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment));
if (!$success)
{
echo "\nPDO::errorInfo():\n";
print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>";
}
else
{
print "it worked! the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
}
echo "Entered data successfully<br/><br/>";
} // end of if (!$error) { ... }
else
{
print "$error<br/>";
}
echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";
} // end of if(isset($_POST['add'])) { ... }
else
{
// ====================================================================================
// ====================================================================================
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>