I'm sure this has been asked 1000 times, but I have looked all over and can't seem to get this to work.
form:
<form action="sendinfo.php" method="post">
<h4>ID:</h4>
<input type="text" name="CustomerID">
<h4>First name:</h4>
<input type="text" name="FirstName">
<h4>Last Name:</h4>
<input type="text" name="LastName">
<h4>Street:</h4>
<input type="text" name="Street">
<h4>City:</h4>
<input type="text" name="City">
<h4>Zip:</h4>
<input type="text" name="Zip">
<h4>State:</h4>
<input type="text" name="State">
<h4>Phone:</h4>
<input type="text" name="Phone">
<h4>Email:</h4>
<input type="text" name="Email">
<input type="submit">
</form>
sendinfo.php
<?php
include('connection.php');
$dbh = con();
$dbh->query = "INSERT INTO Customer (CustomerID, FirstName, LastName, Street, City, State, Zip, Phone, Email)
VALUES ('$_POST[CustomerID]', ('$_POST[FirstName]', ('$_POST[LastName]', ('$_POST[Street]', ('$_POST[City]', ('$_POST[State]', ('$_POST[Zip]', ('$_POST[Phone]', ('$_POST[Email]')";
if (!mysql_query($user_info, $connect)) { die('Error: ' . mysql_error()); } echo “Your information was added to the database.”; mysql_close($connect);
?>
connection.php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "Impact_Technologies");
define("DB_USER", "root");
define("DB_PASS", "password");
function con(){
try {
$db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return $db_connection;
} catch (PDOException $e) {
echo "Sorry, there was a problem connecting to the database." . $e->getMessage();
}
}
?>
When submit is clicked, no messages displayed and no information entered into the db
I see what's the problem, ('$_POST[CustomerID]', ('$_POST[FirstName]', ('$_POST[LastName]', ('$_POST[Street]', ('$_POST[City]', ('$_POST[State]', ('$_POST[Zip]', ('$_POST[Phone]', ('$_POST[Email]')
You're opening a parenthesis before every value, it should be like this:
('$_POST[CustomerID]', '$_POST[FirstName]', '$_POST[LastName]', '$_POST[Street]', '$_POST[City]', '$_POST[State]', '$_POST[Zip]', '$_POST[Phone]', '$_POST[Email]')
First, Simplify your code by doing this
$id = $_POST['custormerID'];
$firstName = $_POST['FirstName'];
//and so on
Secondly, Remove all the opening parenthesis before every value
$dbh->query = "INSERT INTO Customer (CustomerID, FirstName,
LastName, Street, City,
State, Zip, Phone, Email)
VALUES ('$id', '$FirstName',
'$LastName', '$Street', '$City',
'$State', '$Zip', '$Phone', '$Email')";
if (!mysqli_query($user_info, $connect)) {
die('Error: ' . mysqli_error());
}
echo “Your information was added to the database.”; mysql_close($connect);
Thirdly, mysql is depreciated, use mysqli or PDO instead
if (!mysql_query($user_info, $connect)) {
die('Error: ' . mysql_error()); }
echo “Your information was added to the database.”; mysql_close($connect);
do this instead:
if (!mysqli_query($user_info, $connect)) {
die('Error: ' . mysqli_error());
}
echo “Your information was added to the database.”; mysqli_close($connect);
Side Note: Is either you use mysqli or PDO, don't use the both.
You can learn about PDO http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers and http://www.w3schools.com/php/php_mysql_intro.asp
Related
I am learning PHP.using XAMPPlocal server to test. Need help below
when I enter the details and click register in the form, I just see a blank page with the action.php link.
Code for action.php is below:
include 'config.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['register'])){
require 'config.php';
$first_name = !empty($_POST['fname']) ? trim($_POST['fname']) : null;
$last_name = !empty($_POST['lname']) ? trim($_POST['lname']) : null;
$user_name = !empty($_POST['uname']) ? trim($_POST['uname']) : null;
$pass = !empty($_POST['upass']) ? trim($_POST['upass']) : null;
$user_email = !empty($_POST['umail']) ? trim($_POST['umail']) : null;
$sql = "INSERT INTO ams_users (id, firstname, lastname, username, password, email)
VALUES(?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(0,$first_name, $last_name, $user_name, $pass, $user_email);
if($result){
echo 'Thank you for registering';
}else{
echo 'sorry';
}
}enter code here
code for register.php form below:
<div class="reg-form">
<h1>Register</h1>
<form action="action.php" method="POST">
<p><label>First Name* :</label>
<input id="firstname" type="text" name="fname" /></p>
<p><label>Last Name* :</label>
<input id="lasttname" type="text" name="lname" /></p>
<p><label>User Name* : </label>
<input id="username" type="text" name="uname" /></p>
<p><label>Password: </label>
<input id="password" type="password" name="upass" /></p>
<p><label>E-Mail: </label>
<input id="e-mail" type="e-mail" name="umail"/></p>
<input type="submit" name="submit" value="register" />
</form>
</div>
MySQL table has 5 entries: id (autoincrement, firstname, lastname,username,password, and email.
please help where I am going wrong.
execute() takes an array of parameters not directly like you did.
You have less question marks then parameter
If you make id AUTOINCREMENTED then you can omit it from your query
So it becomes:
INSERT INTO ams_users (firstname, lastname, username, password, email)
VALUES(?,?,?,?,?)
Then you execute:
$result = $stmt->execute(array($first_name,
$last_name,
$user_name,
$pass,
$user_email)
);
Or:
INSERT INTO ams_users (id,firstname, lastname, username, password, email)
VALUES('',?,?,?,?,?)
The problem is you should have gotten the error, so make sure it is turned on:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I am trying to make a simple PHP form submission and insert some data to MySQL, my tables are:
category: id, category_name
table1: category_id(FK), title,description
table2: table1_id(FK), filetype, filesize, filedate, filename
Form: Date, Title, description, category(drop down), upload file (get the file info like type, ext, size, filename)
Here is the code:
Form:
<strong>Fill up the form:</strong><br /><br>
<form enctype="multipart/form-data" action="upfileone.php" method="POST">
Date: <?php echo date("d-M-Y") ?>
<p>Title:
<input type="text" name="title" value="<?php echo $sel_filepage['file_title']; ?>" id="file_title" />
</p>
<p>Description:<br>
<textarea name="description" rows="4" cols="24">
<?php echo $sel_filepage['content']; ?></textarea>
</p>
Category:
<select name="select_cat">
<?php $cat_set = get_all_categs();
while($category = mysql_fetch_array($cat_set)){
$catname = $category['cat_name'];
echo '<option value="'.$catname.'">'.$catname.'</option>';
}
?>
</select>
<br><br>
<label for="file">Choose File to Upload:</label>
<input type="file" name="upfile" id="upfile" > <br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="hidden" name="filepage" value="<?php echo $_GET['filepage']?>">
<input type="submit" name="upload" value="Add" class="pure-button pure-button-success">
Cancel
</form> <!-- END FORM -->
Action file:
<?php
require_once("includes/functions.php");
// directory to be saved
$target = "server/php/files/";
$target = $target . basename($_FILES['upfile']['name']);
// gets info from FORM
$currentDate = date("Y-m-d");
$file_title = $_POST['title'];
$content = $_POST['description'];
$category = $_POST['select_cat'];
$upfile = ($_FILES['upfile']['name']);
// connects to db
$con = mysqli_connect("localhost", "root", "password", "database");
if(mysqli_connect_errno())
{
echo "error connection" . mysqli_connect_error();
}
// insert to database
$sql = "INSERT INTO filepages (category_id,file_title,content)
VALUES ('$category','$file_title','$content')";
/*$sql2 = "BEGIN
INSERT INTO filepages (category_id, file_title, content)
VALUES ('$category','$file_title','$content')
INSERT INTO fileserv (file_date)
VALUES ($currentDate)
COMMIT";*/
if(!mysqli_query($con, $sql))
{
die('Error ' . mysqli_error());
}
echo "1 File Added <br>";
if (file_exists("server/php/files/" . $_FILES["upfile"]["name"]))
{
echo $_FILES["upfile"]["name"] . " already exists. ";
}
else
{
insertFile( $_POST['filepage'],
$_FILES["upfile"]["type"],
($_FILES["upfile"]["size"] / 1024),
$_FILES["upfile"]["name"]);
move_uploaded_file($_FILES["upfile"]["tmp_name"],"server/php/files/" . $_FILES["upfile"]["name"]);
echo "The FILE " . basename($_FILES['upfile']['name']) . " has been uploaded.<br>";
echo "Stored in: " . "server/php/files/" . $_FILES["upfile"]["name"] . "<br>";
echo "Upload: " . $_FILES["upfile"]["name"] . "<br>";
echo "Type: " . $_FILES["upfile"]["type"] . "<br>";
echo "Size: " . ($_FILES["upfile"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["upfile"]["tmp_name"] . "<br>";
}
?>
It does insert to both tables, now my main problem is how to get the ID from drop down menu of category and insert to Filepages.category_id.
How can I get the Filepages.ID data and insert it to Fileserve?
So you want the ID of the inserted row.
You can simply use the following php function http://www.php.net/manual/en/mysqli.insert-id.php
This question should nonetheless be moved to stackoverflow
I'm trying to make a page where users can update their information such as their name/email and password. Below is the update function:
public function update() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "UPDATE users SET `username` = :username, `password` = :password, `name` = :name, `email` = :email WHERE `userID` = :userID";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->bindValue( "name", $this->name, PDO::PARAM_STR );
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->bindValue( "userID", $this->userID, PDO::PARAM_STR );
$stmt->execute();
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");
Here is the form on the page:
<?php
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">
<ul>
<li>
<label for="usn">Name : </label>
<input type="text" id="usn" maxlength="36" required autofocus name="name" value="' . $row['name'] . '" />
<input type="text" name="userID" value="' . $row['userID'] . '" class="displaynone"/>
</li>
<li>
<label for="usn">Email : </label>
<input type="text" id="usn" maxlength="46" required autofocus name="email" value="' . $row['email'] . '" />
</li>
<li>
<label for="usn">Username : </label>
<input type="text" id="usn" maxlength="30" required autofocus name="username" disabled="disabled" value="' . $row['username'] . '" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" id="passwd" maxlength="30" required name="password" />
</li>
<li>
<label for="conpasswd">Confirm Password : </label>
<input type="password" id="conpasswd" maxlength="30" required name="conpassword" />
</li>
<li class="buttons">
<input type="submit" name="update" value="Update" />
<input type="button" name="cancel" value="Cancel" />
</li>
</ul>
</form>';
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values //if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->update($_POST);
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match";
}
?>
This returns the following error:
PDO::FETCH_ASSOC: Return next row as an array indexed by column name SQLSTATE[HY000]: General error
I'm really stuck here. I don't know how to troubleshoot this any further.
I have a form which has the following fields:
Company Name,
Address,
City
Using the AUSU jquery autosuggest scripts I am able to populate the address field based on the search done in the company field but what I can't seem to be able to accomplish is also populating the city field with the appropriate value. All data is stored in a mysql database.
I've gotten as far as being able to have the address and city populate the address field but I need these 2 values to go into their respective fields (shiptoaddress and shiptocity).
Any suggestions?
This is my php to obtain data from mysql database:
<?php
$con = mysql_connect("localhost","userid","password");
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db("dbase", $con);
$id = #$_POST['id']; // The id of the input that submitted the request.
$data = #$_POST['data']; // The value of the textbox.
if ($id && $data)
{
if ($id=='clients')
{
$query = "SELECT shiptoaddress,company, shiptocity
FROM Clients
WHERE company LIKE '%$data%'
LIMIT 5";
$result = mysql_query($query);
$dataList = array();
while ($row = mysql_fetch_array($result))
{
$toReturn = $row['company'];
$dataList[] = '<li id="' .$row['shiptoaddress'] .$row['shiptocity'] . '">' . htmlentities($toReturn) . '</li>';
}
if (count($dataList)>=1)
{
$dataOutput = join("\r\n", $dataList);
echo $dataOutput;
}
else
{
echo '<li>No Results</li>';
}
}
}
?>
And this is part of the html form code:
<script>
$(document).ready(function() {
$.fn.autosugguest({
className: 'ausu-suggest',
methodType: 'POST',
minChars: 2,
rtnIDs: true,
dataFile: 'data.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<form action="index.php" method="get">
<div class="ausu-suggest">
<input type="text" size="100" value="" name="clients" id="clients" autocomplete="off" />
<input type="text" size="100" value="" name="shiptoaddress" id="shiptoaddress" autocomplete="off"/>
<input type="text" size="100" value="" name="shiptocity" id="shiptocity" autocomplete="off"/>
</div>
</form>
I solved my problem by using the Jquery autocomplete widget.
I'm trying to make a simple contact form for my website, so I bought one from Code Canyon. After not receiving slow and scarce help from the author, I'm asking you guys for help.
Basically it's a very simple contact form but I'm not too good with coding so it bothers me regardless. This is the HTML code;
<div id="contact" class="clearfix"><!-- contact -->
<h1><img name="logo" src="" width="300" height="50" alt="" style="background-color: #3366FF" /></h1><p class="txn">Lorem ipsum dim sum sum.</p>
<div id="message"></div>
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<legend>Please fill in the following form to contact us</legend>
<label for=name accesskey=U><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for=email accesskey=E><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for=phone accesskey=P><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="" />
<br />
<label for=subject accesskey=S>Subject</label>
<select name="subject" type="text" id="subject">
<option value="Support">Support</option>
<option value="a Sale">Sales</option>
<option value="a Bug fix">Report a bug</option>
</select>
<br />
<label for=comments accesskey=C><span class="required">*</span> Your comments</label>
<textarea name="comments" cols="40" rows="3" id="comments" style="width: 350px;"></textarea>
<p><span class="required">*</span> Are you human?</p>
<label for=verify accesskey=V> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />
<input type="submit" class="submit" id="submit" value="Submit" />
</fieldset>
</form>
The JavaScript file I was given in the template...practically unchanged
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(450,function() {
$('#message').hide();
$('#submit')
.after('<img src="assets/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#telephone').val(),
subject: $('#enquiry').val(),
comments: $('#message').val(),
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('fast');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#contactform #submit').attr('disabled','');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
And then there is the contact-php file I got
<?php
if(!$_POST) exit;
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
exit();
}
if(trim($subject) == '') {
echo '<div class="error_message">Attention! Please enter a subject.</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message">Attention! Please enter your message.</div>';
exit();
} else if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please enter the verification number.</div>';
exit();
} else if(trim($verify) != '4') {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#themeforest.net";
$address = "mylerworks#gmail.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
?>
Problem is: let's say I fill up the form but forget to put my name in. The form will notify me I forgot it but I will not be able to post it, I will need to refresh the page. Also, it keeps giving me the "please enter a valid phone number" error even when I fill the form completely.
So how do I get it to work?
In case I didn't post something correctly here, check how the form looks here - You can view the form here
Your submit button is disabled after posting data . That is why you are not able to re-post it
$('#contactform #submit').attr('disabled','');
Use correct id of input field.
phone: $('#telephone').val(),
this will be always null as there is no component with this id
Its same kind of error. There is no element with id enquiry or message.
subject: $('#enquiry').val(),
comments: $('#message').val(),
Please be sure about name and id of your html components while retrieving values
Thanks