I can't see where i am going wrong, it just won't let me connect to the mysql database and i only get error message when trying to save details.?????? i think there may be a problem where it shows $sql for inserting the values into the table. the first part newstudent.php works, but sql.php does not work.
//new student.php
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
//sql.php
$conn=mysql_connect("localhost", "20915184", "mysqluser");
mysql_select_db("db5_20915184", $conn);
// If the form has been submitted
$id=$_POST['txtstudentid'];
$password=$_POST['txtpassword'];
$dob=$_POST['txtdob'];
$firstname=$_POST['txtfirstname'];
$lastname=$_POST['txtlastname'];
$house=$_POST['txthouse'];
$town=$_POST['txttown'];
$county=$_POST['txtcounty'];
$country=$_POST['txtcountry'];
$postcode=$_POST['txtpostcode'];
// Build an sql statment to add the student details
$sql="INSERT INTO student
(studentid,password,dob,firstname,lastname,house,town,county,country,postcode) VALUES
('$id','$password','$dob','$firstname','$lastname','$house','$town','$county','$country','$postcode')";
$result = mysql_query($sql,$conn);
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The username comes before the password in mysql_connect();
Try running the sql statement in phpmyadmin and see if it works there!
With in your if else statement, where you echo "ERROR", try printing mysql_error() this would show that your mysql_connect() is wrong If the username/password combo is wrong.
To clean this up a bit, Here is what the if/else should look like
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
} else {
echo "There has been an error <br/>";
print mysql_error();
}
EDIT :
Also, Prevent sql injection with mysql_real_escape_string() on all posted values
Well your code is incomplete, you must insert when the button is clicked also its important to check if a field isset before saving the field in the database also important to filter and sanitize user inputs before submitting. Learn to use prepared statements, with mysqli prepared or PDO whatever works for you, Also don't store passwords in plain text/md5 use password_hash() and password_verify()
Your code with mysqli prepared should look like :
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
sql.php
<?php
$servername = "localhost";
$username = "20915184";
$password = "mysqluser";
$dbname = "db5_20915184";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errors = "";
if (isset($_POST['submit'])) { // submit button clicked
// validate fields
if (empty($_POST['txtstudentid'])) {
echo "enter id";
$errors++;
} else {
$id = userData($_POST['txtstudentid']);
}
if (empty($_POST['txtpassword'])) {
echo "enter password";
$errors++;
} else {
$password = userData($_POST['txtpassword']);
$hash = password_hash($password, PASSWORD_DEFAULT); //hashing password
}
if (empty($_POST['txtdob'])) {
echo "enter date of birth";
$errors++;
} else {
$dob = userData($_POST['txtdob']);
}
if (empty($_POST['txtfirstname'])) {
echo "enter first name";
$errors++;
} else {
$firstname = userData($_POST['txtfirstname']);
}
if (empty($_POST['txtlastname'])) {
echo "enter last name";
$errors++;
} else {
$lastname = userData($_POST['txtlastname']);
}
if (empty($_POST['txthouse'])) {
echo "enter house";
$errors++;
} else {
$house = userData($_POST['txthouse']);
}
if (empty($_POST['txttown'])) {
echo "enter town";
$errors++;
} else {
$town = userData($_POST['txttown']);
}
if (empty($_POST['txtcounty'])) {
echo "enter country";
$errors++;
} else {
$country = userData($_POST['txtcounty']);
}
if (empty($_POST['txtpostcode'])) {
echo "enter post code";
$errors++;
} else {
$postcode = userData($_POST['txtpostcode']);
}
if ($errors <= 0) { //all fields are set no errors
//start query
//check if user id does not exist
$statement = $conn->prepare("SELECT studentid FROM students WHERE studentid = ?");
$statement->bind_param('s', $id);
$statment->execute();
$statement->bind_result($studentID);
if ($statement->num_rows == 1) {
echo "the student Id " . $studentID . " already registered please login";
} else {
// no results then lets insert
$stmt = $conn->prepare("INSERT INTO students (studentid,password,dob,firstname,lastname,house,town,country,postcode) VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssss", $id, $hash, $dob, $firstname, $lastname, $house, $town, $country, $postcode);
$stmt->execute();
echo "<p>Your Details have been updated<br> <a href=\"Home.html\">Back to main page";
$stmt->close();
$conn->close();
}
}
}
//filter userinput
function userData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
There are many good tutorials on the net on this, hopes this will help, I'm also open to suggestions and corrections incase I missed something.
**> Question mark (?)(placeholder) is used to assign the value.In Prepared
Statements we assign in the values in bind parameter function so that
our query is processed in secure way and prevent from SQL injections.**
In Prepared Statements we pass or attach the values to database query with the help of Bind Parameter function.
You have to attach all the variables whose value you want in your query with their appropriate Data Types just like we pass the 's' means the variable contains a string Data Type.
To execute the query in Prepared Statements you have to use execute() function with query object.
Remove the parameter from your with the inside inside and put in an empty string. i.e
VALUES('','$password','$dob',
etc etc
Related
I am building a CRM for my wife and I to use for our business. I have created a page with several goals in mind:
Be able to create a new entry in the database.
Be able to view an existing entry in the database.
Be able to update an existing entry in the database.
I originally had several php files performing this stuff, but have now used the GOTO function to get the code to bounce around to the different parts I need run depending on what is happening all while staying on the same page.
My question is, other than it looking messy, is there a downfall to doing it this way? In the future I will be looking into other and cleaner ways to do it (suggestions are welcome), but this is working for me at the moment and I would like to move on with the project and start building the additional parts I require for the CRM. Think of this as a beta version if you will. If there is some huge drawback to what I have done already, Id rather address it now, but if this is at least mildly reasonable I will push forward.
Here is what I have:
<?php
// Include Connection Credentials
include("../../comm/com.php");
//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);
// Connection Error Check
if ($link->connect_errno) {
echo "Sorry, there seems to be a connection issue.";
exit;
}
// Define Empty Temporary Client ID
$new_client_id ="";
// Define Empty Success Message
$successful ="";
// Define Empty Error Messages
$firstnameErr ="";
$lastnameErr ="";
$addressErr ="";
$cityErr ="";
$stateErr ="" ;
$zipcodeErr ="";
$phoneErr ="";
$emailErr ="";
// CHECK FOR SEARCH PROCESS
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['searched'])) {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto SearchReturnProcess;
}
}
// Retrieve Client ID
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['client_id'])) {
$buttontxt = "Create Client";
goto CreatNewClientProcess;
} else {
$client_id = $_POST['client_id'];
$buttontxt = "Update";
goto UpdateClientProcess;
}
}
// CONTINUE FOR NEW CLIENT
CreatNewClientProcess:
// Check For Missing Fields and report
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["email"])) {
$emailErr = "Email is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["address"])) {
$addressErr = "Address is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["city"])) {
$cityErr = "City is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["state"])) {
$stateErr = "State/Province is a required field - please make entry below";
goto FinishUpProcess;
}
if (empty($_POST["zipcode"])) {
$zipcodeErr = "Postal code is a required field - please make entry below";
goto FinishUpProcess;
}
}
// Prepared Statement For Database Search
if ($stmt = $link->prepare("INSERT INTO client (firstname, lastname, address, city, state, zipcode, phone, email) VALUES (?,?,?,?,?,?,?,?)")){
// Bind Search Variable
$stmt->bind_param('ssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Entry
$successful = "Client Successfully Created!";
// Define New Client ID
$new_client_id = $link->insert_id;
// FINISH NEW CLIENT PROCESS
goto FinishUpProcess;
// CONTINUE FOR SEARCHED PROCESS
SearchReturnProcess:
// Prepared Statement For Database Search
$stmt = $link->prepare("SELECT firstname, lastname, address, city, state, zipcode, phone, email FROM client WHERE client_id=?");
// Bind Client ID into Statement
$stmt->bind_param('s', $client_id);
// Execute the Statement
$stmt->execute();
// Bind Variables to Prepared Statement
$stmt->bind_result($firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);
//fetch value
$stmt->fetch();
// Close Statment
$stmt->close();
// FINISH SEARCHED PROCESS
goto FinishUpProcess;
// CONTINUE FOR UPDATE CLIENT PROCESS
UpdateClientProcess:
// Prepared Statement For Database Search
if ($stmt = $link->prepare("UPDATE client SET firstname=?, lastname=?, address=?, city=?, state=?, zipcode=?, phone=?, email=? WHERE client_id=?")){
// Bind Search Variable
$stmt->bind_param('sssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email, $client_id);
// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$client_id = $_POST['client_id'];
// Execute the Statement
$stmt->execute();
}
// Close Statment
$stmt->close();
// Report Successful Update
$successful = "Client Updated Successfully!";
// FINISH UPDATE PROCESS
goto FinishUpProcess;
// CONTINUE FOR FINISHING UP PROCESS
FinishUpProcess:
// Disconnect from Database
mysqli_close($link)
?>
<!DOCTYPE html>
<html>
<head>
<title>Client Information</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<h4>enter client info below</h4>
<font color="red"><?php echo $successful; ?></font>
<fieldset>
<input name="client_id" value="<?php if (empty($_POST['client_id'])) { echo $new_client_id; } else { echo $_POST['client_id']; } ?>" type="hidden">
</fieldset>
<fieldset>
<font color="red"><?php echo $firstnameErr; ?></font>
<input name="firstname" value="<?php if (isset($_POST['client_id'])) { echo $firstname; } else { echo $_POST['firstname']; } ?>" placeholder="First Name" type="text" tabindex="1" autofocus>
</fieldset>
<fieldset>
<font color="red"><?php echo $lastnameErr; ?></font>
<input name="lastname" value="<?php if (isset($_POST['client_id'])) { echo $lastname; } else { echo $_POST['lastname']; } ?>" placeholder="Last Name" type="text" tabindex="2">
</fieldset>
<fieldset>
<font color="red"><?php echo $emailErr; ?></font>
<input name="email" value="<?php if (isset($_POST['client_id'])) { echo $email; } else { echo $_POST['email']; } ?>" placeholder="Email Address" type="email" tabindex="3">
</fieldset>
<fieldset>
<input name="mailinglist" id="checkbox" type="checkbox" checked>
<label>add to the mailing list</label>
</fieldset>
<fieldset>
<font color="red"><?php echo $phoneErr; ?></font>
<input name="phone" value="<?php if (isset($_POST['client_id'])) { echo $phone; } else { echo $_POST['phone']; } ?>" placeholder="Phone Number" type="tel" tabindex="4">
</fieldset>
<fieldset>
<font color="red"><?php echo $addressErr; ?></font>
<input name="address" value="<?php if (isset($_POST['client_id'])) { echo $address; } else { echo $_POST['address']; } ?>" placeholder="Street Address" type="text" tabindex="5">
</fieldset>
<fieldset>
<font color="red"><?php echo $cityErr; ?></font>
<input name="city" value="<?php if (isset($_POST['client_id'])) { echo $city; } else { echo $_POST['city']; } ?>" placeholder="City" type="text" tabindex="6">
</fieldset>
<fieldset>
<font color="red"><?php echo $stateErr; ?></font>
<input name="state" value="<?php if (isset($_POST['client_id'])) { echo $state; } else { echo $_POST['state']; } ?>" placeholder="State/Province" type="text" tabindex="7">
</fieldset>
<fieldset>
<font color="red"><?php echo $zipcodeErr; ?></font>
<input name="zipcode" value="<?php if (isset($_POST['client_id'])) { echo $zipcode; } else { echo $_POST['zipcode']; } ?>" placeholder="Postal Code" type="text" tabindex="8">
</fieldset>
<fieldset>
<font color="red"><?php echo $countryErr; ?></font>
<input name="country" value="<?php if (isset($_POST['client_id'])) { echo $country; } else { echo $_POST['country']; } ?>" placeholder="Country" type="text" tabindex="9">
</fieldset>
<fieldset>
<input name="vegan" type="checkbox">
<label>Vegan or Vegitarian</label>
</fieldset>
<fieldset>
<input name="smoker" type="checkbox">
<label>Smoker</label>
</fieldset>
<fieldset>
<textarea name="client_notes" placeholder="general notes" tabindex="10"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" data-submit="...Sending"><?php echo $buttontxt; ?></button>
</fieldset>
</form>
</div>
</body>
</html>
I'm not sure I even knew that goto existed in PHP. I've used (and abused) my share of gotos over the years, but not lately. On to the fixes:
1 - Many of your gotos (e.g., SearchReturnProcess) can be replaced with function calls. Instead of making a chunk of code starting with a label (and using goto to get there), make a separate function with the same name function SearchReturnProcess() and put the code there.
2 - For the error processing, use if elseif:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is a required field - please make entry below";
} elseif (empty($_POST["lastname"])) {
$lastnameErr = "Last name is a required field - please make entry below";
} elseif...
etc.
Then you can either make that set of statements end with an else followed by the block of "no error" code, or instead of a bunch of separate errors you can make one generic error variable (e.g., $fieldErr) and after the block have code like if ($fieldErr != '') to handle error display and simply display the errors in one location instead of next to each field.
Yes.
I won't preach about heresy and blasphemy but show you that most of your GOTOs are simply wrong.
UpdateClientProcess. That's quite strange an idea that you have to validate input for the creation only. It should be always the same for both create and update. So this one is useless and harmful
FinishUpProcess from validation routines. That's awful from the usability point of view. There was an old Chiniese torture when a victim's head was fixed under the dripping tap. Unharmful at first, it drove people crazy in time. So you are doing with your verifications. Why not to check ALL fields and then tell user at once, instead of showing them errors one by one?
FinishUpProcess from saving data. This violates the HTTP protocol rule says that after processing the POST request a server should issue a Location header redirecting a client using GET method. Otherwise if a client would refresh a page, the record will be duplicated.
It looks messy. You said that. It took me a hard time to navigate your code to review it due to its monotonous structure. Code padding was invented on purpose. In Python, for example, you are forced to use padding to distinguish subordinate code blocks.
A proper structure for this code would be like
$errors = [];
if ($_POST) {
if (empty($_POST["firstname"])) {
$errors['firstname'] = "First name is a required field - please make entry below";
}
// and so on
if (!$errors) {
if (empty($_POST['client_id'])) {
// go for insert
} else {
// go for update
}
header("Location: .");
exit;
}
$firstname = htmlspecialchars($_POST['firstname']);
// and so on
}
if (!$errors ) {
if (!empty($_GET['client_id'])) {
// search your data from a GET variable
} else {
// define empty variables
}
}
?>
<html goes here>
Hi I am using prepared statements for the first time. I have a form whose values, i am inserting in Mysql database using Mysqli prepared statements. But the problem is if user leaves an input box empty, Query doesn't insert row to the database.
Form
<form action="test.php" method="post" class="signupform">
<input type="text" Placeholder="Name" name="name" Required="required"/>
<br />
<input type="email" Placeholder="Email-id" name="email" Required="required"/>
<br />
<input type="password" Placeholder="Password" name="pass" Required="required"/>
<br />
<span>Male<input type="radio" name="sex" value="M" checked="checked"/> Female<input type="radio" name="sex" value="F"/></span>
<br />
<input type="text" Placeholder="City" name="city"/>
<br /><br />
<input type="submit" value="CREATE MY ACCOUNT" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
include_once('includes/db.php');
$name=$_POST['name'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$city = $_POST['city'];
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if($stmt){
echo "result inserted";
}
}
}
?>
On using above form and query when i fill all the boxes of form it insert a new row for me. But if i leave an input box empty, It doesn't insert any row.
I also have seen a lot of questions which says that if i use variables like this
if(empty($_POST['city'])) { $city = null; } else { $city = $_POST['city']; }
then it will work and most of them are accepted answers. I am confused why this solution is not working for me ???
Any help is appreciated...Thanks
Your query is wrong:
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
It should be something like:
if (!empty($name) || !empty($pass) || !empty($email))
{
$stmt = $mysqli->prepare("INSERT INTO login(`name`,`password`,`email`,`sex`,`city`) VALUES(?,?,?,?,?)");
$stmt->execute([$name, $pass, $email, $sex, $city]);
echo "result inserted";
} else {
echo 'You have not entered all of the fields.';
}
In this instance, if the variables are not empty then perform insert. Else if they are empty fire a echo stating the fields haven't been filled in.
If you are happy for the fields to be null simply change !empty() to empty() but as Fred -ii- stated above, ensure your database allows NULL within them fields.
Probably this is not one of the smartest way to do it, but hey, it will get the job done.
One of the things that you need to do before assigning a variable to an $_POST field, you need to check if that $_POST field isset and its not empty, then assign the value if not empty, Currently if someone leaves out a field in your form when you run the query you will probably get a notice of undefined.
This is what you can do.
<?php
if (isset($_POST['submit'])) {
include_once('includes/db.php');
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = " ";
}
if (!empty($_POST['pass'])) {
$pass = $_POST['pass'];
} else {
$pass = " ";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = " ";
}
if (isset($_POST['sex'])) {
$sex = $_POST['sex'];
} else {
$sex = " ";
}
if (!empty($_POST['city'])) {
$city = $_POST['city'];
} else {
$city = " ";
}
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES(?,?,?,?,?)")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if ($stmt) {
echo "result inserted";
} else {
echo "could not insert";
}
}
}
?>
There are other better ways to do this.
I have here the code for insertion using PDO and the insertion is working fine my problem is that how can i can determine if i inputted in the textbox the record that is already in the database,in my database ihave a column of ID, Firstname and Lastname, ID is auto increment,Firstname is set to unique and lastly is password set to varchar..what i want to happen is that when try to insert a record that is already in the database i want a warning message or maybe a alert message that tells me that "the record is already duplicate"..can somebody please help me with it?
here is the code
class.php
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
and here is index.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
if($crud->create($Firstname,$Lastname))
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Insertion Failed!'); </script>";
}
}
?>
<form method="POST" class="signin" action="" name="Add" target="iframe">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="Firstname" name="Firstname" value="" type="text" placeholder="Username" required/>
</label>
<label class="password">
<span>Password</span>
<input id="Lastname" name="Lastname" value="" type="password" Placeholder="Password" required/>
</label>
<br />
<button id="submit" type="submit" name="btn-save">Save</button>
<button id="submit" type="reset" name="reset">Reset</button>
<br />
<br />
<hr>
</fieldset>
</form>
If you have the correct UNIQUE keys set in your database, PDO will already throw such a warning/error. You can easily try it yourself by inserting twice the same name
You should try to change your code to this, as this will throw the actual error. The correct function to call would be PDOStatement::errorInfo
Example code would be like this:
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
if (!$stmt->execute())
{
throw new Exception('Could not execute SQL statement: ' . var_export($stmt->errorInfo(), TRUE));
}
return true;
}
catch(Exception $e)
{
// Here you can filter on error messages and display a proper one.
return $e->getMessage();
}
}
In your index.php, change your PHP code to this:
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
$result = $crud->create($Firstname,$Lastname);
if($result === TRUE)
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert(" . $result . "); </script>";
}
}
An other, better, method would be to do a separate SELECT before you do the actual insert to see if the values you are trying to insert already exist.
My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.
This question already has answers here:
Insert data only if record does not exist
(3 answers)
Closed 8 years ago.
Here's my form:
<section class="loginform tmr">
<form name="login" action="welcome.php" method="post" accept-charset="utf-8">
<label for="username">Username: </label><br />
<?php if (isset($input_errors['username'])) { echo '<div class="error">' . $input_errors['username'] . '</div>'; } ?>
<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 />
<?php if (isset($input_errors['usermail'])) { echo '<div class="error">' . $input_errors['usermail'] . '</div>'; } ?>
<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>
</section>
Here's all my validation on my insert:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
else {
$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('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
I want to check username and email and if either are in use than alert the new registration user...
I'm thinking that my server side validation stuff is getting so messy that maybe i should build a class for this...??
That's not necessarily something i need help with atm.. I really just want to check mysql using best practices if the email is in use or the username is in use..
Any and all help would be greatly appreciated. Thank you.
try below or follow link php mysqli check if any result exist
<?php
function user_exists($email) {
$query = "SELECT 1 FROM " . USER_TABLE . " WHERE email = ?";
$stmt = $this->_db->prepare($query);
$stmt->execute(array($email));
return (bool)$stmt->fetchColumn();
}
//do your stuff here same for username
if(user_exits($register_email))
This code selects the number of rows with either username or email:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}