I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>
Related
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
Hey there im currently try to create a page where I can insert some information into my SQL database, this is the php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "film";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$filmtitle = $_POST['filmtitle'];
$filmyear = $_POST['filmyear'];
$filmduration = $_POST['filmduration'];
$filmrating = $_POST['filmrating'];
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When I hit the submit button I get the following error,
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Here is the HTML as well
<html>
<body>
<h1> Insert a new film!</h1>
<form action ="insert-film.php method="post">
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Certificate: <input type="text" name="filmcertificate">
<input type="submit">
</form>
</body>
</html>
There's a few things wrong here.
First
<form action ="insert-film.php method="post">
^ right there.
is missing a quote.
<form action ="insert-film.php" method="post">
Then this: you used ticks instead of quotes for $filmyear and a trailing comma
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
^ right there.
which should read as
('$filmtitle', '$filmyear', '$filmduration', '$filmrating')";
You also seem to be using the wrong array for filmcertificate which should be filmrating.
Certificate: <input type="text" name="filmcertificate"> there is no POST array for it.
$filmtitle = $_POST['filmtitle'];
$filmyear = $_POST['filmyear'];
$filmduration = $_POST['filmduration'];
$filmrating = $_POST['filmrating'];
and
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Certificate: <input type="text" name="filmcertificate">
The last one does not match the $_POST['filmrating'] array.
You probably meant to do:
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Film rating: <input type="text" name="filmrating">
Only you know what that should be. Ajust accordingly.
Once your PHP kicks in after fixing the quote in the action, you would have been thrown an undefined index filmrating in line... notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
You have an extra comma at the end of your sql:
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
should be:
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
($filmtitle', '$filmyear', '$filmduration', '$filmrating')";
Also, make sure you are consistent with your backticks versus single quotes.
Finally, you are exposed to SQL injection attack.
I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}
I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.
I am trying to set up my first PHP site and I really want to do it the right way. I am working on the form located: http://www.bwgblog.com/signup.
I have set up the following form:
<p><form action="/signup/register.php" method="post">
<label for="first_name">First Name</label>
<input type="text" name="first_name" />
<label for="last_name">Last Name</label>
<input type="text" name="last_name" />
<label for="company">Company</label>
<input type="text" name="company" />
<label for="job_title">Job Title</label>
<input type="text" name="job_title" />
<label for="phone">Phone</label>
<input type="text" name="phone" />
<label for="email">Email</label>
<input type="text" name="email" />
<label for="username">Choose a Username</label>
<input type="text" name="username" />
<label for="password">Choose a Password</label>
<input type="text" name="password" />
<label for="confirm_password">Confirm Your Password</label>
<input type="text" name="confirm_password" />
<input type="submit" value="Get Started" />
</form>
And here is my PHP page, register.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","*******","******"); //Replace with your actual MySQL DB Username and Password
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bwgblog", $con); //Replace with your MySQL DB Name
$first_name=mysql_real_escape_string($_POST['first_name']);
$last_name=mysql_real_escape_string($_POST['last_name']);
$company=mysql_real_escape_string($_POST['company']);
$job_title=mysql_real_escape_string($_POST['job_title']);
$phone=mysql_real_escape_string($_POST['phone']);
$email=mysql_real_escape_string($_POST['email']);
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$confirm_password=mysql_real_escape_string($_POST['confirm_password']);
$sql="INSERT INTO members (first_name,last_name,company,job_title,phone,email,username,password,confirm_password) VALUES ('$first_name','$last_name','$company','$job_title','$phone','$email','$username','$password','$confirm_password')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
I am trying to figure out how to add in AJAX such that it gives me two things. 1) The ability for it to check in realtime the username field as that field should be unique, and 2) the ability to have the confirm password field render a green checkmark if it == password field.
I have been looking all day for how to do this and can't get a clear look at it. Here is how the files are laid out:
signup (folder)
-> index.php
-> register.html.php
-> register.php
1) AJAX doesn't require the backend to be anything special - so the simplest solution there may be to have a 'usercheck.php' file that queries the DB for the username passed, then returns some form of true/false. You'll probably want to reply using JSON (this is easy if you have PHP 5 - see json_encode).
Regarding the AJAX frontend you'll find it easiest if you use an existing framework (I've used Mochikit and prototype, both seem fine) of which there are several. This should allow you to load the server's response easily.
If you have the AJAX use GET rather than POST (this is simpler) then you can test the response by just viewing the page with the appropriate query string. In any case using Firebug will allow you to view the calls in realtime.
2) There is no need to have the password check AJAX - that can be done simply using plain JavaScript: simply compare the .value properties of the two inputs.
Agreed with PeterJCLaw on all accounts except the choice of javascript framework. Here is how you could do it with jQuery:
// give the form an ID to use a better selector: ie: $('#myform')
// intercept form submit
$('form').submit(function(){
// check if passwords match; you might want to do more thorough validation
if($('input[name=password]').val()==$('input[name=confirm_password]').val()){
// make ajax post request and store the response in "response" variable
$.post('/signup/register.php', $(this).serialize(), function(response){
// process response here (assume JSON object has boolean property "ok"
if(response.ok==true){
// sweet, it worked!
alert('OK!');
}else{
// handle error
alert('Ooops');
}
}, 'json');
// stop the form from being submitted
return false;
}else{
// for the sake of simplicity
alert('Passwords don't match!);
}
});
Look at Jquery's validate extension.
It will simplify all of this. Checking remote values is simple too.
A relatively recent post on this with example code.
You can upload Jquery to your server, or google code hosts them. Using the google version greatly increases the chance that your customers will have already downloaded it also and can use their cached copy.
$fields = array('first_name','last_name','company','job_title','phone','email','username','password','confirm_password');
$dbfields = array(); $dbdata = array(); $dbfieldq = array(); $types = ''; //Setting Variable
foreach ($fields as $field){ //For Each Field
if (!isset($_POST[$field]){ header('Location: signup.php'); die('Please Fill in all fields, they are required'); } //Missing Field Error -- Doublecheck on serverside
array_push($dbdata, strip_tags($_POST[$field])); //Add Data - MySQLi Prepared Statements don't need to be escaped
array_push($dbfields,$field); //Add a field
array_push($dbfieldq,'?'); //Add a ?
$types += 's'; //Add a field type (string for all of these)
}
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); //Connect
if ($mysqli->connect_error) { //If there is a connect Error
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$names = explode($dbfields); //Explode the Field Names
$questions = explode($dbfieldq); //Explode the ?
$stmt = $mysqli->prepare("INSERT INTO DBName ($names) VALUES ($questions)");
$params = $this->paramValues;
array_unshift($dbdata, implode($this->paramTypes);
call_user_func_array( array( $stmt, 'bind_param' ), $params);
$stmt->bind_param($types, $code, $language, $official, $percent);
$stmt->execute();
$mysqli->close();
A better way to do the php... Use prepared statements and loops to prepare the variables.