I am fairly new to both PHP and MySQL and would appreciate some help with this one.
What I am trying to achieve: store a time sheet into a MySQL table using the form below which should post each day's data into a separate row while keeping the same employee name for each day entered. The user has the option to add additional days to the form -- a max of 7. I've tested everything without the use of arrays and am able to store data to the table without any problems.
HTML:
<form id="timesheet" method="post" action="timekeep.php">
<fieldset>
<h1>Employee Info</h1>
<ul>
<li>
<label>First Name:</label>
<input name="firstname" type="text">
</li>
<li>
<label>Last Name:</label>
<input name="lastname" type="text">
</li>
</ul>
</fieldset>
<fieldset>
<h1>Time Info</h1>
<h3>Day: 1</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
<h3>Day: 2</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
</fieldset>
<input id="submit" name="submit-time" type="submit" value="Submit Time">
</form>
PHP:
$sql_connection = mysql_connect($dbhost, $dbuser, $dbpass) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbuser, $sql_connection);
$sql = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (".
PrepSQL($date) . ", " .
PrepSQL($firstName) . ", " .
PrepSQL($lastName) . ", " .
PrepSQL($straightHours) . ", " .
PrepSQL($overtimeHours) . ", " .
PrepSQL($premiumHours) . ", " .
PrepSQL($totalHours) . ", " .
PrepSQL($perDiem) . "
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
Using PDO object would make this easier, mysql_ is legacy anyway:
$db = new PDO($hostname,$username,$password);
$qry = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (:date, :firstname, :lastname, :straighthours, :overtimehours, :premiumhours, :totalhours, :perdiem)"; // colon variables will be bound to actual variable
$statement = $db->prepare($query); //prevents injection
// binds variables to place holder in query
$statement->bindValue(':firstname', $firstname);
$statement->bindValue(':lastname', $lastname);
$statement->bindValue(':straighthours', $straighthours);
$statement->bindValue(':overtimehours', $overtimehours);
$statement->bindValue(':premiumhours', $premiumhours);
$statement->bindValue(':totalhours', $totalhours);
$statement->bindValue(':perdiem', $perdiem);
$statement->execute();
$statement->closeCursor();
you can do further input checking with php before passing anything to the sql via:
trim(strip_tags(htmlentities($firstname)));
PDO is a lot simpler to use and understand IMO
UPDATE:
tutorials on PDO
UPDATE #2:
For added functionality with arrays per day you can do:
<input type="text" name="firstname1">
// do this for all fields then
$workingday1 = array();
$workingday1['firstname'] = $_GET['firstname1'];
// etc. for all the other fields
Then you can access the field by:
$workingday1 = $_GET['workingDay1']; // or post or however you want to pass it
$firstname = $workingday['firstname'];
After that you can prune your database however you like. You can have a single table with all the values and edit your selects to display by employee or day or w/e. You can also have a table for each employee and then grab from those tables and display the data how ever you like.
Related
I'm a complete newbie in php & MySQL
Basically what I want to do is be able to retrieve data from a table
in MySQL database and put it in a drop down menu .
After I fill in the other fields I want to data from the drop down menu to be written to another table in the same database .
This is my insert.php file
<?php
#### INSERTS A SINGLE CUSTOMER IN Company-->Customer Database with UTF8 Change for special German Characters - Cyrilic Doesnt work - Other change then utf8 ???
#### Getting Data from Index.php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "company";
//making an array with the data recieved, to use as named placeholders for INSERT by PDO.
#### Getting DAta from Index.php
$data = array('CustomerName' => $_POST['CustomerName'] , 'Address1' => $_POST['Address1'], 'Address2' => $_POST['Address2'], 'City' => $_POST['City'], 'PostCode' => $_POST['PostCode'], 'CountryID' => $_POST['CountryID'], 'ContactName' => $_POST['ContactName'], 'ContactEmail' => $_POST['ContactEmail'], 'ContactPhone' => $_POST['ContactPhone'], 'ContactFax' => $_POST['ContactFax'], 'Website' => $_POST['Website']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); ### Database Connect with Special characters Change
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query with named placeholders to avoid sql injections
$query = "INSERT INTO customer (CustomerName, Address1, Address2, City, PostCode, CountryID, ContactName, ContactEmail, ContactPhone, ContactFax, Website )
VALUES (:CustomerName, :Address1, :Address2, :City, :PostCode, :CountryID, :ContactName, :ContactEmail, :ContactPhone, :ContactFax, :Website )";
//statement handle $sth
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>
And this is the source from the html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Product</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="CustomerName">CustomerName:</label>
<input type="text" name="CustomerName" id="CustomerName">
</p>
<p>
<label for="Address1">Address 1:</label>
<input type="text" name="Address1" id="Address1">
</p>
<p>
<label for="Address2">Address 2:</label>
<input type="text" name="Address2" id="Address2">
</p>
<p>
<label for="City">City:</label>
<input type="text" name="City" id="City">
</p>
<p>
<label for="PostCode">Post Code:</label>
<input type="text" name="PostCode" id="PostCode">
</p>
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
<p>
<label for="ContactName">Contact Name:</label>
<input type="text" name="ContactName" id="ContactName">
</p>
<p>
<label for="ContactEmail">Contact Email:</label>
<input type="text" name="ContactEmail" id="ContactEmail">
</p>
<p>
<label for="ContactPhone">Contact Phone:</label>
<input type="text" name="ContactPhone" id="ContactPhone">
</p>
<p>
<label for="ContactFax">Contact Fax:</label>
<input type="text" name="ContactFax" id="ContactFax">
</p>
<p>
<label for="Website">Website:</label>
<input type="text" name="Website" id="Website">
</p>
<input type="submit" value="Add Records">
</form>
</body>
</html>
So I wanna add this php code that pulls out the country list and prefixes for the phone numbers and then when I hit the submit button the actual output of the drop down menu to we written in the customers table
<p>
<label for="CountryID">Country:</label>
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "company";
$con_qnt = mysqli_connect($servername, $username, $password, $dbname);
if(!mysqli_connect("localhost","root",""))
{
die('oops connection problem ! --> '.mysqli_connect_error());
}
if(!mysqli_select_db($con_qnt, "company"))
{
die('oops database selection problem ! --> '.mysqli_connect_error());
}
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
I don't even know if this is doable - I searched for long time but couldn't find anything that is kind of what I need . Mostly I found hard coded html dropdown menus . In fact hard coding this will work for the countries but it wont work if I want it to be able to show lets say products in a drop down menu . Thank you all in advance .
Hi I just made a quick sample to answer your question on how to populate dropdown using data from database.
In this example, I used
JQuery's AJAX Function
so first, for the backend, (this is just a quick sample to select data. Do not use this as a pattern for your future codes
<?php
$dbh = new PDO("mysql:host=localhost;dbname=dbhelp", 'root', 'pup');
$stmt = $dbh->prepare("SELECT * from t_country");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
?>
I repeat. This is just for quick reference. Do not use it as a pattern for your code.
So using that code, we have now selected data from our table country and usedjson_encode to make it in json format. read more about this here. http://php.net/manual/en/function.json-encode.php.
Next one is the frontend(HTML part)
<body>
// empty dropdown button to be filled by data from database
<select id="country">
</select>
//include the jquery library
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax ({
url : 'dropdown_database.php', // the url from which the data will be pulled
success: function(data) {
var country = $.parseJSON(data); // parse the json format data
$.each(country, function(i, d) {
$('#country').prepend('<option>'+ d.country +'</option>'); // this one adds the <option></option> tag in the dropdown
});
}
});
});
</script>
If I got you right, you want to replace this:
<p>
<label for="CountryID">Country ID:</label>
<input type="text" name="CountryID" id="CountryID">
</p>
With a dropdown so you can quickly pick the country from the dropdown instead of memorizing the ID for each individual country. And to create the select you are using this code:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='label'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryName' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
<name="CountryID" id="CountryID">
</p>
That should work fine... after you fix some issues:
If you want to replace the input with the select, the select should have the same name as the input so the value is processed automatically. Right now the select has "label" as the name and there is a strange (and incorrect) name tag. To fix this:
Get rid of the unnecessary name tag.
Replace the name attribute in the select with value "CountryID":
echo "<select name='CountryID'>";
The option value should be the country ID so, unless the ID is the country name (not the best choice), you are not using the right value. Change that line too:
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
(Considering CountryID as the ID, replace it for the right column name).
And I think with those two changes, the rest of the code should work just fine with insert.php that wouldn't require any updates at all. Finally it would look something like this:
<p>
<label for="CountryID">Country:</label>
<?php
// some code here that I removed to avoid noise
$sql = "SELECT * FROM country";
$result = mysqli_query($con_qnt, "SELECT * FROM country" );
echo "<select name='CountryID'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['CountryID' ] . "'>" . $row['CountryName' ] . " (" .$row['PhonePrefix' ] . ")" . "</option>";
}
echo "</select>";
?>
</p>
I am trying to insert 4 forms that are the same. but with different values to mysql using PHP.
When I submit my data, the database only takes the values from the last form and inserts it 4 times. I am trying to get the values from all 4 on submit.
<div class="req3">
<h1>Requirement 4</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<br>
Enter info for 4 teams and it will inserted into the database<br><br>
<div class="sqlForm">
<p class="formHead">Team 1</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 2</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 3</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br>
</div>
<div class="sqlForm">
<p class="formHead">Team 4</p>
<label>Team Name:</label> <input type="text" name="teamname"><br>
<label>City:</label> <input type="text" name="city"><br>
<label>Best Player:</label> <input type="text" name="bestplayer"><br>
<label>Year Formed:</label> <input type="text" name="yearformed"><br>
<label>Website:</label> <input type="text" name="website"><br><br></div>
<input class="styled-button" type="submit" name="insert" value="Submit">
</form>
<?php
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
$servername = "localhost:3306";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo ("Connection failed: " . $conn->connect_error);
} else {
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite')";
if ($conn->multi_query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysql_query($sql);
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
}
}
?>
chnage the names of your controls so they Post as Arrays
<input type="text" name="teamname[G1]">
<input type="text" name="teamname[G2]">
this why when you use $varTname = $_POST['teamname']; $varTname is an array and each of the 4 values of teamname are set as $varTname['G#'] where # matches the number you set for that group of input fields.
then use a for loop to get the data and execute your query, something like bellow. while you at it you can also fix up your SQL Injection vulnerability. you may also want to so some more sanitation to the data just to be sure
$varTname = $_POST['teamname'];
$varCity = $_POST['city'];
$varBplayer = $_POST['bestplayer'];
$varYearformed = $_POST['yearformed'];
$varWebsite = $_POST['website'];
$stmt = $mysqli->prepare('INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES (?,?,?,?,?,?)');
$varTname1Bind = "";
$varTnameBind = "";
$varCityBind = "";
$varBplayerBind = "";
$varWebsiteBind = "";
// assuming they are all strings, adjust where needed
$stmt->bind_param('sssssss',
$varTname1Bind,
$varTnameBind,
$varCityBind,
$varBplayerBind,
$varYearformedBind,
$varWebsiteBind);
for($i = 1; i < 5; $i++)
{
$varTname1Bind = $varTname['G'.$i];
$varTnameBind = $varTname['G'.$i];
$varCityBind = $varCity['G'.$i];
$varBplayerBind = $varBplayer['G'.$i];
$varYearformedBind = $varYearformed['G'.$i];
$varWebsiteBind = $varWebsite['G'.$i];
$stmt->execute();
}
will save you on how much code you need to do
You can convert your input names into arrays by adding [] then in your php loop through the array of the $_POST[] and built up your $sql by concatenating the values until you finish looping through all values and INSERT it as multiple values.
HTML:
<label>Team Name:</label> <input type="text" name="teamname[]"><br>
<label>City:</label> <input type="text" name="city[]"><br>
<label>Best Player:</label> <input type="text" name="bestplayer[]"><br>
<label>Year Formed:</label> <input type="text" name="yearformed[]"><br>
<label>Website:</label> <input type="text" name="website[]"><br>
PHP:
<?php
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES ";
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$sql .= "(" .$varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite. "),";
}
$sql = rtrim($sql, ','); // omit the last comma
// Then Excute your query
?>
This way you don't need to give them unique names name="test1", name="test2" and so, to see it in action check this PHP Fiddle in the bottom of the result page, I've already set the values of the input fields, just hit submit and go to the bottom of the result page to see the composed INSERT statement.
NOTE that the above SQL is just a demo on how to build it up, DO NOT use it like this without validation and sanitizing.. ALSO STOP querying this way and instead use Prepared Statements with PDO or MySQLi to avoid SQL Injection.
So for MySQLi prepared statements, procedural style - I work with PDO - as you see in this PHP Fiddle 2, the code is:
<?php
// you validation goes here
if (isset($_POST['insert'])) {
insertTable();
} else {
$conn->close();
}
function insertTable() {
// enter your credentials below and uncomment it to connect
//$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$sql = "INSERT INTO Teams (teamname, city, bestplayer, yearformed, website) VALUES";
$s = '';
$bind = '';
for($i = 0 ; $i < count($_POST['teamname']) ; $i++){
$sql .= " (?, ?, ?, ?, ?)";
$s .= 's';
$varTname = $_POST['teamname'][$i];
$varCity = $_POST['city'][$i];
$varBplayer = $_POST['bestplayer'][$i];
$varYearformed = $_POST['yearformed'][$i];
$varWebsite = $_POST['website'][$i];
$bind .= " , " . $varTname. " , " .$varCity. " , " .$varBplayer. " , " .$varYearformed. " , " .$varWebsite;
}
$sql = rtrim($sql, ','); // omit the last comma
$s = "'" .$s. "'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, $s , $bind);
mysqli_stmt_execute($stmt);
}
?>
Normally this is done by creating arrays of form controller.
<input type="text" name="teamname[]">
<input type="text" name="city[]">
And then you can get an array in post request.
Hope this helps!
use different name like teamname1,teamname2,teamname3,teamname4
<input type="text" name="teamname1">
<input type="text" name="teamname2">
<input type="text" name="teamname3">
<input type="text" name="teamname4">
For get values :-
$varTname1 = $_POST['teamname1'];
$varTname2 = $_POST['teamname2'];
$varTname3 = $_POST['teamname3'];
$varTname4 = $_POST['teamname4'];
For insert values :-.
$sql = "INSERT INTO Teams (teamname)
VALUES ('$varTname1'),
('$varTname2'),
('$varTname3'),
('$varTname4')
or you can try this:-
<input type="text" name="teamname[]">
Get value like :-
$_POST['teamname'][0]
try this method
$sql = "INSERT INTO Teams (teamname, city, bestplayer,yearformed,website)
VALUES ('$varTname', '$varCity', '$varBplayer', '$varYearformed', '$varWebsite'),
";
$sql.= query same as abov
$sql.= query same as abov
$sql.= query same as abov
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
note the . dot after the first query.
I think you should also use an auto increment keyThis should work.
Hello Currently I have a MYSQL DB in which I post form data into. I then USE PHP to echo the data out and see the form info. Recently I added a check box and the values of the check box get stored as an ARRAY. When I go to echo my DB the output I get is
Name,Date,Array,Array
Instead of getting the word ARRAY I would like to get the value of the submission. I know you are supposed to use the implode command but I could not figure out a way to incorporate it into my code. The retrieval code looks like this. With field_10,field_11,field_12 returning just the word ARRAY.
<html>
<head>
</head>
<body>
<style>
body {background-color:#DAD8EE}
</style>
<img class="formInfo" src="ree.jpg" alt="" style="width:1000px;">
<?
$con = mysql_connect("localhost","dk1","root1");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("usersignup", $con);
$query = "SELECT * FROM `users`";
$comments = mysql_query($query);
echo "<h1> User Sign Ups </h1>";
while($row = mysql_fetch_array($comments, MYSQL_ASSOC))
{
$company=$row['field_1'];
$name=$row['field_2'];
$contact_numb=$row['field_3'];
$email_adress=$row['field_4'];
$conf_yr=$row['field_5'];
$dt_arrival=$row['field_6'];
$arrival_tm=$row['field_7'];
$dt_depart=$row['field_8'];
$departure_tm=$row['field_9'];
$dnr_one=$row['field_10'];
$dnr_two=$row['field_11'];
$cmd_shw=$row['field_12'];
$company = htmlspecialchars($row['field_1'],ENT_QUOTES);
$name = htmlspecialchars($row['field_2'],ENT_QUOTES);
$contact_numb = htmlspecialchars($row['field_3'],ENT_QUOTES);
$email_adress = htmlspecialchars($row['field_4'],ENT_QUOTES);
$conf_yr = htmlspecialchars($row['field_5'],ENT_QUOTES);
$dt_arrival = htmlspecialchars($row['field_6'],ENT_QUOTES);
$arrival_tm = htmlspecialchars($row['field_7'],ENT_QUOTES);
$dt_depart= htmlspecialchars($row['field_8'],ENT_QUOTES);
$departure_tm = htmlspecialchars($row['field_9'],ENT_QUOTES);
$dnr_one= htmlspecialchars($row['field_10'],ENT_QUOTES);
$dnr_two= htmlspecialchars($row['field_11'],ENT_QUOTES);
$cmd_shw= htmlspecialchars($row['field_12'],ENT_QUOTES);
echo " <div style='margin:30px 0px;'>
<ul>
<li>Name: $name<br /></li>
<li>Company: $company<br /></li>
<li>Contact Number: $contact_numb<br /></li>
<li> Email Adress: $email_adress<br /></li>
<li> Conference Year: $conf_yr<br /></li>
<li> Date of Arrival: $dt_arrival<br /></li>
<li> Arrival Time: $arrival_tm<br /></li>
<li> Date of Departure: $dt_depart<br /></li>
<li> Departure Time: $departure_tm</br></li>
<li> Dinner on the 14th?: $dnr_one</br></li>
<li> Dinner on the 15th?: $dnr_two</br></li>
<li> Comedy Show?: $cmd_shw</br></li>
</div>
";
}
mysql_close($con);
?>
The form processing code is this
<?php
$where_form_is="http://".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9,field_10,field_11,field_12) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . $_POST['field_3'] . "','" . $_POST['field_4'] . "','" . $_POST['field_5'] . "','" . $_POST['field_6'] . "','" . $_POST['field_7'] . "','" . $_POST['field_8'] . "','" . $_POST['field_9'] . "','" . $_POST['field_10'] . "','" . $_POST['field_11'] . "','" . $_POST['field_12'] . "')";
mysql_query($query);
mysql_close($link);
include("confirms.html");
?>
The Form itself
<div id="mainForm">
<div id="formHeader">
<img class="formInfo" src="ree.jpg" alt="" style="width:1000px;">
<h2 class="formInfo">DEMO Conference Sign Up </h2>
<p class="formInfo">DEMO </p>
</div>
<BR/><!-- begin form -->
<form method=post enctype=multipart/form-data action=processors.php onSubmit="return validatePage1();"><ul class=mainForm id="mainForm_1">
<li class="mainForm" id="fieldBox_1">
<label class="formFieldQuestion">Company Name *</label><input class=mainForm type=text name=field_1 id=field_1 size='20' value=''></li>
<li class="mainForm" id="fieldBox_2">
<label class="formFieldQuestion">Guest Name * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Guest Name here</span></a></label><input class=mainForm type=text name=field_2 id=field_2 size='20' value=''></li>
<li class="mainForm" id="fieldBox_3">
<label class="formFieldQuestion">Contact Number * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Phone Number here </span></a></label><input class=mainForm type=text name=field_3 id=field_3 size='20' value=''></li>
<li class="mainForm" id="fieldBox_4">
<label class="formFieldQuestion">Email Address * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter Email Address </span></a></label><input class=mainForm type=text name=field_4 id=field_4 size='20' value=''></li>
<input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value='2015'>
<li class="mainForm" id="fieldBox_6">
<label class="formFieldQuestion">Date of Arrival * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please select your date of arrival </span></a></label><select class=mainForm name=field_6 id=field_6><option value=''></option><option value="October 13 (Pre Conference)">October 13 (Pre Conference)</option><option value="October 14 (Day 1)">October 14 (Day 1)</option><option value="October 15 (Day 2)">October 15 (Day 2)</option><option value="October 16 (Final Day)">October 16 (Final Day)</option></select></li>
<li class="mainForm" id="fieldBox_7">
<label class="formFieldQuestion">Enter Your Arrival Time * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please Enter the Time you will be arriving to the airport </span></a></label><input class=mainForm type=text name=field_7 id=field_7 size='20' value=''></li>
<li class="mainForm" id="fieldBox_8">
<label class="formFieldQuestion">Date of Departure * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Enter the date you will be leaving the conference</span></a></label><select class=mainForm name=field_8 id=field_8><option value=''></option><option value="October 13 (Pre Conference)">October 13 (Pre Conference)</option><option value="October 14 (Day 1)">October 14 (Day 1)</option><option value="October 15 (Day 2)">October 15 (Day 2)</option><option value="October 16 (Final Day)">October 16 (Final Day)</option></select></li>
<li class="mainForm" id="fieldBox_9">
<label class="formFieldQuestion">Time of Departure * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Please enter what time you will be departing the conference </span></a></label><input class=mainForm type=text name=field_9 id=field_9 size='20' value=''></li>
<li class="mainForm" id="fieldBox_10">
<label class="formFieldQuestion">Dinner October 14th * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Would you like to attend dinner with INFORM applications staff? </span></a></label><span><input class=mainForm type=checkbox name=field_10[] id=field_10_option_1 value="Yes" /><label class=formFieldOption for="field_10_option_1">Yes </label><input class=mainForm type=checkbox name=field_10[] id=field_10_option_2 value="No " /><label class=formFieldOption for="field_10_option_2">No </label></span></li>
<li class="mainForm" id="fieldBox_11">
<label class="formFieldQuestion">Dinner October 15th * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>Would you like to attend dinner with members of the INFORM staff? </span></a></label><span><input class=mainForm type=checkbox name=field_11[] id=field_11_option_1 value="Yes " /><label class=formFieldOption for="field_11_option_1">Yes </label><input class=mainForm type=checkbox name=field_11[] id=field_11_option_2 value="No " /><label class=formFieldOption for="field_11_option_2">No </label></span></li>
<li class="mainForm" id="fieldBox_12">
<label class="formFieldQuestion">Do You Want To Attend The Comedy Show ? * <a class=info href=#><img src=imgs/tip_small.png border=0><span class=infobox>A comedy show will be held at the Borgata on Wednesday the 14th </span></a></label><span><input class=mainForm type=checkbox name=field_12[] id=field_12_option_1 value="Yes " /><label class=formFieldOption for="field_12_option_1">Yes </label><input class=mainForm type=checkbox name=field_12[] id=field_12_option_2 value="No " /><label class=formFieldOption for="field_12_option_2">No </label></span></li>
<!-- end of this page --->
<!-- page validation -->
<SCRIPT type=text/javascript>
<!--
function validatePage1()
{
retVal = true;
if (validateField('field_1','fieldBox_1','text',1) == false)
retVal=false;
if (validateField('field_2','fieldBox_2','text',1) == false)
retVal=false;
if (validateField('field_3','fieldBox_3','menu',1) == false)
retVal=false;
if(retVal == false)
{
alert('Please correct the errors. Fields marked with an asterisk (*) are required');
return false;
}
return retVal;
}
//-->
</SCRIPT>
<!-- end page validaton -->
<!-- next page buttons --><li class="mainForm">
<input id="saveForm" class="mainForm" type="submit" value="Submit" />
</li>
</form>
<!-- end of form -->
<!-- close the display stuff for this page -->
It is not possible to store an PHP array in a MySQL database (because of it's type), but you can convert it to string and store this. Of course, you can convert this string later back to an array. You should change a database field to type LONGTEXT to store an array in it.
To store an array in text form, you can use serialize:
$arr = serialize($arr); // To save it in DB
$arr = unserialize($arr); // To get array after select
Or use JSON (better readable in database):
$arr = json_encode($arr); // To save it in DB
$arr = json_decode($arr); // To get array after select
Hey guys I just wanted to post the complete code encase anybody else is having trouble. I added the serialize function to my form processing part.
<?php
$where_form_is="http://".$_SERVER['SERVER_NAME'].strrev(strstr(strrev($_SERVER['PHP_SELF']),"/"));
include("config.inc.php");
$link = mysql_connect($db_host,$db_user,$db_pass);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db($db_name,$link);
$query = "INSERT into `".$db_table."` (field_1,field_2,field_3,field_4,field_5,field_6,field_7,field_8,field_9,field_10,field_11,field_12) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . $_POST['field_3'] . "','" . $_POST['field_4'] . "','" . $_POST['field_5'] . "','" . $_POST['field_6'] . "','" . $_POST['field_7'] . "','" . $_POST['field_8'] . "','" . $_POST['field_9'] . "','" . serialize($_POST['field_10']) . "','" .serialize($_POST['field_11']) . "','" .serialize($_POST['field_12']) . "')";
mysql_query($query);
mysql_close($link);
include("confirms.html");
?>
Strangely when you unserialize it. It just outputs the word array again.
Currently i'm doing my final year project about hotel management system. Now I'm stuck on using IF STATEMENT on PHP MYSQL query. I had create column named roomtype and roomprice under reservation table. The case are like this:
If guest selected single on roomtype, it automatically shown the
price on roomprice. Let say the price was 100.
Then if guest selected superior, the price is 200.
And then if deluxe was selected, the price is 300.
Below are my codes to store to database
$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db('hotel_reservation3') or die('Could not select database');
// Store query in variable
$query = "INSERT INTO reservation (user_id,fullname,contactno,passport,roomtype,roomprice,num_of_rooms,dor,dco,bookingdate,length_of_stay)
VALUES
(
'".$_SESSION['user_id']."',
'".$_POST['fullname']."',
'".$_POST['contactno']."',
'".$_POST['passport']."',
'".$_POST['roomtype']."',
'".$_POST['num_of_rooms']."',
'".$_POST['dor']."',
'".$_POST['dco']."',
sysdate(),
DATEDIFF(dco,dor)
)";
// Performing SQL query
$result = mysql_query($query)
or die('Query failed: ' . mysql_error());
//echo "Success inserting record!";
// Closing connection
mysql_close($link);
header("Location:reservation.php?success");
I'm using POST method which comes from a form. Below are partial code of the form
<form action="" method="post">
<ul>
<li>
Full name*: <br>
<input type="text" name="fullname">
</li>
<li>
Contact No.: <br>
<input type="text" name="contactno">
</li>
<li>
IC/Passport*: <br>
<input type="text" name="passport">
</li>
<li>
Room Type*: <br>
<select name="roomtype" id="roomtype">
<option value="Single">Single</option>
<option value="Superior">Superior</option>
<option value="Deluxe">Deluxe</option>
</select>
</li>
<li>
Number of Rooms*:</li>
<input type="text" size="3" name="num_of_rooms">
<br>
<li>
Date of reservation*: <br>
<input type="text" size="12" id="dor" name="dor"/>
</li>
<li>
Check-out Date*: <br>
<input type="text" size="12" id= "dco" name="dco"/>
</li>
<input type="submit" value="Submit">
<input type="reset" value="Clear" >
<li>
<br>
<br>
<br>
<br>
<br>
<br>
</ul>
</form>
Does anyone know the code?
As everyone has mentioned, please protect your SQL from injection.
You should calculate your price in PHP.
if($_POST['roomtype'] == "deluxe"){
$roomprice = 300;
}else if($_POST['roomtype'] == "superior"){
$roomprice = 200;
}else{
$roomprice = 100;
}
// Store query in variable
$query = "INSERT INTO reservation (user_id,fullname,contactno,passport,roomtype,roomprice,num_of_rooms,dor,dco,bookingdate,length_of_stay)
VALUES
(
'".$_SESSION['user_id']."',
'".mysql_real_escape_string($_POST['fullname'])."',
'".mysql_real_escape_string($_POST['contactno'])."',
'".mysql_real_escape_string($_POST['passport'])."',
'".mysql_real_escape_string($_POST['roomtype'])."',
$roomprice,
'".mysql_real_escape_string($_POST['num_of_rooms'])."',
'".mysql_real_escape_string($_POST['dor'])."',
'".mysql_real_escape_string($_POST['dco'])."',
NOW(),
DATEDIFF(dco,dor)
)";
I have seen few posts in SO related to the same scenario as mine but did not find a proper resolution. So am posting question with my problem stuff.
I have an HTML form
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="e_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="date" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
<div id="someElement"></div>
And I have the following to perform my form elements submission to a PHP page-
$(document).ready(function(){
$("#insert").click(function(e) {
e.preventDefault();
alert("am in the Insert function now");
$.ajax({
cache: false,
type: 'POST',
url: 'insert.php',
data: $("#myForm").serialize(),
success: function(d) {
$("#someElement").html(d);
}
});
});
});
Here is my PHP -
<?php
$con=mysqli_connect("localhost","root","root","employee");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name =" ";
$dob =" ";
$gender =" ";
$address =" ";
if(isset($_POST['emp_name'])){ $name = $_POST['emp_name']; }
if(isset($_POST['emp_dob'])){ $dob = $_POST['emp_dob']; }
if(isset($_POST['emp_gender'])){ $gender = $_POST['emp_gender']; }
if(isset($_POST['emp_address'])){ $address = $_POST['emp_address']; }
echo $name;
echo $dob;
echo $gender;
echo $address;
$sql="INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Now what happens is, when I enter some values in my form and click on Submit, action performs well and a new row inserts in the database. But all the rows are empty. They're just empty, not even "NULL".
I tried to echo my field values in the PHP but there is no output there. My "1 Record Added" has come-up well, but no form values appear here.
Kindly help me sorting this out.
Thanks in advance.
$_POST[] references to the name attribute of html-tag, not id.
For example, $_POST['emp_name'] should be $_POST['e_name']
Furthermore, don't encapsulate your variables with single quotes:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
Do this instead:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('" . $name . "', '" . $gender . "', '" . $address . "')";
Or use bind_param() from mysqli ofcourse!
Make the id and name of your input elements same
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="emp_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="emp_dob" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="emp_gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="emp_address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
Otherwise change your $_POST array keys.Because you will get the keys of $_POST array will be the name of input elements.But i recommend you to mak ethe name and id same