Insert values into DB not working? - php

Hey guys i had a similar problem before but i scraped that idea. Now basically my system allows my users to input there data into the fields and if they submit it the information will go to the database. Now for some reason the data does not go and i am presented with the echo that i stored in my else statement which was " echo" try again later" ;"
Now i have gone back into the database and looked at all the fileds and there correct names and placed them into the query but nothing gets stored into the db. Now you may be thinking whats the file on top called connect.inc.php in my code this is its basically a script in php which connects to the server.
here is my code pleas have a look thank you :)
<?php
//require 'core.inc.php';
include 'connect.inc.php';
if(isset($_POST['Username'])&& isset($_POST['Password']) && isset($_POST['PasswordAgain'])&& isset($_POST['Firstname'])&& isset($_POST['Lastname'])){
$username = $_POST['Username'];
$password = $_POST['Password'];
$password_again = $_POST['PasswordAgain'];
$Firstname = $_POST['Firstname'];
$password_hash = md5($password);
$Lastname = $_POST['Lastname'];
if(!empty($username)&& !empty($password) && !empty($password_again) && !empty($Firstname) && !empty($Lastname)){
if ($password !== $password_again) {
echo "passwords do not match";
}
else{
$query = "SELECT username FROM members WHERE username = '$username'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run )==1){
echo "The username ". $username ." is taken";
}else{
$query = "INSERT INTO members VALUES ('','Firstname','Lastname','Username','Password')";
if ($query_run = mysql_query($query)){
echo "Well done";
}else{
echo "Sorry we couldn't register at this time. Please try again later thank you";
}
}
}
}
else{
echo "Please fill in all the details thank you ";
}
}
?>
<form action="join.inc.php" method="post">
Username: <input type="text" name="Username" value="<?php echo $username; ?>" /><br />
Password: <input type="password" name="Password" /><br />
Password Again: <input type="password" name="PasswordAgain" /><br />
FirstName: <input type="text" name ="Firstname" value="<?php echo $Lastname; ?>" /><br />
LastName: <input type="text" name ="Lastname" value="<?php echo $Firstname ?>" /><br />
<input type="submit" value="SUBMIT" />
</form>
Connect Script

I would recommend explicitly stating the columns used in your INSERT statement.
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','Firstname','Lastname','Username','Password')
Also, what is the blank value you are trying to insert? If that field is an AUTO_INCREMENT field, you should not include it in the VALUES declaration.

Try this :
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','$Firstname','$Lastname','$Username','$password_hash')

IF your first field is auto_increment
omit the field1 as shown below
INSERT INTO members (`field2`,`field3`,...)
VALUES ('field2Val','field3Val',...);

password !== $password_again
should be
password != $password_again

enable error_reporting and see whats wrong actually, is the ID first field auto increment?
if that's auto increment your query will execute but if its not auto increment and set to PK only it wont insert records and raise duplicate key error.
hope this helps

Try changing to:
$query = "INSERT INTO members VALUES ('". $Firstname."','". $Lastname. "','" .$username. "','" .$password_hash. "')";
$result = mysql_query($query);
if (!$result){
echo "Sorry we couldn't register at this time. Please try again later thank you";
}else{
echo "Well done";
}

you should use something like this.
$query = "insert into members (id,username) values ('','$username')";

Related

Canit insert into my MYSQL table

I am trying to make a registration form in which I have connected to the database and it can also check whether the username is unique or not but unfortunately, I can't insert the new data in my table.
I would really appreciate if anyone could help me with this.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include 'connect.inc.php';
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
//md5 password
$password_hash = md5($password);
//check to see if the fields are empty
if(empty($username) || empty($password)|| empty($firstname)|| empty($lastname)) {
echo "Not all fields filled!<br /><br />";
exit();
}
//check if password is equal
if($password != $password2) {
echo "Your Passwords Do Not Match.<br />";
exit();
} else {
$query = "SELECT `username` From `users` WHERE username='$username'";
$result = mysql_query($query);
if(mysql_num_rows($result) ==1) {
echo "Sorry, that user has already exists.";
exit();
} else {
$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username', '$password_hash', '$firstname', '$lastname'");
if($result1 = mysql_query($query1)) {
echo "Registered Successfully";
} else {
echo "Sorry, You could not Register";
}
}
}
}
?>
<form action="" method="POST">
Username:<br />
<input type="text" name="username" /><br /><br />
Password:<br />
<input type="password" name="password" /><br /><br />
Confirm Password:<br />
<input type="password" name="password2" /><br /><br />
First Name:<br />
<input type="text" name="firstname" /><br /><br />
Last Name:<br />
<input type="text" name="lastname" /><br /><br />
<input type="submit" value="Register" name="submit" />
</form>
Your INSERT statement is missing a closing parenthesis.
$query1= mysql_query("INSERT INTO ... '$lastname'");
$query1= mysql_query("INSERT INTO ... '$lastname')");
^
By the way, I find it easier when doing a single-row INSERT to use an alternative syntax, so the column names and the value are matched up:
$query1= mysql_query("INSERT INTO `users` SET
username='$username',
password='$password',
firstname='$firstname',
lastname='$lastname'");
That's easier to make sure you have the columns matched up to the right variables. Also there's no closing parenthesis to worry about.
See http://dev.mysql.com/doc/refman/5.7/en/insert.html for details on this syntax.
You should also abandon the deprecated mysql extension, and use PDO instead. Read this nice tutorial: https://phpdelusions.net/pdo
And Jay Blanchard is correct that your code is insecure. Security, like correctness, is not an add-on feature. You mention you are a beginner, but you should not start developing bad habits. Read https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
Try using
$query1= mysql_query("INSERT INTO users (username,password,firstname,lastname) VALUES ('$username', '$password_hash', '$firstname', '$lastname'");
Replace your else block with
else {
die('Error: ' . mysql_error());
//echo "Sorry, You could not Register";
}
From your comment, your INSERT QUERY is wrong. To find out what is wrong with your SQL query, add var_export($query1, true) with die. i.e.
die('Error: ' . mysql_error().'<br>Info: '.var_export($query1, true));
My guess is that you are still using your old query which has '' as one of the column names.
You want to probably insert the user id in the database.Define it as Autoincrement e remove the blank data from the query below:
Before:
$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username', '$password_hash', '$firstname', '$lastname'");
After:
$query1= mysql_query("INSERT INTO `users` (username,password,firstname,lastname) VALUES ('$username', '$password_hash', '$firstname', '$lastname')") or die(mysql_error());
And you need also to replace the line with the code if($result1 = mysql_query($query1)) { by if($result1) {

Creating login page with a student ID mysql and php

i have created a login page where a student is able to register using username, password and email. I have created a table which contains all the students ID. So when a students registers they have to enter a correct ID which has to match the table in order for them to register. I was wondering how can i do this. I am using php and mysql.
f(isset($_POST["submit"])){ `if(!empty($_POST['user']) && !empty($_POST['pass']) && !empty($_POST['email'])) {
$user=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$con=mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
query=mysql_query("SELECT * FROM login WHERE username='".$user."'");
$numrows=mysql_num_rows($query); if($numrows==0)
$sql="INSERT INTO login(username,password,email) VALUES('$user','$pass', '$email')";
$result=mysql_query($sql);
if($result){ echo "Account Successfully Created"; } else {
echo "Failure!";
else { echo "That username already exists! Please try again with another.";
else { echo "All fields are required!";
i have not included the student ID part as i am unsure
You would need to query the MySQL database and check that the user ID that the person has submitted is in the table. If it is in the table, then do whatever you want to do, or if not then tell the user that the user ID is incorrect.
It might help if you gave some more information about what you've actually already done...
like MattFiler said, you need to query the MYSQL database and check that the user ID and password a person has submitted is in the table or not. something like this;
PHP
require ('config.php');
if (isset($_POST['uname']) && isset($_POST['pass'])) {
$user = $_POST['uname'];
$pass = $_POST['pass'];
$que = "SELECT * FROM login WHERE username = '$user' AND password = '$pass' ";
$run = mysql_query($que);
$row = mysql_fetch_array($run);
$user_db = $row['username'];
$pass_db = $row['password'];
if ($user == $user_db && $pass == $pass_db) {
echo "LOGGED IN!";
// anything else you want to do here..
}
else {
echo "INVALID USER ID OR PASSWORD<br />Please Sign Up if you are a new user.";
die();
}
}
HTML
<form action="" method="post">
<p><label class="field">Username:</label></p>
<input class="textbox-300" name="uname" pattern="[a-zA-Z0-9\. ]+" required="" title="Please enter your Username" type="text">
<p><label class="field">Password:</label></p>
<input class="textbox-300" id="pass" name="pass" required="" type="password"> <input name="check" type="hidden">
<input class="button" name="sub" type="submit" value="Login">
</form>
Note: this is just a demo, do it with mysqli/PDO and consider taking care of SQL Injection/XSS before you go live.

php form submission to mysql database

I have a registration form. In the database, the username and email are unique index. When the form submits and username or email are already present in the database, the values are not inserted. I want to notify the user that the values were not inserted. How can i do this?
HTML
<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>
register.php:
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
mysqli_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
}
*Sweet And Short *
First check that username or email is exist or not using select query if resulting is 0 (it means not exists), Insert query will run ahead
<?php
if($_POST['register']){
$uname = $_POST['uname'];
$email = $_POST['email'];
$name= $_POST['name'];
$pass= $_POST['pass'];
$result = mysqli_query($con, 'SELECT * from TABLE_NAME where email_id = "'.$email.'" or username = "'.$uname.'" ');
if(mysqli_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysqli_query($con , 'INSERT INTO TABLE_NAME (`email_id`, `username`,`name`,`pass`) VALUES("'.$email.'", "'.$email.'", "'.$uname.'","'.$name.'", "'.$pass.'")');
if($query){
echo "data are inserted successfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
The query method would return true or false, depending on if the row has been inserted or not.
Try the following Code
include ("db.php");
if (isset($_POST['register']))
{
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$var = mysqli_query('SELECT * from company_profile where email_id = "'.$email.'" or username = "'.$uname.'" ');
$num = mysqli_num_rows($var);
if($num==0)
{
$result = INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','');
$res = mysqli_query($result);
if($res)
{
echo "Records Inserted Successfully!!";
}
else
{
echo "Records Inserted Failed!!";
}
}
else
{
echo "User with the Details Already exists!!"
}
}

PHP/MySql Update Will Not Work

i have created 2 pages
update.php
edit.php
we start on edit.php so here is edit.php's script
<?php
$id = $_SESSION["id"];
$username = $_POST["username"];
$fname = $_POST["fname"];
$password = $_POST["password"];
$email = $_POST["email"];
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("a2670376_Pass") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE members SET username = '$username', fname = '$fname',
password = '$password' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
<form action="update.php" method="post">
<input type="hidden" name="id" value="<?=$id;?>">
ScreenName:<br> <input type='text' name='username' id='username' maxlength='25' style='width:247px' name="username" value="<?=$username;?>"/><br>
FullName:<br> <input type='text' name='fname' id='fname' maxlength='20' style='width:248px' name="ud_img" value="<?=$fname;?>"/><br>
Email:<br> <input type='text' name='email' id='email' maxlength='50' style='width:250px' name="ud_img" value="<?=$email;?>"/><br>
Password:<br> <input type='text' name='password' id='password' maxlength='25' style='width:251px' value="<?=$password;?>"/><br>
<input type="Submit">
</form>
now here is the update.php page where i am having the MAJOR problem
<?php
session_start();
mysql_connect('mysql13.000webhost.com', 'a2670376_Users', 'Password') or die(mysql_error());
mysql_select_db("a2670376_Pass") or die(mysql_error());
$id = (int)$_SESSION["id"];
$username = mysql_real_escape_string($_POST["username"]);
$fname = mysql_real_escape_string($_POST["fname"]);
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$query="UPDATE members
SET username = '$username', fname = '$fname', email = '$email', password = '$password'
WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
now on edit.php i fill out the form to edit the account "test" while i am logged into it now once the form if filled out i click on |Submit!| button
and it takes me to update.php and it returns this
(0) Not Updated
(0) <= id of user logged in
Not Updated <= MySql Error from
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
i want it to update the user logged in and if i am not mistaken in this script it says
$id = (int)$_SESSION["id"];
witch updates the user with the id of the person who is logged in
but it isnt updating its saying that no tables were effected
if it helps heres my MySql Database picture
just click here http://i50.tinypic.com/21juqfq.png
even with
session_start();
it wont work returns the same thinf as before
it appears that you have not started your session, therefore $_SESSION['id'] is not set.
session_start();
And, as always don't use mysql_* functions, that time has gone. Use mysqli or PDO
it seems your session might have times out or you did not even initialize it at all.
from your output it shows the id is 0 so there is your problem

Simple PHP + MySQL Form Not Working

Alright, so recently I watched a tutorial and coded along with it in Notepad++. I am attempting a simple MYSQL login/register form, but when I login- it gives me the "Wrong U/P" error echo I wrote. It saves everything in the database as the md5 and stuff. Here is my codes.
register.php
<?php
require('config.php');
if(isset($_POST['submit'])){
//Preform the verification of the nation
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($email1 == $email2) {
if($pass1 == $pass2) {
//All good. Carry on.
$name = mysql_escape_string($_POST['name']);
$lname = mysql_escape_string($_POST['lname']);
$uname = mysql_escape_string($_POST['uname']);
$email1 = mysql_escape_string($_POST['email1']);
$email2 = mysql_escape_string($_POST['email2']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$pass1 = md5($pass1);
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname'");
if(mysql_num_rows($sql) > 0) {
echo "Sorry, that user already exists!";
exit();
}
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
}else{
echo "Sorry, your passwords do not match<br><br>";
exit();
}
}else{
echo "Sorry, your emails do not match.<br><br>";
}
}else{
$form = <<<EOT
<form action="register.php" method="POST">
First Name: <input type="text" name="name" /><br />
Last Name: <input type="text" name="lname" /><br />
Username: <input type="text" name="uname" /><br />
Email: <input type="text" name="email1" /><br />
Confirm Email: <input type="text" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name="pass2" /><br />
<input type="submit" value="Register" name="submit" />
</form>
EOT;
echo $form;
}
?>
login.php
<?php
require('config.php');
if(isset($_POST['submit'])){
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
echo "You are now logged in.";
exit();
}else{
echo "Wrong U/P combination";
}
}else{
$form = <<<EOT
<form action="login.php" method="POST">
Username: <input tye="text" name="uname" /><br>
Password: <input type="password" name="pass" /><br>
<input type="submit" name="submit" value="Login" />
</form>
EOT;
echo "$form";
}
?>
and config.php
<?php
mysql_connect("localhost", "X", "X");
mysql_select_db("X");
?>
The config.php code is correct, but I am not giving away X.
As you can see, this code echos out an error for login.php if it's incorrect. It gives me that error even if it is correct. I used MD5 hash passes, so please help!
Firstly, you're using the ` tag in there - this should be ' .
You need to either interpolate or concatenate your variables; i.e; instead of
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
use;
mysql_query("INSERT INTO 'users' ('id', 'name', 'lname', 'uname', 'email', 'pass') VALUES (NULL, '{$name}', '{$lname}', '{$uname}', '{$email1}', '{$pass1}')");
Anyway, aside from some good practice, have a look at this line;
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
Just a small typo ruining everything for you. Change SELECET to SELECT , and you should be good to go.
Best of luck!
Eoghan
you don't need the following lines:
$email2 = mysql_escape_string($_POST['email2']);
and
`$pass2 = mysql_escape_string($_POST['pass2']);`
2. run SELECET * FROM users in order to see that the user/pwd really made it to the DB
3. add echo "$uname $pass <br>"; to the login form to make sure that it passed correctly
The other two answers are correct, but you have a more fundamental issue with this: you are using the old, deprecated mysql_* functions. Those functions are an old, procedural interface to MySQL and don't support the modern features of that RDBMS. I suggest using mysqli or PDO for an OOP approach to database access.
If you are going to stick to this ancient code, you should at least use mysql_real_escape_string() instead of mysql_escape_string().

Categories