checking to see if a text box is empty in php - php

I have a php/html from where the user enters a number of values which are then updated into a database by using mysqli and a insert query, If the user does not enter anything into any of the text boxes I want a message to appear saying that the information is not there, I have tried using
if($ownerName == "" ){
echo("Missing Information!");
but it won't work.
Here is my php code
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
?>
Here is my form
<html><head><title>Connect to Database</title></head><body>
<font size="4"> Enter owner details</font><br><br>
<form action="update.php" method="post" >
Owner Name:<input type="text" name="OwnerName">
Location: <input type="text" name="Location">
Phone Number:<input type="text" name="PhoneNumber">
<input type="submit" name = "submit" value="Submit Value">
</form></body></html>

try this:
if((!isset($ownerName)) || $ownerName == "" || (!isset($location)) || $location == "" || (!isset($phoneNumber)) || $phoneNumber == "")){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
}
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}

Try this
Change your condtion from
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
to
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
} else {
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}

<?php
include "connect.php";
if(isset($_POST["submit"]))
{
$ownerName = isset($_POST['OwnerName']) ? $_POST['OwnerName']: '';
$location = isset($_POST['Location']) ? $_POST['Location']: '';
$phoneNumber = isset($_POST['PhoneNumber']) ? $_POST['PhoneNumber']: '';
//preventing sql injection
/*
$ownerName = mysqli_real_escape_string($con, $ownerName);
$$location = mysqli_real_escape_string($con, $ownerName);
$$phoneNumber = mysqli_real_escape_string($con, $ownerName);
*/
if(empty($ownerName) || empty($location) || empty($phoneNumber)){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
}else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
}
mysqli_close($con);
?>
Also try using var_dump($_POST) to see what is sent.
EDIT:
I've updated if/else statement so now it should work. Also, make sure you have your error reporting enabled:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

Try this
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];}
if(empty($ownerName) && empty($location) && empty($phoneNumber))
{
echo("Missing Information!");}
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
?>

Try this:
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
}
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
}
mysqli_close($con);
}
?>

**Please replace your code from below code**
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
} else {
// please replace your column name (`owner_name`, `location`, `phone_number`)
$query = "INSERT INTO OWNER (`owner_name`, `location`, `phone`) VALUES ('" . $ownerName . "', '" . $location. "', " . $phoneNumber. ")";
if (!mysqli_query($con, $query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
}
?>

Try to use empty() function or isset()

Related

how to get get sign up message from my database

I'm setting up the wholly organized sign up form, I'm trying to sent into information into my MySQL database server. My code not work and can't figuring out pops up message You have been signed up!
I've tried several options but none of them work on a server,
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
// So I'm guessing here need to some additions of based my own inclinatios.
my code
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
$link = mysqli_connect("localhost", "id8955440_bigebro", "sunshine1987**", "id8955440_bigebro");
if (mysqli_connect_error()) {
die("There was an error connecting to the database");
}
if ($_POST['email'] == '') {
echo "<p>Email address is required.</p>";
} else if ($_POST['password'] == '') {
echo "<p>Password is required.</p>";
} else {
$query = "SELECT `id` FROM `bigebro` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo "<p>That email address has already been taken.</p>";
} else {
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
}
}
}
?>
HTML
<form method="post">
<input name="email" type="text" placeholder="Email address">
<input name="password" type="password" placeholder="Password">
<input type="submit" value="Sign up">
</form>
$link = mysqli_connect("localhost", "id8955440_bigebro", "sunshine1987**", "id8955440_bigebro");
When I signed up form only pops up "There was a problem signing you up - please try again later" I want to expect to "you have been signed up" from the result
. please see sign up form
Use mysqli_error to track error in query.
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "Error: " . mysqli_error($conn);
}
Also check your db stucture like id should be auto incremented, email and password should be varchar.
you should validate email and password with javascript.
put an echo statement below the line
$query = "INSERT INTO `bigebro` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
echo $query;
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
Run the printed query with the same database credentials. If it runs then the problem is with ur PHP code. u should have INSERT privileges for your database user.

SQL INSERT doens't insert, without any error

I am making a hotel booking system for a school project.
Guests first need to create an account:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$signupdate = mysqli_real_escape_string($conn, $_POST['signupdate']);
$first = mysqli_real_escape_string($conn, $_POST['firstname']);
$last = mysqli_real_escape_string($conn, $_POST['lastname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$hoteluserkey = uniqid('', true);
//Error handlers
//Check for empty fields
if (empty($signupdate) || empty($first) || empty($last) || empty($email) || empty($phone) || empty($address) || empty($pwd)) {
header("Location: ../index.php?signup=empty");
exit();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../index.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?signup=invalidemail");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO hotelusers
(hotelusers_signupdate, hotelusers_hoteluserkey, hotelusers_first, hotelusers_last, hotelusers_email, hotelusers_phone, hotelusers_address, hotelusers_pwd)
VALUES ('$signupdate', '$hoteluserkey', '$first', '$last', '$email', '$phone', '$address', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../index.php?signup=success");
exit();
}
}
}
} else {
header("Location: ../index.php");
exit();
}
This code works.
Now to problem comes. When someone books a room they see these input fields:
<div class="book">
<p class="main_p_ex">Book a room</p>
<form class="book" action="includes/book.inc.php" method="post">
<input type="hidden" name="bookdate" value="<?php echo date("Y-m-d h:i:sa"); ?>">
<input type="text" name="userkey" placeholder="your key">
<input type="password" name="pwd" placeholder="password">
<p>room</p>
<select name="room">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
<p>from</p>
<input type="date" name="from" min="<?php echo date("Y-m-d");?>">
<p>to</p>
<input type="date" name="to" min="<?php echo date("Y-m-d");?>">
<textarea name="otherguests" placeholder="full names of all other
guests"></textarea>
<textarea name="comments" placeholder="any comments?"></textarea>
<button type="submit" name="submit">Book!</button>
</form>
</div>
This also works fine.
I have this code for inserting these inputs into a database:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$bookdate = mysqli_real_escape_string($conn, $_POST['bookdate']);
$userkey = mysqli_real_escape_string($conn, $_POST['userkey']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$room = mysqli_real_escape_string($conn, $_POST['room']);
$from = mysqli_real_escape_string($conn, $_POST['from']);
$to = mysqli_real_escape_string($conn, $_POST['to']);
$otherguests = mysqli_real_escape_string($conn, $_POST['otherguests']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
$bookingkey = uniqid('', true);
//Error handlers
//Check if inputs are empty
if (empty($userkey) || empty($pwd) || empty($room) || empty($from) || empty($to) || empty($pwd)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM hotelusers WHERE hotelusers_hoteluserkey='$userkey'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?key=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//De-hashing the password
$hashedPwdCheck = password_verify($pwd, $row['hotelusers_pwd']);
if ($hashedPwdCheck == false) {
header("Location: ../index.php?key=error");
exit();
} elseif ($hashedPwdCheck == true){
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$roomnew = $row['hotelrooms_name']; }
}
$fromnew = strtotime($from);
$tonew = strtotime($to);
$datediff = $tonew - $fromnew;
$days = round($datediff / 86400);
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$pricepd = $row['hotelrooms_price']; }
}
$price = $days * $pricepd;
echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments;
$sql = "INSERT INTO hotelbookings
(hotelbooking_bookingkey, hotelbooking_bookdate, hotelbooking_userkey, hotelbooking_room, hotelbooking_from, hotelbooking_to, hotelbooking_days, hotelbooking_price, hotelbooking_paid, hotelbooking_otherguests, hotelbooking_comments)
VALUES ('$bookingkey', '$bookdate', '$userkey', '$roomnew', '$from', '$to', '$days', '$price', '$otherguests', '$comments');";
mysqli_query($conn, $sql);
//header("Location: ../index.php?booking=success");
exit();
}
}
}
}
} else {
header("Location: ../index.php?booking=error");
exit();
}
NOTE: I disabled the last header function for debugging. Un-commenting it changes nothing. Also tried clearing browser history, cookies and all that. Nothing works.
What am I missing here?
I don't get any errors, and the echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments; works fine. It just doesn't insert anything.
solved it myself by just making everything again... kinda weird I know

php - MYSQL Update Query not work complete

I have a little Problem with my Update query to chnage the Profile Infos
Problem now:
My Update Query is not working completly, the E-Mail query work but the status query is not working.
PHP CODE
if(!empty($_POST)) {
$query = "UPDATE users SET";
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if($row != 0) {
header("Location: ".$l['settings']."?msg=2");
die("REDIRECT");
}
$query .= " `email`='".$_POST['email']."'";
$_SESSION['u']['email'] = $_POST['email'];
} else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: ".$l['settings']."?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if(!empty($_POST['status'])) {
$query .= ",`status`='".$_POST['status']."'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
$query .= " WHERE id='".$_SESSION['u']['id']."'";
mysql_query($query);
header("Location: ".$l['settings']."?msg=1");
die("REDIRECT");
}
HTML FORM
<input maxlength="200" type="text" class="form-control" placeholder="Status" name="status" value="<?php //ECHO STATUS ?>" />
Maybe someone can help me.
On your $query you have
$query .= ",`status`='".$_POST['status']."'";
remove comma make it like this
$query .= " `status`='".$_POST['status']."'";
You need to set a flag for email condition as
$flag = FALSE;// set a flag
if (!empty($_POST)) {
if (!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if ($row != 0) {
header("Location: " . $l['settings'] . "?msg=2");
die("REDIRECT");
}
$flag = TRUE;// set to true if success
$_SESSION['u']['email'] = $_POST['email'];
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: " . $l['settings'] . "?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if (!empty($_POST['status'])) {
$query = "UPDATE users SET";
$query .= " `status`='" . $_POST['status'] . "'";
if ($flag) {// if true then apply email condition
$query .= ",`email`='" . $_POST['email'] . "'";
}
$query .= " WHERE id='" . $_SESSION['u']['id'] . "'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
mysql_query($query);
header("Location: " . $l['settings'] . "?msg=1");
die("REDIRECT");
}
Note:- mysql is deprecated instead use mysqli OR pdo

unknown problems with php login

i'm new to here, nice to meet you all ^_^
I'm having a project that to implement a simple website which allow user to login
i try to search around online but still have no idea how to fix it.
below are the code(login.php) that i written after referring to several source.
if(!($stmt = $mysqli->prepare("SELECT * FROM attendant WHERE username = ?")))
{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
else
{
if(!($stmt->bind_param('s',$username)))
{
echo "bind parameter failed";
}
else
{
if(!($stmt->execute()))
{
echo "Execute Failed:(" . $stmt->errno .")". $stmt->error;
}
else
{
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row["username"] == $username && $row["password"] == $password && $row["status"] == $status)
{
$_SESSION['user']=$username;
header("Location: test.html?user=$username");
}
else if($row["username"] == $username && $row["password"] == $password && $row["status"] != $status)
{
header("Location: test.html?user=$username#verify-slide");
}
else
{
header("Location: test.html?Login=Fail#login-slide");
}
}
}
}
}
$stmt->close();
}
the login works perfectly when the username does exist in the database.
But if it's not, the function are not working anymore and will only stay at the login.php file.
If there is no matched record in db, then it will not come into the while loop.
Add exit(); right after head(...), and put header("Location: test.html?Login=Fail#login-slide"); outside the while loop.
And the while loop is not necessary, you could change your code like:
$res = $stmt->get_result();
if ($row = $res->fetch_assoc() && $row["password"] == $password) {
if($row["status"] == $status) {
$_SESSION['user']=$username;
header("Location: test.html?user=$username");
} else {
header("Location: test.html?user=$username#verify-slide");
}
} else {
header("Location: test.html?Login=Fail#login-slide");
}
exit();
If there aren't any matches to the username then you never enter the while loop. That means your script will continue to the end. You should first put an exit() statement after each header call. Then you should do whatever you want to do in the event that the username name doesn't exist after the while loop.
Maybe you can try this :
if(!($stmt = $mysqli->prepare("SELECT * FROM attendant WHERE username = ?")))
{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
else
{
if(!($stmt->bind_param('s',$username)))
{
echo "bind parameter failed";
}
else
{
if(!($stmt->execute()))
{
echo "Execute Failed:(" . $stmt->errno .")". $stmt->error;
}
else
{
$res = $stmt->get_result();
if($res->mysqli_num_rows()==0)
{
header("Location: test.html?Login=Fail#login-slide");
}
else
{
while($row = $res->fetch_assoc())
{
if($row["username"] == $username && $row["password"] == $password && $row["status"] == $status)
{
$_SESSION['user']=$username;
header("Location: test.html?user=$username");
}
else if($row["username"] == $username && $row["password"] == $password && $row["status"] != $status)
{
header("Location: test.html?user=$username#verify-slide");
}
}
}
}
}
}
$stmt->close();
}

Validate Input form in PHP

I'm trying to validate my form before inserting into database with this code, but I keeps printin 'You missed a value'. I would like your help to figure out the problem.
Thanks
<?php
$username = mysql_real_escape_string($_POST['username']);
$pword = mysql_real_escape_string($_POST['passwd']);
$fname = mysql_real_escape_string($_POST['firstname']);
$lname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$telephone = mysql_real_escape_string($_POST['telephone']);
$ad1 = mysql_real_escape_string($_POST['ad1']);
$ad2 = mysql_real_escape_string($_POST['street']);
$ad3 = mysql_real_escape_string($_POST['town']);
$pcode = mysql_real_escape_string($_POST['pcode']);
if( $username == " " || $pword == " " || $fname == " " || $lname == " " || $email == " ")
echo 'You missed a value';
exit();
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("people", $con);
//$description = mysql_real_escape_string($_POST[description]);
$pword = md5($pword);
$sql="INSERT INTO members (username, pword, fname, lname, email, telephone, ad1, ad2, ad3, pcode)
VALUES
('$username','$pword','$fname', '$lname', '$email','$telephone','$ad1','$ad2','$ad3','$pcode')";
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
You should validate off the raw POST values, not the mysql_real_escape_string ones. Also you are comparing to (space) not empty string and assigning them not comparing them.
if( $username == '' || $pword == '' || $fname == '' || $lname == '' || $email == '')
You are assigning an empty space to the variables by doing $var = "", instead of comparing with with the comparison operators $var == '', or stricter $var === ''.
This would be a little bit cleaner code to follow and maintain:
function sqlEscape($string){
return "'".mysql_real_escape_string($string)."'";
}
if( $_POST['username'] == ''
|| $_POST['passwd'] == ''
|| $_POST['firstname'] == ''
|| $_POST['lastname'] == ''
|| $_POST['email'] == '')
{
exit('You missed a value');
}
$con = mysql_connect('localhost', 'root', '');
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('people', $con);
//$description = mysql_real_escape_string($_POST[description]);
$pword = md5($_POST['passwd']);
$sql = sprintf('INSERT INTO members (username, pword, fname, lname, email, telephone, ad1, ad2, ad3, pcode)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
sqlEscape($_POST['username']),
sqlEscape($pword),
sqlEscape($_POST['firstname']),
sqlEscape($_POST['lastname']),
sqlEscape($_POST['email']),
sqlEscape($_POST['telephone']),
sqlEscape($_POST['ad1']),
sqlEscape($_POST['street']),
sqlEscape($_POST['town']),
sqlEscape($_POST['pcode']));
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
echo '1 record added';
mysql_close($con)
I added in a function (sqlEscape) to run all the mysql_real_escape_string, just to make the escapes a piece of cake. Notice that I am calling this function after the MySQL connection has been established, because mysql_real_escape_string will NOT work without a connection.
check your if condition use == instant of =
wrong
if( $username = " " || $pword = " " || $fname = " " || $lname = " " || $email = " ")
Use == instead of = in your if's.
if( $username == " " || $pword == " " || $fname == " " || $lname == " " || $email == " ")
take out the spaces in this line and you need double equals
if( $username = " " || $pword = " " || $fname = " " || $lname = " " || $email = " ")
change to
if( $username == "" || $pword == "" || $fname == "" || $lname == "" || $email == "")
if( $username = " ") does not compare but assign, use if( $username == " ") instead – which still checks, whether the input is a single space-char, which maybe mostly isn't. To check if a variable has content or not use if(empty($username)).
Also its maybe better for you to use array_map on the $_POST-array to escape the values:
array_map(function($value) {
return mysql_real_escape_string($value);
}, $_POST);
(If you're prior to PHP 5.3, you need to use a separate function declaration instead of an anonymous callback.)
Yeap, the sign "=" is to set a variable, the comparaison sign is "==" or "===" in PHP.
btw, to minimize your code you can use "array_map" to apply "mysql_real_escape_string" function to your POST array :
$post = array_map("mysql_real_escape_string", $_POST);
= is assignment operator. It gives a value.
== is comparison operator. It compares the 2 things.
=== is also a comparison operator, but it compares whether the values and the variable types are the same. You need to remember that.
Also, you can also make your code clearer like this (it's just an example, don't copy paste it because it can be improved and it's not exactly safe):
foreach($_POST as $key => $value)
{
$columns[] = $key;
$value = mysql_real_escape_string($value);
$values[] = "'" . $value ."'";
if(empty($value))
{
$errors[] = 'POST with key '. $key .' was not filled in';
}
}
if(!isset($errors))
{
$query = "INSERT INTO (". implode(',', $columns .") VALUES (". implode(',', $values .")";
}
else
{
echo implode('<br />', $errors);
}
While learning how to program, if you find yourself copypasting certain code - you then know it's something you can code more intelligently.
if( $username == " " || $pword == " " || $fname == " " || $lname == " " || $email == " ")
{
echo 'You missed a value';
exit();
}
I think you should add this line after assigning your variables:
if($_SERVER['REQUEST_METHOD']== 'POST'){if( $username == " " || $pword == " " || $fname == " " || $lname == " " || $email == " ")
echo 'You missed a value';
exit();
}
//OTHER CODE

Categories