I am trying to make a form using html and php to update mysql database. the database updates (autoincrements) the keys, but it does not add any of the strings to the values. i have searched people with similar problems but because their codes are different than mine I cannot understand it (i am a noob with php and mysql) I think my problem is in the way that i use the html to get the values but I could be wrong
<form action=submitform.php method=GET>
Name:<input type="text" name="cuName" size=20 maxlength=20><br>
Password:<input type="password" name="password" size=20 maxlength=45><br>
Account:<input type="text" name="account" size=20 maxlength=45><br>
Phone:<input type="tel" name="phone" size=10 maxlength=10><br>
Email:<input type="text" name="email" size=20 maxlength=45><br>
<input type=submit>
</form>
and my php is
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')");
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
thanks in advance for any help
Your code is relying on REGISTER_GLOBALS to be turned on; it is usually turned off for security reasons.
You should replace $cuName with $_GET['cuName'] to get the values that are sent from the form.
Additionally, you should escape any value that is going to the database otherwise you may be exposing yourself to an SQL injection vulnerability.
Cleaning up your code for both these scenarios, results in something like this:
<?php
if (!mysql_connect(localhost, myUsername, "myPassword")) {
print 'There was an error connecting to the database'.mysql_error();
exit();
}
if (!mysql_select_db(myDatabaseName)) {
print 'Could not select db. The error was: '.mysql_error();
exit();
}
$query = "INSERT INTO Customer (`cuName`, `password`, `account`,`phone`,`email`)";
$query .= "VALUES (";
$query .= "'".mysql_real_escape_string($_GET['cuName'])."','";
$query .= mysql_real_escape_string($_GET['password'])."','";
$query .= mysql_real_escape_string($_GET['phone'])."','";
$query .= mysql_real_escape_string($_GET['email'])."'";
if (!mysql_query($query)) {
print 'There was an error inserting '.$query.'. Error was '.mysql_error();
} else {
echo $_GET['cuName']." thank you for reserving!";
}
print $_GET['cuName'];
?>
I also added some error checking. You should always check results of functions that rely on external systems (such as databases) because you never know what is the status of the database (it could be down, not working, etc.) So you should always check and print any error messages.
You don't define any of your GET values anywhere. $cuName, etc are not defined.
Each value needs to be associated to the $_GET. IE,
$cuName = $_GET['cuName']
But you also need to make sure you don't insert data that hasn't been cleaned to prevent SQL injection. An example of this is:
$cuName = mysql_real_escape_string($_GET['cuName']);
So, try this:
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
//Define Variables
$cuName = mysql_real_escape_string($_GET['cuName']);
$password = mysql_real_escape_string($_GET['password']);
$account = mysql_real_escape_string($_GET['account']);
$phone = mysql_real_escape_string($_GET['phone']);
$email = mysql_real_escape_string($_GET['email']);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')") or die (mysql_error());
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
Better to use:
$cuname = $_GET['cuname'];
like this....
Because your form method is on "GET",and my advise is to POST data than GET.
Related
I made a simple form with two variables which should be sent to database after SUBMITing them. However even thought there is no bug reports, the database is still empty after submit. Where Can I look for mistake?
I already tried multiple ' or " or '", none of these worked. I can with no problem SELECT data from fdatabase so the connection is established.
$total = $_POST['kwota'];
$way = $_POST['sposob'];
echo $total . "<BR>" . $way;
$sql = "INSERT INTO payments (Total, Way) VALUES ('$kwota', '$sposob');";
mysqli_query($conn, $sql);
header("Location: ../index.php?Payment=success");
<form action="includes/Platnosc.inc.php" method="POST">
<input type="text" name="kwota" placeholder="kwota"><br>
<input type="text" name="sposob" placeholder="sposób"><br>
<button type="submit" name="submit">Dodaj płatność</button>
</form>
You are inserting $_POST array indexes as php variables. Change your query to this
$sql = "INSERT INTO payments (Total, Way) VALUES ('$total', '$way')";
However, I suggest you to use prepared statements to prevent from sql injections
I'm having an issue with a form I have created (Test purposes only, I am aware it's vulnerable to SQL Injection)
Basically, the form does not insert into the DB, yet it seems to be returning true on the script.
The code is as follows:
form.php
<form action="create.php" method="post">
<p>Username: <input type="text" name="username" />
</p>
<p>Password: <input type="password" name="password" />
</p>
<p><input type="submit" value="Create" name= "cre" />
</p>
</form>
create.php
<?php
session_start();
$dbname = "obsidian";
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
?>
I get the success message, but as I stated, the values do not get inserted into the DB.
Any help would be good.
This defines a query, but does NOT run it:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
The this is NOT "testing" for success. It's simply seeing the variable to true:
if($registerquery = true)
= is assignment, == is for equality testing.
You have to query the database. Try this:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if ($mysqli->query($registerquery))
{
// success.
}
else
{
// failed.
}
Here is the documentation: http://php.net/manual/en/mysqli.query.php
You missed the step where you actually hand the SQL query to the database.
$mysqli->query($registerquery);
has to be run before it will be inserted.
You can also change your if statement to the following
if ($mysqli->query($registerquery))
Also, you're currently using a single =, which is setting $registerquery instead of checking its value.
All you are doing here:
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
if($registerquery = true)
is setting a string and then later setting the string to true. This is always going to return true. There are two problems with this:
You need to execute the SQL statement that you have stored in the string for anything to happen in the database.
You are not really checking the return value ("=="), but rather using "=", which simply sets the variable. A very common mistake.
Additionally, you should probably no longer use the mysqli built in functions, since they will soon be deprecated. I would recommend switching to PDO before moving any further.
Formally, You should do something like this:
if(isset($_POST['cre'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli('localhost','admin1', 'password1','obsidian' ) or die('Failed to connect to DB' . $mysqli->error );
$hashed_password = password_hash($password,PASSWORD_DEFAULT);
$registerquery = "INSERT INTO users (username, hash) VALUES('$username', '$hashed_password')";
$stmt=$mysqli->prepare($registerquery);
if($stmt->execute())
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
$stmt->close();
}
Also, you could call only mysqli_query
if($mysqli->query($registerquery)){
....
}
It would be enough. The first call is better if you need to bind parameters and make several calls to the same query with different values.
Regards.-
Ok, this is just for a school project so it doesn't need incredible security so i just need help with this signup feature for an sql database:
<h1>Signup:</h1><br><form method="post">Username: <input type="text" name="username"><br>Password: <input type="password" name="password"><br>Confirm Password: <input type="password" name="cpassword"><br><input type="submit"></form>
<?php
$user = $_POST['username'];
$pass = crypt($_POST['password'], '$1a');
$cpass = crypt($_POST['cpassword'], '$1a');
if($pass == $cpass) {
$query = "INSERT INTO users (uName, pWord) VALUES ('$user', '$pass')";
}
else
echo "<script type='text/javascript'>alert('Password is different');</script>";
?>
The problem i actually have is i am doing pretty much the same thing with the login and the $_POST method in there is stopping me from being able to do it here, how do i refer to a specific $_POST method?
You forgot to actually execute the query. You're just assigning a string to a variable.
As described in the title, I am running into an SQL injection error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
How do I fix this? Provided below is my php code and html code
PHP:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
else $err[]='Wrong Password To Start With!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML:
<form action="" method="post">
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
</form>
I have it working where a user is able to change/update their password, however, when they click the Change button on the form, they are directed to that error message I posted above, and if they click the refresh button, only then they are redirected back to their profile and the changes have been made. So my main question at hand is, how do I get this to fully work without that mysql error message? Any help would be much appreciated!
A few things wrong here, more than can be put in a comment. I'm sorry, I can't see exactly what your error is, but if you follow point #1, it'll go away.
Don't use the mysql library. It is deprecated, and has been removed (finally!) in PHP 5.5. It is only working for you at the moment, because your version of PHP is out of date. You should either be using PDO or MySQLi. Check out this article for information on PDO: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
Don't put any variable that's not generated in the script you're looking at into your query, this includes SESSION variables. You just need one flaw in your application, and the user can inject data into the SESSION. Treat every variable as dirty. If you know that it isn't - 100% for certain - then treat it as dirty. If you use prepared statements with PDO or MySQLi, this isn't a problem.
You should reference users by their ID, not username. Much faster and safer.
Never ever ever ever store passwords raw or simply encrypted (like with plain md5()) in the database. At the very least, you can encrypt with something like: crypt($password, '$2a$07$sillystring' . sha1($password) . '$') and verify by recrpyting the password and see if it matches. That's a very basic, more secure way of doing it. There are many articles written on password salting that go more in depth and are worth checking out.
Except for what Connor said, you have a serious problem here:
if($row['username'])
{
$querynewpass =
mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
The first inner line already performs the mysql_query and returns a resource, which is assigned to $querynewpass.
You're resending the result (a resource) to another query, as if it was a string containing the SQL command you want to perform.
This is the function's specification:
resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
This is the correct usage of mysql_query (which is deprecated as people mentioned):
if($row['username'])
{
$querynewpass =
"UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
}
This code snippet could help to you
$pass1 = md5(mysql_real_escape_string($_POST['password1']));
$newpass = md5(mysql_real_escape_string($_POST['passwordnew1']));
$username = mysql_real_escape_string($_SESSION['username'])
$query = "SELECT id,username FROM members WHERE username = '$username' AND pass = '$pass1'";
$result = mysql_query($query); //that could also use , mysql_query($query,$yourconnection);
if(mysql_num_rows($result)>0)
{
$updatequery = "UPDATE members SET pass='$newpass' WHERE username='$username'";
$updateresult = mysql_query($updatequery) or die(mysql_error());
}
Please note that mysql library is deprecated in after php ver 5.5.0
HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.