I'm having a problem in inserting data to my database. I don't have any clues what's the error.
Here's my index:
<form id="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<button id="sub">Save</button>
</form>
<span id="result"></span>
And here's my insert.php:
include_once('db.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
if(mysql_query("INSERT INTO table_users VALUES('$name', '$username', '$password')")){
echo "Successfully Inserted";
} else {
echo "Insertion Failed";
}
And my db.php:
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('neverstoplearning');
You need to make the HTML form in a valid way like you use form but not a submit button as type submit.
HTML Form
<form id="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"/><br/>
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" id="sub" value="Save" name='submit_form'/>
</form>
Now when you click on he submit button its go for the page insert.php and from there you need to store your the username, name and password.
insert.php
For this part you need to follow some rules, Stay away from SQL Injection, follow what i share as a Note at the bottom. And must use a isset submit for doing all these thing.
if(isset($_POST['submit_form']){
include_once('db.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
// use mysqli_* and the $conn string.
if(mysqli_query($conn, "INSERT INTO table_users VALUES('$name', '$username', '$password')")){
echo "Successfully Inserted";
} else {
echo "Insertion Failed";
}
}
Note:
For the protection of SQL Injection must use mysqli_escape_string,
mysql_real_escape_string, addslashes , md5, hash.
and mysql_* now Deprecated, so start use of mysqli_* or PDO.
Related
I have the tables users and register in my database. I've created a login page which starts a session using the users table, then people fill out a form to insert data into the register table. I've used the following code to insert the data. My code doesn't have errors but the thing is it is not inserted to my table. Please help me. Thanks.
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else { ?>
<html>
<body>
<h2>New users Signup!</h2>
<form action="login.php" method="post">
<input type="text" name = "firstname" placeholder="Firstname"/>
<input type="text" name = "lastname" placeholder="Lastname"/>
<input type="text" name = "address" placeholder="Address"/>
<input type="text" name = "contact" placeholder="Contact"/>
<input type="text" name = "email" placeholder="Email Address"/>
<input type="password" name = "password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name = "submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
} else {
$insert_query = mysql_query("insert into users (users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date) values ('$users_firstname','$users_lastname','$users_address','$users_contact','$users_email','$users_password','$users_date')");
$users_id=mysql_insert_id();
if(mysql_query($insert_query)) {
echo "<script>alert('post published successfuly')</script>";
}
}
}
} ?>
Now try this code:
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = mysql_query("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
$users_id=mysql_insert_id();
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class="bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
I have:
Repositioned your PHP code for inserting to be at the top of the form
changed <form action="login.php" to <form action="" because we are executing from the same page
Your query has already run so removed the if(mysql_query...
Removed the spaces in the form e.g. name = " nameofform" to name="nameofform"
I don't see any reason for having this $users_id=mysql_insert_id();, YOu should use auto-increment for the userID on your database
But since we don't know how you have connected to your database, because also that can be an issue: you can also try this way
<?php
//connect to DB
$hostname_localhost = "localhost"; //hostname if it is not localhost
$database_localhost = "databasename";
$username_localhost = "root"; //the username if it is not root
$password_localhost = "password_if_any"; //if no password leave empty
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
// include("includes/db.php");
if (!isset($_SESSION)) {
session_start();
}
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = sprintf("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
mysql_select_db($database_localhost, $localhost);
$Result = mysql_query($insert_query, $localhost) or die(mysql_error());
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
You should removed the whitespaces in your html-code:
Wrong
<input type="text" name = "firstname" placeholder="Firstname"/>
^^^^^
Correct
<input type="text" name="firstname" placeholder="Firstname"/>
Do not put the variables in single quotes:
$insert_query = mysql_query("INSERT INTO users
(users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date)
VALUES
($users_firstname,$users_lastname,$users_address,$users_contact,$users_email,$users_password,$users_date)");
Update: This was wrong. The whole string is in double-quotes so the OP did correct and my notice was wrong. For information-purposes i will let stand the link to the documentation here.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Read more about single- and double-quotes in the PHP documentation.
Do not double-run the query/perform wrong function-call
$insert_query = mysql_query(".......");
........
if(mysql_query($insert_query)){
echo "<script>alert('post published successfuly')</script>";
}
You already have run the query in the first line. If you want to check if it was successful, you have to use if($insert_query) {}. The call mysql_query($insert_query) is wrong because mysql_query() returns a ressource instead of the sql-query.
Do not use mysql_*() function calls. You mysqli_*() instead.
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
Check your use of session.
You are checking the $_SESSION for user_name and if it is not set, you are redirecting via header("location: login.php").
The problem is, that you are never inserting the user_name into the session, so it will always be not set.
You can set the value via $_SESSION['user_name'] = $_POST['user_name']. Have in mind that you have to set the session before checking the session-value. ;-)
remove action
Try this
<form action="" method="post">
I want to check in the username text field to be typed only letters how can i do it in PHP? Plus in the password area to input both letters and numbers. When I click the Register button it displays Successful Registration although the form is not filled and I also put an else statement to display a message to fill all the fields.
the form
<form action = "register.php" method = "POST">
Username: <input type="text" name="username" > <br /><br/>
Password: <input type="password" name="password"> <br /><br/>
Confirm Password: <input type="password" name="repassword"> <br /><br/>
Type:
<select name="type">
<option value="Choose">Please select..</option>
<?php
$sql=mysql_query("SELECT type FROM type");
while($row=mysql_fetch_array($sql)){
echo "<option value='".$row['type']."'>".$row['type']."</option>";
}
?>
</select><br/><br/>
<input type="submit" value="Register" name="submit">
</form>
the register code
<?php
require('connect.php');
$username=$_POST['username'];
$password=$_POST['password'];
$repass=$_POST['repassword'];
$type=$_POST['type'];
if (isset($_POST['submit'])){
//input only letters in username textfield
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['type'])){
$sql = "INSERT INTO users (username, password, type) VALUES ('$username', '$password', '$type')";
$result = mysql_query($sql);
echo "Successful Registration";
}
if(!$result){
$msg = "User Failed to be Registered.";
}
}
else{
echo "Please fill all the fields.";
}
?>
don't validate the userinput with the isset() function. Instead use !empty().
Because isset() also returns true if the POST variable is an empty string.
Also be careful with your SQL-Query (SQL-Injection), you have to escape the $_POST inputs.
You can use this code
$username = real_escape_string ($_POST['username']);
$password = real_escape_string ($_POST['password']);
$type = real_escape_string($_POST['type']); //if type is int, use intval() to escape
BTW: you don't validate the password against the repassword.
I've been trying to update a MYSQL table in PHP but it doesn't seem to be working. I tweak the code and sometimes it says it has updated, when it hasn't and other times it says it didn't work. If anybody could have a look at my code and tell me if they can see anything wrong that would be much appreciated.
Form:
<form method="post" action="update.php" name="update" id="update">
<input type="text" name="username" placeholder="Username" id="regUsername" value="<?php echo $row['username'] ?>" /><br><br>
<input type="password" name="password" placeholder="Password" id="regPassword" value="<?php echo $row['password'] ?>" /><br><br>
<input type="email" name="email" placeholder="Email Address" id="regEmail" value="<?php echo $row['email'] ?>" /><br><br>
<p id="FillInFields"></p>
<input type="submit" value="submit"/><br>
</form>
Update.php
<?php
$linkme = mysql_connect("*******","******","******");
if (!$linkme)
die ("Could not connect to database");
mysql_select_db("*******", $linkme);
$username = mysql_real_escape_string($_REQUEST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
$email = mysql_real_escape_string($_POST["email"]);
$edit_id = $_POST['edit_id'];
$query = mysql_query(
"UPDATE user
SET username = '$username' ,
password = '$password' ,
email = '$email'
WHERE user_id = '$edit_id'");
mysql_query ($query)
or die ("Sorry but your details were not uploaded.");
echo ("Your details didn't update");
mysql_close($linkme);
?>
edit_id is the session id that is on the form page: and the session has been started inside all pages using sessions.
$edit_id = $_SESSION['edit_id'];
Thank you
Comment to answer to close the question since it did work for the OP.
Try something like:
<input type="hidden" name="edit_id" value="<?php echo $row['id_row'] ?>">
['id_row'] being an example of the said row, since you're iterating over some type of fetching of rows from DB.
Since you're using sessions, you'll need to assign that POST array to a sessions array after.
Sidenote about the use of the deprecated MySQL library you are using:
Look into using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
is your variable $edit_id missing in the form file?
<form method="post" action="update.php" name="update" id="update">
<input type="text" name="username" placeholder="Username" id="regUsername" value="<?php echo $row['username'] ?>" /><br><br>
<input type="password" name="password" placeholder="Password" id="regPassword" value="<?php echo $row['password'] ?>" /><br><br>
<input type="email" name="email" placeholder="Email Address" id="regEmail" value="<?php echo $row['email'] ?>" /><br><br>
You must to set an input (usualy of type hidden) to put the key id. In your case, the $edit_id
There are couple of things I've noticed.
To debug your sql query, seperate your sql query into a var
echo $query = "UPDATE user SET username = '$username', password = '$password', email = '$email' WHERE user_id = '$edit_id'";
$query = mysql_query($query); //echo the $query in update.php and
//run the actual query in a sql dialog
//if that doesn't work, then there's
//something definitely wrong with your
//query.
mysql_query ($query)
or die ("Sorry but your details were not uploaded.");
echo ("Your details didn't update"); //you have an echo statement in the
//middle of the script in an area
//without in a conditional loop, it
//will echo this error message even
//if the query committed
//successfully
You're also missing $edit_id. You can have a hidden field in your form as
<input type="hidden" name="edit_id" value="edit_id_val">
You also don't need to put single ticks in your query around the edit_id field value because its an integer.
<?php
$linkme = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die('could not connect because of '.mysqli_error())
$username = mysqli_real_escape_string($linkme, $_REQUEST["username"]);
$password = mysqli_real_escape_string($linkme, $_POST["password"]);
$email = mysqli_real_escape_string($linkme, $_POST["email"]);
$edit_id = mysqli_real_escape_string($linkme, $_POST['edit_id']);
$q = "UPDATE user SET
username = '$username',
password = SHA1('$password'),
email = '$email'
WHERE user_id = '$edit_id'";
$r = mysqli_query($linkme, $q);
if($r){
echo 'success';
}else{
echo '<p>'.$q.'</p>';
echo '<p>'.mysqli_error($linkme).'</p>';
}
?>
you should encrypt the password to using SHA1 or MD5
also you are missing the edit_id
<?php
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$result = mysql_query($con,'SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"');
if(mysql_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysql_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
if($query){
echo "data are inserted succesfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
HTML form
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
Trying to check whether username or email exist in database if yes alert user if no insert values to db. The code doesn't work for me. no error no echo no insertion. any solution?
You have no field with name register
Regarding this
if (isset($_POST['register'])) {
It will never evaluate to true.
<input type="submit" value="Register" class="button" />
needs name attribute name="register"
In addition:
http://php.net/mysql_query
You have wrong order of arguments. However, using mysql_* is highly NOT encouraged. It is an obsolette database API with a lot of vulnerabilities. Switch to mysqli or PDO instead
your first check isset($_POST['register']) is always false because there is no input in your form with the name="register"
and also you chould fix your query , $con should be the second parametre.
and keep in mind that your code is highly vulnerable don't publish this on a server except of your localhost
Try this:-
$result = mysql_query('SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"',$con);
mysql_query
as you are using mysql_query, the link identifier should be second paramater
$result = mysql_query('SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"', $con);
You are over complicating yourself...
First of all, to check the user, just do this when form submits:
var_dump(mysql_num_rows(mysql_query("select bla bla where username=`{$_GET['username']}`")));
//by bla bla i mean primary key, don't select *, affects performance.
Also, please see this, you have an error in your syntax... take a look at the right parameters for mysql_query
http://ro1.php.net/mysql_query
After you set your queries and do the above test and figure out if its good or not, you can cut the 3-4 lines you have above in 1 if line like this
if(mysql_num_rows(mysql_query("select bla bla where username=`{$_GET['username']}`"))) { //code here
}
Try Without $con in INSERT query
$query = mysql_query("INSERT INTO company_profile
(
user_name, password,
company_name, email,
phone, country,
activation_string
)
VALUES
(
'$uname', '$password',
'$name', '$email',
'', '',
''
)");
You need to specify the name to your input field and check for that:-
<input type="submit" name="register" value="register">
OR
<button type="submit" name="register">Register</buton>
This code I wrote is not working for an unknown reason. PHP does not report any errors or warnings.
<html>
<head>
<title>PHP Blog</title>
</head>
<body>
<?php
require 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if(isset($_POST['username']) and isset($_POST['password']))
{
$pass = "test";
$user = "test";
if($_POST['username'] == "test" and $_POST['password'] == "test")
{
echo <<<_END
<form action="post.php" method="post"><pre>
Title: <input type="text" name="title">
Post: <textarea rows="5" cols="64" name="post">
</textarea>
<input type="submit" value="Submit">
</pre></form>
_END;
if(isset($_POST['title']) and isset($_POST['post']))
{
$title = $_POST['title'];
$post = $_POST['post'];
$query = "INSERT INTO blog(title,post) VALUES('$title', '$post')";
mysql_query($query);
echo 'Succesfully posted..';
echo 'Click here';
}
}
else
{
echo "Wrong Password!";
}
}
?>
Everything works until I set variables $_POST['title'] and $_POST['post'] by clicking the button. When I do that I just get a blank page.
If the code that you have provided is post.php, this is the problem:
When you press the Submit button, the post.php only receives $_POST['title'] and $_POST['post'] from the form.
Making the $_POST['username'] and $_POST['password'] null/empty. Therefore returning FALSE for the if statement, and producing a blank page.
There are many ways to fix this, depending on your implementation.
You can pass the username and password value from the form. You can use input type hidden or text if you like.
<input type="hidden" name="username"><input type="hidden" name="password">
Use $_POST['title'] and $_POST['post'] inside the isset() instead of $_POST['username'] and $_POST['password']
And many more..
Because your form should be:
echo <<<_END
<form action="post.php" method="post"><pre>
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Title: <input type="text" name="title">
Post: <textarea rows="5" cols="64" name="post">
</textarea>
<input type="submit" value="Submit">
</pre></form>
_END;
you lose your $_POST['username'] and $_POST['password'] and no test is echoed because you don't have an else for:
if(isset($_POST['username']) and isset($_POST['password']))
or you can save your login info in a session and use them without making the user eneter again his user and password.
You have to echo the login form right after the body tag.
IF not, you will always get a blank page, because your username and password will always be blank.