I have the code below:
<html><body>
<?php
$con = mysql_connect("localhost","will","blahblah");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("blahblah", $con);
$sql="INSERT INTO links (link, notes, username)
VALUES
('$_POST[link]','$_POST[notes]','$_POST[username]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 link added";
mysql_close($con)
?>
</body></html>
It should insert a link and notes and a username into my database but it doesn't. I am clueless as to why and would appreciate some help with it! It is getting these values from the form below:
<div id="stylized" class="myform">
<form id="form" name="form" method="post" action="user.php">
<label>Username
<span class="small">Enter Your Username</span>
</label>
<input type="text" name="name" id="username" />
<label>Link
<span class="small">Paste Your Link</span>
</label>
<input type="text" name="email" id="link" />
<label>Notes
<span class="small">Add Some Notes</span>
</label>
<input type="text" name="password" id="notes" />
<button type="submit"></button>
<div class="spacer"></div>
</form>
</div>
Thanks!
I see at least three problems, with your code :
First, when injecting strings into an SQL query, you must escape it, using mysql_real_escape_string() :
$link = mysql_real_escape_string($_POST['link']);
$notes = mysql_real_escape_string($_POST['notes']);
$username = mysql_real_escape_string($_POST['username']);
$sql="INSERT INTO links (link, notes, username)
VALUES ('$link','$notes','$username')";
Third, in your PHP code, you must use the name attribute of your input fields -- and not their id attributes.
Considering your HTML code looks like this :
<input type="text" name="name" id="username" />
<input type="text" name="email" id="link" />
<input type="text" name="password" id="notes" />
You should work with :
$_POST['name'], and not $_POST['username']
$_POST['email'], and not $_POST['link']
$_POST['password'], and not $_POST['notes']
Note : using a name and an id that are that different leads to troubles ;-)
So, to summarize, your code should look a bit more like this :
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$name = mysql_real_escape_string($_POST['name']);
$sql="INSERT INTO links (link, notes, username)
VALUES ('$email','$password','$name')";
Note : you should use the same names for the input fields, and the fields in the table -- it would make your code easier to understand.
Replace it :
$sql="INSERT INTO links (link, notes, username)
VALUES
('$_POST[link]','$_POST[notes]','$_POST[username]')";
with:
$sql="INSERT INTO links (link, notes, username)
VALUES
('". mysql_escape_string($_POST['name']) ."','".
mysql_escape_string($_POST['email']) ."','".
mysql_escape_string($_POST['password']) ."')";
Note that POST variables you're trying to use in Your query are completely different from those on your form
The indexes of POST variables must match the names of the form items.
So either write:
<input type="text" name="link" id="link" /> or use $_POST[email]
Adapt for the other variables.
id attributes are meaningless when submitting the form. You probably want to swap the name and id attributes.
Currently, $_POST['name'], $_POST['email'] and $_POST['password'] are being submitted instead of $_POST['username'], $_POST['link'] and $_POST['notes'].
Your code is also vulnerable to SQL injection.
The items in $_POST are indexed by name attribute, not by id.
Related
Updated
This is the whole code.
Still i do not have a value in the text field "user" but i have in all others.
I print the values before adding them to the db ( deleted it from the original code already - i have all values instead the one in the user field )
This is a testing environment.
What I have issues with, is the following:
the field "user" is a field containing text and for some reason the $_post do not contain it.
all the others variables from the number fields are carried in $_post[field_name], but not the text field.
Do you have any idea how to fix this?
I tried with using html special char, but still no results.
Thanks in advance for the help !
this is the html
<html><head><title>MySQL Table Viewer</title></head><body>
<form action="submit.php" method="POST">
Day: <input type="number" name="day"/> Month: <input type="number" name="mont"/> Year: <input type="number" name="year"/>
<br> <br>
Start Hour:<br>
<input type="number" name="shour"/>
<br>
End Hour:<br>
<input type="number" name="ehour"/>
Agent: <input type="text" name="user" value=""/>
<input type="submit" class="button" name="submit" value="submit" />
</form>
</body></html>
this is the php
<html>
<body>
<?php
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$con = mysql_connect("localhost","root","samokow");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("reservations", $con);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user)
VALUES ('$day', '$mont','$year', '$shour','$ehour','$user')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Booking done." ;
mysql_close($con);
?>
</body>
</html>
You're quoting your $_POST[] you should do it like this:
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES (".mysql_real_escape_string($_POST['day']).", ".mysql_real_escape_string($_POST['mont']).",".mysql_real_escape_string($_POST['year']).", ".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['shour']).",".mysql_real_escape_string($_POST['user'])."))";
this should work.
You don't have to qoute variables such as post in your query but instead use mysql_real_escape_string
EDIT:
Your year tag is invalid you end it with an $, and in your query you're getting shour 2 times
`Year: <input type="number" name"year"$`
Should be: Year: <input type="number" name="year">
$_POST[day]', '$_POST[mont]','$_POST[year]', '$_POST[shour]','$_POST[shour]'
shouldn't the second shour be ehour?
I hope this code is for testing purposes only?
Paste all of this in the same page!
<form method="POST">
Day: <input type="number" name="day" />
Month: <input type="number" name="mont" />
Year: <input type="number" name="year" />
Start Hour: <input type="number" name="shour" />
End Hour: <input type="number" name="ehour" />
Agent: <input type="text" name="user" />
<input type="submit" class="button" name="submit" value="submit" />
</form>
Before including the $_POST values in your database, you should use mysql_real_escape_string() Just like the others said.
ALSO, you will have to use mysqli or PDO because mysql_query() is deprecated.
if(isset($_POST['submit'])){
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (`day`, `mont`, `year`, `shour`, `ehour`, `user`) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
}
I would recommend to provide a valueparameter in the input tag as well:
.... Agent: <input type="text" name="user" value="">
some browsers are picky about that (MS IE ...?)
Try this :
$day = mysql_real_escape_string($_POST['day']);
$mont= mysql_real_escape_string($_POST['mont']);
$year = mysql_real_escape_string($_POST['year']);
$shour = mysql_real_escape_string($_POST['shour']);
$ehour = mysql_real_escape_string($_POST['ehour']);
$user = mysql_real_escape_string($_POST['user']);
$sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
you need to put the row in quotes like this:
$_POST['user']
I am trying to generate a script to insert comments on a blog to 'comments' table in MySsl database
<form action="insertcomment.php" method="post">
<p class ="ctitle">Leave a Comment:</p>
<p>
<label for="name"><b>PostID:</b></label>
<input type="text" id="postid" name="name" maxlength="4" /> <br/>
<label for="name"><b>Name:</b></label>
<input type="text" id="name" name="name" maxlength="25" /> <br/>
<label for="email"><b>Email:</b></label>
<input type="text" id="email" name="email" maxlength="50" /> <br/>
<label for="website"><b>Website:</b></label>
<input type="text" id="website" name="website" maxlength="25" /> <br/>
<label for="content"><b>Comment:</b></label>
<textarea id="content" name="content" cols="10" rows="4" maxlength="800"></textarea> <br/>
<input type="submit" value="Submit Comment" name="submit_comment" /> <br/>
</p>
</form>
and my PHP script is as follows:
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if(isset($_POST['submit'])) {
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ('$_POST[postid]','$_POST[name]', '$_POST[email]', '$_POST[website]', '$_POST[content]')";
mysql_query($sSql);
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
But I was not able to insert my comment into database. my 'comments' table has comment_id,post_id,name,email,website,content,date_published fields. comment_id is the primary key. It has the option auto_increment. and date_published by default gives current time stamp. I was not able to figure out what my error is. Any thoughts would be appreciated.
Thank You!
You should use mysqli or PDO, but if you need to use the about-to-be depreciated mysql plugin:
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if(isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
$$key = mysql_real_escape_string($value); // You should always sanitize user inputs.
}
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ($postid,'$name', '$email', '$website', '$content')"; // No quotes around $postid because I'm assuming post_id column is an int type.
mysql_query($sSql);
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
Notice the single quotes have been removed from $postid. This is because if table post_id is an int type, then you should not have quotes around the integer value.
Also, notice I've used the mysql_real_escape_string() function to clean your inputs. You should never ever quote direct user-inputted variables into SQL. It's very dangerous as users can use SQL injection attacks to gain access to your DB where they shouldn't or even possibly drop tables.
Still, I recommend converting to mysqli or PDO if at all possible, because the mysql plugin is about to be depreciated.
How do you create a javascript button to take the information from the form to the php sql:
<form>
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
?php
$name = $_GET['name'];
$number = $_GET['number'];
$location = $_GET['location'];
$con = mysql_connect(".....",".....",".....");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
("chanh", $con);
$sql ="INSERT INTO book (name, number, location,timestamp)
VALUES ('$name', '$number','$location',NOW())";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added"
mysql_close($con);
?>
Any help would be appreciated as I am just a rookie! Thanks
You just need to specify where you form will be submitted
<form action="submit.php" method="get">
<input type="text" placeholder="Name" name="name" class="name" /></br>
<input type="text" placeholder="Phone Number" name="number" class="number"/></br>
<input type="text" placeholder="Location " name="location" class="location"/></br>
<input type="submit" value="Add Booking" />
</form>
Javascript is only needed here if you want to perform some sort of validation
NOTE
Avoid adding variables directly to your query, you will be vulnerable to SQL injection.
Here is what you can do:
$con = mysql_connect(".....",".....",".....");
$name = mysql_real_escape_string($_GET['name']);
$number = mysql_real_escape_string($_GET['number']);
$location = mysql_real_escape_string($_GET['location']);
create an , then set that when the button is clicked, the form is submitted. ie
but = document.getElementById('clickButton');
formToSubmit = document.getElementById('myForm');
but.onclick = function(){
formToSubmit.submit();
};
You don't need JavaScript to submit a form. It looks like you're just missing the < from <?php for now.
You could explicitly specify the action and method on the form HTML element, but if you don't it's a GET request and it will submit to the current URL (Web address).
Really, if you're doing something other than fetching data (like a search), your form should be using a HTTP POST, not a GET. For more understanding of why this kind of thing matters, see What should every programmer know about web development. However, that is a very big topic!
You just need to postback the form, in other words, set an action on the form as in:
<form id="mainForm" action="process.php" method="post">..
And add an onclick handler on the button as follows:
<input type="submit" value="Add Booking" onclick="javascript:document.getElementById('mainForm').submit();" />
However, not that I set the method to post; this will require your PHP code to change to:
$name = $_POST['name'];
$number = $_POST['number'];
$location = $_POST['location'];
Using POST in this case may not be necessary but you need to be aware that using GET will encode the form parameters in the URL as in process.php?name=value&numner=value... and some of this information may be sensitive and therefore, desirable to be submitted to the server in the body of the HTTP request as opposed to transmitted encoded in the URL.
I am php beginner and I am trying to make e-commerce by using php.
I am trying to make register form and I want to save these data into mysql server.
The coding looks like OK, but the data did not store in mysql server.
Could you give your answer for this? php language is first time that it is what I am struggled. Please give some advice. Thanks.
--registerForm.php--
<h4>Create a new account</h4>
<div class="box">
<form action="register.php" method="post">
<p>User ID: <input type="text" name="userId" size="30"/>*</p>
<p>Password: <input type="password" name="password" size="30"/>*</p>
<p>Retype Password: <input type="password" name="repassword" size="30"/>*</p>
<p>First Name: <input type="text" name="firstName" size="30"/>*</p>
<p>Last Name: <input type="text" name="lastName" size="30"/>*</p>
<p>Your Address (*):</p>
<p> <textarea name="address" rows="5" cols="30"></textarea></p>
<p>Phone: <input type="text" name="phone" size="20"/>*</p>
<p>E-mail: <input type="text" name="email" size="21"/>*</p>
<p><input type="submit" value="Create Account"/></p>
</form>
</div>
--register.php--
<?php
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_GET["userId"]==$_GET["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
--sql_connection.php--
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "**MY_PASS**";
$db_name = "**MY_DB**";
#mysql_connect("$db_host", "$db_username", "$db_pass", "$db_name") or die("connection is fail.");
#mysql_select_db("$db_name") or die("database does not exsist.");
echo "Successfully connection!!";
?>
if($_GET["userId"]==$_GET["repassword"])
Why do you compare userid to a retype pssword field?
I think it should be :
if($_GET["password"]==$_GET["repassword"])
Also make sure you escape strings to prevent SQL Injection Attacks.
http://php.net/manual/en/function.mysql-real-escape-string.php
And Like Paul said, to correctly retrieve the data use $_POST
Few things. Your $_GET and $_POST are mixed up. and NEVER post your db_pass and uername in public. Also, you're suppressing errors using #. don't do that.
i.e.
if($_GET["userId"]==$_GET["repassword"]){
should be
if($_POST["userId"]==$_POST["repassword"]){
and changes all these to $_POST
Your code:
$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')
Should be:
$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')"
As your form method defined is POST so use $_POST to get values after submit instead of $_GET
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_POST["userId"]==$_POST["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
Values are not quoted properly. You should quote then before insert.
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('".$_POST[userId]."','".$_POST[password]."','".$_POST[firstName]."','".$_POST[lastName]."','".$_POST[address]."','".$_POST[phone]."','".$_POST[email]."')")
I think that what you are trying to do is:
if($_GET["password"]==$_GET["repassword"]) {
I have a page which basically allows an admin user to create manager user types (basically a register function. So when the values are submitted, they are stored into the DB, very very basic stuff. However, I have a hidden variable type..reasons are I have 3 different user levels and I have declared they identification as an integer (e.g. 7 = manager, 8 =user etc.)
Can someone help me out with how to correctly pass this hidden value so it stores in the database...
Here is my form:
<form id="userreg" name="userreg" method="post" action="adduser-process.php">
<label>Full Name:</label> <input name="fullname" size="40" id="fullname" value="<?php if (isset($_POST['fullname'])); ?>"/>
<br />
<label>Username:</label> <input name="username" size="40" id="username" value="<?php if (isset($_POST['username'])); ?>"/> <br />
<label>Password:</label> <input name="password" size="40" id="password" value="<?php if (isset($_POST['password'])); ?>"/> <br />
<label>Email Address:</label> <input name="emailaddress" size="40" id="emailaddress" value="<?php if (isset($_POST['emailaddress'])); ?>"/>
<br />
<input name="userlevel" type="hidden" size="1" id="userlevel" value="<?php $_POST[5]; ?>" /> <br />
<input value="Add User" class="addbtn" type="submit" />
</form></div>
Next, here is the script that runs the query:
<?php
require_once "config.php";
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$password = $_POST['password'];
$emailaddress = $_POST['emailaddress'];
$userlevel = $_POST[5];
$sql = "INSERT INTO users_tb VALUES('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".$emailaddress."','".$userlevel."')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: administratorfrontview.php");
exit();
?>
I'm basically trying to pass the hidden typem with a constant value of '5' just for this form, as it will not be changed...also while im here, for some reason, the 'fullname' is not stored in the DB either!!?? WTH?? all other fields are processed fine. Any help is much appreciated! Thank you.
Two things. One, $userlevel should equal $_POST['userlevel'] not 5 as POST data isn't always in that order. Two, your insert statement should be preceded with the column names (to prevent any data from going in the wrong order).
$sql = "INSERT INFO users_tb (id, name, username, password, email, userlevel) ".
"('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".
$emailaddress."','".$userlevel."')";
Your PHP for outputting the value is wrong. Use:
<?= $_POST[5]; ?>
or
<?php echo $_POST[5]; ?>