The form submits correctly and it sends me an email. No error is reported and the SQL it creates works fine, I tested it at phpMyAdmin. mysql_error() raises nothing, it just doesn't add a row. Can anyone see what's going on?
<?PHP
$to = "me#gmail.com";
$subject = "New Lead";
$date = date ("l, F jS, Y");
$time = date ("h:i A");
$mysql = mysql_connect("db.perfora.net:3306","db","password");
if(!$mysql)
{
die("Could Not Connect: ".mysql_error());
}
mysql_select_db("db",$mysql);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['firstname']." ".$_POST['lastname'];
$email = $_POST['email'];
$phone = "(".$_POST['areacode'].") ".$_POST['firstthree']."-".$_POST['lastfour'];
$area = $_POST['area'];
$lookdate = $_POST['lmm']."/".$_POST['ldd']."/".$_POST['lyyyy'];
$lookdatedb = date("{$_POST['lmm']}.{$_POST['ldd']}.{$_POST['lyyyy']}");
$movedate = $_POST['mmm']."/".$_POST['mdd']."/".$_POST['myyyy'];
$movedatedb = date("{$_POST['mmm']}.{$_POST['mdd']}.{$_POST['myyyy']}");
$loft = $_POST['loft'] ? "loft" : "";
$highrise = $_POST['highrise'] ? "highrise" : "";
$traditional = $_POST['traditional'] ? "traditional" : "";
$price = $_POST['price'];
$comments = $_POST['comments'];
$sql = "INSERT INTO Leads
(Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments)
VALUES
('$name', '$email', '$phone', '$area', '$lookdatedb', '$movedatedb', '{$_POST['loft']}', '{$_POST['highrise']}', '{$_POST['traditional']}', '$price', '$comments')";
if (mysql_query($sql,$con))
{
echo "Row added.";
}
else
{
echo "Error adding row: " . mysql_error();
echo("\n\n".$sql);
}
$msg = "
New Lead Submitted On $date at $time.\n\n
Name: $name\n
Email: $email\n
Phone: $phone\n
Area: $area\n
Look Date: $lookdate\n
Move Date: $movedate\n
Type: $loft $highrise $traditional \n
Price: $price\n
Comments: $comments\n
";
}
mysql_close($mysql);
mail($to, $subject, $msg, "From:$email");
if ($forward == 1) {
header ("Location:$location");
}
else {
echo "Thank you for submitting our form. We will get back to you as soon as possible.";
}
?>
Response:
Thank you for submitting our form. We will get back to you as soon as possible.
Generated SQL:
INSERT INTO Leads (Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments) VALUES ('work work', 'work#work.com', '(214) 131-4131', 'dallas', '02.18.2010', '02.25.2010', '', '1', '1', '$333333333333333333', '33fdsdfsdfsd')
Database Structure:
http://imgur.com/iQHRk.jpg
Let's see, your DB connection handle is obviously referenced by $mysql, but you've done this:
if (mysql_query($sql,$con))
Your DB handler is wrong.
mysql_query($sql,$con);
should return something why don't you take a look at that
i.e.
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
It's a best practice to check for errors when you can.
Also to be noted, you are not escaping any of the user input so your code is vulnerable to SQL injections. please use mysql_real_escape_string.
take the post variable in another variable and then pass to the insert query i think it will be work
like this
$sql = "INSERT INTO Leads
(Name, Email, Phone, Area, LookDate, MoveDate, Loft, HighRise, Traditional, Price, Comments)
VALUES
('$name', '$email', '$phone', '$area', '$lookdatedb', '$movedatedb', '$loft', '$highrise', '$traditional', '$price', '$comments')";
mysql_query($sql);
Related
It's working, but when I add the data in to my database, the data will be twice. I don't know if my syntax is wrong or my code is wrong.
Here's the structure:
//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) {
if (isset($_POST['submitBtn'])) {
if ($row['reservefrom'] == $checkin) {
echo "Same Date";
return;
}
else
{
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
$address = $_POST['text_address'];
$tnumber = $_POST['text_tnumber'];
$cnumber = $_POST['text_cnumber'];
$email = $_POST['text_email'];
$checkin = $_POST['text_checkin'];
$checkout = $_POST['text_checkout'];
$room = $_POST['text_room'];
$tour = $_POST['text_tour'];
$guest = $_POST['text_guest'];
$query = "INSERT INTO reservation
(lastname, firstname, homeaddress,
telephonenumber, cellphonenumber, email,
reservefrom, reserveto, room, tour,
guestnumber)
values ('$lastname', '$firstname', '$address',
'$tnumber', '$cnumber', '$email', '$checkin',
'$checkout', '$room', '$tour', '$guest')";
mysqli_query($db, $query);
echo "Data Submitted!";
}
}
}
You're getting multiple inserts because you are looping for each record in $reservations. You should first look into why you are getting multiple records if you expected just a single record reservation.
That aside, alter your code by replacing your while loop with:
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){
if($row['reservefrom'] == $checkin) die("Same Date");
$lastname = $_POST['text_lastname'];
$firstname = $_POST['text_firstname'];
// ... other values, then execute your query
}else{
// either submitBtn was not posted or no result were found in $reservation
}
I noticed also that you use return in your code, but the code doesn't seem to be within a function so that's confusing. If it is within a function, it's probably a bad idea to echo from within unless the function is specifically meant to send data directly to the browser.
the problem is..i try to parsing json from php..here is jquery code:
$.post( "confirmsignup.php", $("#signupform").serialize()).always(function( data ) {
alert(data.msg);
}, "json");
PHP code:
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!($query_run = mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
?>
{
"msg": "<?php echo $msg ." - ". $query; ?>"
}
secureing() is for returning string after escape_string..
$msg suppose to return string "complete"... but it returning "error"..
however in phpmyadmin, query is successfully executed..
i think there is no mistake..what is my mistake?please help..
Can you please change the following code with your code, I have used mysql_insert_id to check record is inserted or not.
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
$query_run = mysql_query($query);
$id = mysql_insert_id();
if($id > 0)
{
$msg = "complete";
}
else
{
$msg = "error";
}
It may help you.
I have same issue long time ago!
it's because you haven't any AI primary key in the table!
add a field like this to the table: id INT Primary Key Auto Increment.
this will works!
and migrate to mysqli or pdo for better security and support! ;)
try my code is seem you have put wrong condition
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!(mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
i just found the solution, after change my php API to connecting to database.
from:
if(!#mysql_connect('localhost', 'root', '')||!#mysql_select_db('knewit')){
die("something not right");
}
to:
$mysqli = new mysqli("localhost", "root", "", "knewit");
after that, i change my executing method from mysql_query to $mysqli->query.
i also change my jquery post method from always to done.
and the final code be like this.
jQuery script:
$.post( "confirmsignup.php", $("#signupform").serialize()).done(function( data ) {
alert(data.msg);
}, "json");
PHP script:
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$passs=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '$passs', '$dob')";
if(!($query_run = $mysqli->query($query))){
$msg = "error";
}
else
{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
$arrayName = array('msg' => $msg );
echo json_encode($arrayName);
thank you for answer my question. i really appreciate it.
I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!
The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";
you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";
mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected
Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)
UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.
if (isset($submit)) {
$getusers = mysql_query("SELECT * FROM register");
while($getrows = mysql_fetch_array($getusers)) {
$users = $getrows['username'];
if ($touser == $users) {
echo "$users";
$send = $_GET['send'];
if ($send == $one) {
$query = mysql_query(
"INSERT INTO mailtbl VALUES
(
'', '$touser', '$fromuser', '$subject',
'$message', '0', '0', '1', '$date', '$rand'
)"
);
$query2 = mysql_query(
"INSERT INTO mailtbl_admin VALUES
(
'', '$touser', '$fromuser', '$subject',
'$message', '0', '0', '1', '$date', '$rand'
)"
);
$echo = "Message successfully sent.";
}
} else {
$echo = "There is no such user with the name of '$touser'";
}
}
echo "$echo";
}
I am trying to write code that accepts the message to send to another user if the recipient is in my database. The problem is that I think my condition (if ($touser == $users) is wrong. $touser refers to my $_POST['recipient'] in my form and $users refer to the users in the database.
Could someone please review my code to ensure I'm on the right track?
Instead of looping through all the users in your table, why don't you instead add a WHERE statement in your SQL command like this:
"SELECT * FROM register WHERE username = '" . $touser . "'"
If you get results send the message. If you get no results, display the 'no such user' message.
Also, if you are having trouble evaluating $touser to $user, try outputting the contents of $touser to make sure it's what you think it is.
print_r($touser);