Php form submission-Error - php

<?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>

Related

Dynamic insert into with multiple values

This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";

Why does my user registration form not work properly?

I am trying to create a user registration form using php and mysql. When I try to hit the submit button no new record is added to my database. The database is functional and has worked with other forms.
HTML/FORM
<?php
include 'header.php';
?>
<section>
<div class="form">
<form action="signup.php" method="post">
<h1> Sign Up!</h1>
<p>First name:
<input type="text" name="fName" maxlength="15" required pattern="^[a-zA-Z]{3,20}$" placeholder="Enter Name" />
</p>
<p>Last name:
<input type="text" name="lName" maxlength="15" pattern="^[a-zA-Z]{3,20}$" required placeholder="Enter Last Name" />
</p>
<p>Email:
<input type="email" name="email" maxlength="40" required placeholder="Enter Email" />
</p>
<p>Username:
<input type="text" name="username" maxlength="20" ^[A-Za-z0-9_]{1,15}$ required placeholder="Enter Username" />
</p>
<p>Password:
<input type="password" name="password" maxlength="20" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required placeholder="Enter Password" />
</p>
<p>Re-type Password:
<input type="password" name="password2" maxlength="20" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required placeholder="Re-type Password" />
</p>
<p>
<button type="submit" name="signupbutton"> Sign up </button>
</p>
</form>
</div>
</section>
<div class="footerspecial">
<?php
include 'footer.php';
?>
</div>
PHP/SQL
<?php
//have they submitted at least once?
if(isset($POST['$password2'])){
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
//do the passwords NOT match?
if ($password !== $password2) {//do string comparison here
echo'<h2>Error: passwrods don\'t match!</h2>';
require ('registerform.php');
}
else {
//does the username already exist?
$sql = mysql_query("SELECT * FROM users WHERE username=='$username'");
if ($results=$con->query($sql)){
echo'<h2>Error: username is already taken</h2>';
require ('registerform.php');
}
else {
$sql = mysql_query("SELECT * FROM users WHERE email=='$email'");
if ($results=$con->query($sql)){
echo'<h2>Error: email already used</h2>';
require ('registerform.php');
}
else {
// If the values are posted, insert them into the database.
$sql= "INSERT INTO users (fName, lName, email, username, password, password2) VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
if (!$con->query($sql)){
echo 'Error: coulndt do suff';
}
else {
echo 'Account made';
}//ENDS SUCCESSFUL INSURT
}//ENDS EMAIL VALIDATION
}//ENDS THE USERNAME VALIDATION
}//END PASSWORD VALIDATION
}
?>
Picture of the form don't really know if its helpful but ya'know
https://gyazo.com/418b86ecb5090604a1f229e1e94fe3bf
I'm guessing here that your database doesn't have a password2 column (seems kind of pointless to have) so trying to insert into it will give an error.
You should read about MySQLi error reporting
Also add error_reporting(-1); at the start of your PHP file to show PHP errors.
P.S. your code is vulnerable to SQL injection, you should use prepared statements to be safe from this.
Could have multiple problems first you do not have the single quotes around $password2. This could be leading to a failed insert.
VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
Also I would echo the sql errors out as you are not doing. you can do this easily. Test the if statement for a true not a false
if ($con->query($sql)){
//if true then runs your code;
}
else {
echo "Error: " . $sql . "<br>" . $con->error; // This will echo out any sql errors you may have
}

Trying to update MYSQL table in PHP

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

I'm throwing and error using mysqli prepared statements on an insert into my DB

Based on an earlier post I'm trying to learn prepared statements to sanitize everything properly.
Here's my form:
<form name="login" action="regi.php" method="post" accept-charset="utf-8">
<label for="username">Username: </label><br />
<input type="username" name="username" placeholder="Handle" required><br />
<input type="hidden" name="sign_up_date" value="<?php echo $_POST['sign_up_date'] ?>">
<label for="usermail">Email: </label><br />
<input type="email" name="usermail" placeholder="yourname#email.com" required><br />
<label for="password">Password: </label><br />
<input type="password" name="password" placeholder="password" required><br />
<input type="submit" value="Login">
</form>
Here's the regi.php page:
include("mysql_connect.php");
include("classes/insert.php");
if (!mysqli_query($mysqli,$stmt))
{
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
mysqli_close($mysqli);
Here is my insert.php page:
$user = $_POST['username'];
$email = $_POST['usermail'];
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ssd', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . "row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
}
Here is my error message:
Localhost via UNIX socket 0row(s) insertedError:
I assume i'm doing something wrong on my insert.php page?
Any help would be greatly appreciated. Thank you.
you could write your query as a stored procedure ... this way the actual query is stored in the db and not in your php file.
also, based on what you have right now it does not look like you are inserting the correct values into the right columns in your table
here is the stored procedure approach
// update your php files so that the following variables read
$cmd = call `people`.`procedurename` (?,?)";
$stmt->bind_param($user, $email );
log into mysql and create a stored procedure with this code
DELIMITER $$
CREATE PROCEDURE `people`.`procedurename` (
IN username VARCHAR(50),
IN email VARCHAR(50)
)
BEGIN
INSERT INTO people (username, email, sign_up_date) VALUES (username, email, NOW());
END
$$
good luck :)

Trying to write to a MySQL database with a PHP form

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Categories