Basic PHP/MySQL INSERT INTO Multiple Tables from Forms - mysql

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

Related

How to notification show after Form successful submit

I change my website template. i change Contact Form also previous contact form work correctly, when i change contact form template than submit form successful notification dont show under submit button. i checked all details but i can not find any error. help me this form.
form code
<form class="contact-form" id="contact-form" method="post" action="sendemail.php">
<div class="form-group tiple">
<input type="text" class="contact-box" name="name" value="" placeholder="Enter Your Name">
</div>
<div class="form-group tiple">
<input type="email" class="contact-box" name="email" value="" placeholder="Enter Your Email">
</div>
<div class="form-group tiple">
<input type="text" pattern="[6|7|8|9][0-9]{9}" class="contact-box" name="phone" value="" placeholder="10 Digit Mobile No.">
</div>
<div class="form-group">
<label>Subject</label>
<select name="subject" class="form-control">
<option value="Demo Registraion">Demo Registraion</option>
<option value="Contact Us">Contact Us</option>
<option value="Feedback">Feedback</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<textarea name="message" class="contact-box" placeholder="Your Message" rows="10"></textarea>
</div>
<button type="submit" class="short-line margin-top-10">Submit now</button>
</form>
sendmail.php code
<?php
// Define some constants
define( "RECIPIENT_NAME", "NAME" );
define( "RECIPIENT_EMAIL", "mail#email.com " );
// Read the form values
$success = false;
$senderName = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$senderPhone = isset( $_POST['phone'] ) ? preg_replace( "/[6|7|8][0-9][9]/", "", $_POST['phone'] ) : "";
$subject = isset( $_POST['subject'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['subject'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
// If all values exist, send the email
if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$mailBody = 'Sender Name: ' . $senderName. "\r\n" . 'Sender Email: ' . $senderEmail . "\r\n" .'Sender Phone: '. $senderPhone . "\r\n" . 'Subject: ' . $subject . "\r\n" . 'Message: ' . $message;
$success = mail( $recipient, $subject, $mailBody, $headers );
echo 'Your Request Send Successful';
echo "<p class='success'>Thanks for contacting us. We will contact you ASAP!</p>";
?>
i want an notification under the submit button
msg submit successfull or failed
You can follow PRG pattern and use RedirectAttributes to add flash attributes.
For example:
#RequestMapping(value = "/contractor", method = RequestMethod.POST)
public String handle(#Valid #ModelAttribute Contractor contractor,
BindingResult result,
RedirectAttributes redirectAttributes) {
// Save contactor ...
redirectAttributes.addFlashAttribute("message", "Successful!");
return "redirect:/someGetUrl";
}
And just show this message in the view rendered by /someGetUrl handler.

How to Transfer Data in Web Form to a Database

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

Can't update table when POST form is getting it's ID from a previuos GET form

On my index.php page I have a form method='GET' action='new.php' which gets it's values from a mySQL query.
On top on the new.php page: $id = $_GET['id'] which retrieves the id from the previuos form in the index.php page. And on the new.php page I also have a form which get it's values through a query with help of $id but this time it's a POST form thats update a table with a mySQL query.
But the table it's not updating. Why is that? I know that I have all the code right because when I change GET on the index.php page to POST the table is updating.
EDIT:This is the code from new.php
require_once('include/connect.php');
$id = htmlentities ($_GET['id']);
if (isset($_POST['edit_client'])) {
if ($_POST['edit_client'] == "1") {
$_POST['edit_client'] = "0";
$query3 = "SELECT * FROM client WHERE id='" . $id ."'";
$result3 = $connect->query($query3);
$result_rs3 = mysqli_fetch_assoc($result3);
if(mysqli_num_rows($result3)!=0){
do{
echo"<form action='' method='POST' class='ajaxform'>
<div class='col-md-6 padding0 kundForm'>
<div class='controls controls-row left'>
<label>Firstname</label>
<input type='text' size='22' class='form-control' name='firstname' value='" . $result_rs3['firstname'] . "'>
</div>
<div class='controls controls-row left marginLeft10'>
<label>Lastname</label>
<input type='text' size='22' class='form-control span3' name='lastname' value='" . $result_rs3['lastname'] . "'>
</div>
</div>
<div class='marginTop20 clear'>
<input type='submit' value='Save' class='btn btn-primary btn-danger center-block' onclick=\"return confirm('Save changes?')\"/>
<input type='hidden' name='edit_name' value='1'/>
<input type='hidden' name='id' value='" . $id . "'/>
</div>
</form> \n";
}
while($result_rs3 = mysqli_fetch_assoc($result3));
}
}
}else if (isset($_POST['edit_name'])) {
if ($_POST['edit_name'] == "1") {
$_POST['edit_name'] = "0";
$id = htmlentities ($_POST['id']);
$firstname = htmlspecialchars ($_POST['firstname']);
$lastname = htmlspecialchars ($_POST['lastname']);
$query2 = "UPDATE client SET
firstname ='" . $firstname . "',
lastname ='" . $lastname . "',
WHERE id ='" . $id . "'";
$connect->query($query2);
mysqli_close($connect);
}
}
Solved it myself. Screwed up my if-statesment. Changed the else if{} to if{} and that did the trick!

Send completed form information to an email

Hey guys I'm just starting to learn some php and I was wondering how I could send information from a completed form to an email. I have the code I have listed on the bottom but I know it's not right, any help will be appreciated thanks!
PHP:
<?php
$email = $_REQUEST['clientEmail'] ;
$subject = "New Order";
$name = $_REQUEST['clientName'] ;
$articleAmount = $_REQUEST['articleNum'];
$wordAmount = $_REQUEST['wordNum'];
$topic = $_REQUEST['topic'];
$info = $_REQUEST['addInfo'];
mail("kevin.duan996#gmail.com", $subject,
"Name:" . $name . "<br/>" . "Amount of Articles:" . $articleAmount . "<br/>" . "Amount of Words:" . $wordAmount . "<br/>" . "Topic:" . $topic . "<br/>" . "Additional Information:" . $info, "From:" . $email);
echo "Thank you for ordering!";
?>
html:
<form action="order.php">
<fieldset id="client" >
<legend>Client Information</legend>
<label for="clientName">Name:</label><input type="text" name="clientName" id="clientName" tabindex="1"/>
<label for="clientEmail">Email:</label><input type="email" name="clientEmail" id="clientEmail" tabindex="2"/>
</fieldset>
<fieldset id="order">
<legend>Order Information</legend>
<label for="articleNum">Number of Articles</label><input type="text" name="articleNum" id="articleNum" tabindex="3"/>
<label for="wordNum">Words per Article</label><input type="text" name="wordNum" id="wordNum" tabindex="4"/>
<label for="topic">Topics</label><input type="text" name="topic" id="topic" tabindex="5"/>
<label for="addInfo">Additional Info</label><input type="text" name="addInfo" id="addInfo" tabindex="6"/>
</fieldset>
<fieldset>
<button type="submit">Submit!</button>
</fieldset>
</form>
Use PHP mail or PHPMailer (works pretty well) ?
Using the PHPMailer library: https://github.com/PHPMailer/PHPMailer
define('PROJECT_ROOT', '/path/to/your/root/'); //Different for different webhosts or self hosted environments
require (PROJECT_ROOT . 'PHPMailer-master/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$to = $_POST['clientEmail']; //Email dervied from POST data.
$mail->Host = "mail.example.com"; //If you haven't got an SMTP server, use Gmail's free one.
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Username = "someEmail#example.com";
$mail->Password = "somePass";
$mail->From = 'someEmail#example.com';
$mail->FromName = 'My Website';
$mail->WordWrap = 50;
$mail->isHTML(true); // Or false
$mail->addReplyTo('support#example.com', 'Support');
$mail->Subject = 'Message subject here';
$mail->addAddress($to);
$mail->Body = ""; // Message body using HTML here. (Remove if $mail->isHTML(); is false)
$mail->AltBody = "
Client: " . $_POST['clientName'] . " //Again: derived from POST data.
Email: " . $to . " //We defined this variable before as clientEmail
Number of Articles: " . $_POST['articleNum'] . "
Words per Article: " . $_POST['wordNum'] . "
Topics: " . $_POST['topic'] . "
Additional Info: " . $_POST['addInfo'] . "
";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
} else {
echo "Mail sent!";
}
I noticed that your form is missing a method of sending this information that the users type in.
<form action="order.php">
It should be:
<form action="order.php" method="POST">
Hope that you get it working!

AUSU jquery-Ajax Autosuggest Multiple values

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.