my php registration file creates too many entries in the database - php

I have a file named reg.php that extends my registration.php for a login system.
The registration is connected with a mysqli database and I have a manual
increase in user id in php instead of autoincrement in mysqli because I could
not make this work.
When I hit the register button, my code is creating two entries in the db and
I dont know why.
<?php
if(isset($_POST["register_user"])){
header('location: login.php');
}
if(isset($_POST["username"])){
$username = mysqli_real_escape_string($db, $_POST['username']);
}
if(isset($_POST["email"])){
$email = mysqli_real_escape_string($db, $_POST['email']);
}
if(isset($_POST["password"])){
$password = mysqli_real_escape_string($db, $_POST['password']);
}
if(isset($_POST["passwordconfirm"])){
$passwordconfirm = mysqli_real_escape_string($db, $_POST['passwordconfirm']);
}
$idcount = mysqli_num_rows(mysqli_query($db, "SELECT id FROM user"));
$regquery = "INSERT INTO user (id, name, email, password) VALUES ('$idcount', '$username', '$email', '$password')";
mysqli_query($db, $regquery);
?>
all I want is one single entry.

There's nothing in the code, in your question, that could insert two rows in your database. My guess it that you call this script twice, probably because your form has two ways of submitting the same data:
The normal way, with the form action attribute.
Through an event, like onSubmit
You've got to stop the former, if the latter is used. Look at the example in the link for 2. It tells you how to stop the form from submitting as well:
// For this example, don't actually submit the form
event.preventDefault();
So if the onSubmit works, it stops the normal form submission, but if it doesn't work, the form is submitted the normal way.

Related

An issue with displaying post system regarding AJAX usage

So, I have this system where you can make a post. So, how it works is, there is an input field, whatever you type in the input field, and click post, it will send to the database as en entry and get posted. The post will be displayed. However, with my current system, after entering something in the input field, and clicking post, the entry gets sent to the database, but the post doesn't actually display. For it to display, you need to refresh the page again, which it displays then, and two entries go to the database.
I don't want this to happen. Right when the user enters text into the input field and clicks post, the post should display on the go, you shouldn't have to refresh for the post to be displayed, and only one entry should be sent to the database, not two. Now, I also included my database connection and my insert statements, but here is the code to display the post:
<div class="textPost">
<?php
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="textpostFormat">
// all the displayed post content
</div>
<?php
}
}
?>
</div>
Insert Statement (post.php):
<?php
session_start();
// Making Connection To The Database
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";
$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");
// Posting System
if (!empty($_POST['postContent'])) {
$post = $_POST['postContent'];
$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
$stmt = mysqli_stmt_init($connection);
// nested if statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "";
} else {
mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
mysqli_stmt_execute($stmt);
}
} else {
echo "";
}
?>
So, since PHP is a server side language, to make the calls, you would require AJAX to accomplish this problem/situation. The only problem is, I don't know what the AJAX would be. So my question is, for this particular situation, what would the AJAX be? I don't want any tutorials, just the code. Also, I can't try on some AJAX code and ask for help, because I don't even know what it would be in the first place. I don't want to use the PHP approach to solve this problem, I want the AJAX approach, and for that, the AJAX code to solve this situation.
So, please, please spare a few minutes of your time to answer this question. Please. Thanks a lot! I greatly appreciate your help.

Using $_POST in 2 if statements

I'm trying to use one post in 2 different if statements.
What I'm trying to achieve is that I want to insert 3 values in mysql with post.
$action = $_POST['action'];
if($action == "checkCharacterName"){
$username = $_POST['name'];
}
it gets the character name here ^
and then in different action it gets the password:
if($action == "registerUser"){
$password = $_POST['password'];
$qry = $db->prepare ( 'INSERT INTO user_data (id, username, password, gold)
VALUES (null, "'. $username .'","'. $password .'", 500)');
$qry->execute();
but it shows this error:
Undefined variable: username
The posts are sending through swf, so I'm not able to change it cause its not mine swf
You work in PHP. This is a STATELESS langage. It means each time you post data, the whole script is executed but NO VARIABLES are saved. There is two ways to bypass this.
Adding state : Save the $username in the $_SESSION object or in the $_COOKIE object.
Working stateless : Do your request in only ONE POST. (Sending the username and the password at same time.
More informations to maintain a state here

Entries to the database automatically after reload the web site

( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.

Why is my SELECT code not working?

I have a program that moves registration data from one datatable to another (think login activation page from temp to permanent after email confirmation). I'm not the best at Mysql yet, still learning so it might be a stupid question. I've checked all over stackoverflow and it looks like I'm doing it correctly.
For some reason my select call is not working. Here is a bit of my code:
$username = mysqli_query($dbc,"SELECT 'username' FROM 'temp_users' WHERE 'activation'= '$key'");
$password = mysqli_query($dbc,"SELECT 'password' FROM 'temp_users' WHERE 'activation'= '$key'");
// Add row to database
mysqli_query($dbc,"INSERT INTO users (username, password, salt', 'email') VALUES ('$username', '$password_hash', '$salt', '$email')");
echo $username, $password, $email, mysqli_affected_rows($dbc), $key;
// Print a customized message:
if (mysqli_affected_rows($dbc) == 1) //if update query was successfull
{
echo '<div>Your account is now active. You may now Log in</div>';
} else {
echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
I threw in the echo my variables so I could see what was going on. At this point, $key is correct, $email is correct from earlier code, mysqli_affected_rows($dbc) is giving me a -1 (which means error). $username and $password are blank variables, so clearly I am doing the SELECT incorrectly.
Any thoughts or help?
Remove '(Single quotes) use (backticks) = ``
SELECT `username` FROM `temp_users` WHERE `activation`= '$key'

What is wrong with this MySQL insert statement?

The form is ok and it captures all of the information correctly, however, the errors started when I used a function to generate a random string that is used for user activation.
function generateActivationString() {
$randomSalt = '*&(*(JHjhkjnkjn9898';
$uniqId = uniqid(mt_rand(), true);
return md5($randomSalt.$uniqId);
}
if (!get_magic_quotes_gpc()) {
// $_POST['pass'] = addslashes($_POST['pass']);
$username = addslashes($_POST['username']);
$firstname = addslashes($_POST['firstname']);
$surname = addslashes($_POST['surname']);
// $_POST['email'] = addslashes($_POST['email']);
$email = mysql_real_escape_string(addslashes($_POST['email']));
$pass = mysql_real_escape_string(sha1($_POST['pass']));
$activationString = generateActivationString();
}
$insert = "INSERT INTO users (username, password, firstname, surname, email, activation_string)
VALUES ('".strtolower($username)."', '".$pass."', '".strtolower($firstname)."', '".strtolower($surname)."', '".strtolower($email)."', '".$activationString."')";
Here is the echoed insert statement:
INSERT INTO users (username, password, firstname, surname, email, activation_string) VALUES ('', '', '', '', '', '')
I know it has created a new entry as the auto_increment id row is populated however al of the other fields remain empty.
Here is the code from the generateActivationString() so I know that's working too! - 264361eeb6e75d3934ce249a0d05f2c1
Any suggestions are more than welcome and greatly appreciated!
Going strictly by the code above, your variables like $username,$password etc are in the scope of your if block, move them outside of the if.
I don't see you send that query anywhere, maybe that's your problem...
Oh dear. The biggest problem with your statement is that you are not using prepared statement and taking info directly from the POST parameters. This is a recipe for disaster and how most sites get hacked.

Categories