i am a beginner and am trying to make a form validation with PHP. i want to check if one of the inputs is empty, the form says that the empty input is required.
I show the php script behind.
<?php
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if (empty($_POST["submit"])) {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
}
?>
<form method="post" action="insert_post.php">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
include("includes/connect.php");
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = date('d-m-Y');
$author = $_POST['author'];
$keywords = $_POST['keywords'];
$content = $_POST['content'];
$image = $_FILES['image'] ['name'];
$image_tmp = $_FILES['image'] ['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
}
?>
The problem is i want to stop the scrit if the inputs are empty but i can't use functions like: exit() and break;.
and if i submit, the form sends empty values to the database :C.
how can i solve this problem?
We make use of session variables which temporarily stores data locally. To use sessions we must always start sessions by session_start() at the start of every page to be able to access the variables. Now we can store data and pass it to whatever page we want to without having to send it - we just store it and then grab it.
index.php
<?php
session_start();
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
if(!empty($_POST["title"]) && !empty($_POST["author"]) && !empty($_POST["keywords"]) && !empty($_POST["content"])){
$_SESSION["title"] = $_POST["title"];
$_SESSION["author"] = $_POST["author"];
$_SESSION["keywords"] = $_POST["keywords"];
$_SESSION["content"] = $_POST["content"];
$_SESSION["image"] = $_FILES["image"];
header("location: insert_post.php");
exit();
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38" value="<?php if(isset($_POST['title'])){ echo $_POST['title']; }; ?>">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38" value="<?php if(isset($_POST['author'])){echo $_POST['author']; }; ?>">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38" value="<?php if(isset($_POST['keywords'])){echo $_POST['keywords']; }; ?>">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15" value="<?php if(isset($_POST['content'])){echo $_POST['content']; }; ?>"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
insert_post.php
<?php
session_start();
include("includes/connect.php");
$title = $_SESSION['title'];
$author = $_SESSION['author'];
$keywords = $_SESSION['keywords'];
$content = $_SESSION['content'];
$date = date('d-m-Y');
$image = $_SESSION['image']['name'];
$image_tmp = $_SESSION['image']['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
else{
echo "<center><h1>Error! Post was not published!</h1></center>";
}
echo $title . " " . $author . " " . $keywords . " " . $content;
?>
Btw, you should be using prepared statements for your database inserts to prevent SQL-injections. Read more about it here.
You don't hAve to Break the Script using the Exit Funktion. Just prove if the error variables aren't empty and only in the Case when they aren't empty send a dB-request.
Chenge these lines:
include("includes/connect.php");
if(isset($_POST['submit'])){
to
include("includes/connect.php");
if( isset($_POST['submit']) //Fix here, it will only insert if all error message
&& empty($titleErr) //are empty.
&& empty($authorErr)
&& empty($keywordsErr)
&& empty($contentErr) ){
Edit
And also change this line
if (empty($_POST["submit"])) {
To
if (isset($_POST["submit"])) {
On the init of your script. The empty function will return true if you did not submit the page, that's why you are hving the error messages.
Related
UPDATE
I can now get it to update with actual values by having the coding on one page instead of 2 but it still wont update using the form, I have made it to only work on the landline for now until I can get it to work from the form.
Below is the new code without the html body which has some links to the php header;
$search = $_POST['search'];
$search2 = $_POST['search2'];
$results = mysqli_query($connection, "SELECT RecordReference, Dateofrecordcreation, Status, AgentName, ReturnFiledOn, InfoOnline, Surname, Forename, DateofBirth, UTR, NINO, Address, Postcode, AddressAffectiveFrom, Mobile, Landline, Email, Balance FROM `selfemployed` WHERE Surname LIKE '$search' AND Forename LIKE '$search2'");
while($row = mysqli_fetch_array($results))
{
$RecordReference = $row['RecordReference'];
$Dateofrecordcreation = $row['Dateofrecordcreation'];
$Status = $row['Status'];
$AgentName = $row['AgentName'];
$ReturnFiledOn = $row['ReturnFiledOn'];
$InfoOnline = $row['InfoOnline'];
$Surname = $row['Surname'];
$Forename = $row['Forename'];
$DateofBirth = $row['DateofBirth'];
$UTR = $row['UTR'];
$NINO = $row['NINO'];
$Address = $row['Address'];
$Postcode = $row['Postcode'];
$AddressAffectiveFrom = $row['AddressAffectiveFrom'];
$Mobile = $row['Mobile'];
$Landline = $row['Landline'];
$Email = $row['Email'];
$Balance = $row['Balance'];
}
if(isset($_POST['Update']))
$RecRef = $_POST['RecordReference'];
$Datereccr = $_POST['Dateofrecordcreation'];
$Sta = $POST['Status'];
$AgName = $_POST['AgentName'];
$Srnm = $_POST['Surname'];
$Frnm = $_POST['Forename'];
$DoB = $_POST['DateofBirth'];
$NatIn = $_POST['NINO'];
$Add = $_POST['Address'];
$Pstc = $_POST['Postcode'];
$AddAffFrm = $_POST['AddressAffectiveFrom'];
$UTaxR = $_POST['UTR'];
$Mob = $_POST['Mobile'];
$llffs = $_POST['Landline'];
$Eml = $_POST['Email'];
$RetFiled = $_POST['ReturnFiledOn'];
$Bal = $_POST['Balance'];
$Online = $_POST['InfoOnline'];
$id = $_POST['id'];
// Information to update
$sql_query = "UPDATE `selfemployed` SET `Landline` = '$llffs' WHERE RecordReference = '$RecordReference'";
// Update Qquery
mysqli_query($connection, $sql_query);
// Close our connection to the database
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<style type="text/css">
<!--
Original post
I have been trying to create an update function for my database and have been stuck for days on this now so thought that I would ask for help. The code seems to run without issues and no errors are being reported but it isn't being updated.
The search/display code is below (this works ok except it doesnt show all the text when there is spaces in the data)
Here is the search and display code
require_once "config.php";
$search = $_POST['search'];
$search2 = $_POST['search2'];
$results = mysqli_query($connection, "SELECT RecordReference, Status, ReturnFiledOn, InfoOnline, Surname, Forename, DateofBirth, UTR, NINO, Address, Postcode, AddressAffectiveFrom, Mobile, Landline, Email, Balance FROM `selfemployed` WHERE Surname LIKE '$search' AND Forename LIKE '$search2'");
while($row = mysqli_fetch_array($results))
{
$RecordReference = $row['RecordReference'];
$Dateofrecordcreation = ['Dateofrecordcreation'];
$Status = $row['Status'];
$AgentName = $row['AgentName'];
$ReturnFiledOn = $row['ReturnFiledOn'];
$InfoOnline = $row['InfoOnline'];
$Surname = $row['Surname'];
$Forename = $row['Forename'];
$DateofBirth = $row['DateofBirth'];
$UTR = $row['UTR'];
$NINO = $row['NINO'];
$Address = $row['Address'];
$Postcode = $row['Postcode'];
$AddressAffectiveFrom = $row['AddressAffectiveFrom'];
$Mobile = $row['Mobile'];
$Landline = $row['Landline'];
$Email = $row['Email'];
$Balance = $row['Balance'];
}
// Close our connection to the database
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<style type="text/css">
<!--
.style1 {color: #000000}
.style10 {color: #F4A5A4}
.style11 {color: #D3D3D3}
.style14 {color: #000000; font-size: 14px; }
.style15 {font-size: 14px}
.style16 {color: #D3D3D3; font-size: 14px; }
.style17 {color: #F4F2A4; font-size: 14px; }
.style3 {color: #000000; font-size: 18px; font-weight: bold; }
.style8 {color: #ABDEB2}
.style9 {color: #F4F2A4}
.style18 {
font-size: 24px;
font-weight: bold;
}
-->
</style>
<body>
<form action="updateselfemp.php" method="post">
<table width="850" border="0">
<tr>
<td width="420" valign="top" bgcolor="#F4A5A4"><table width="418" border="0">
<tr>
<td align="right">Reference<span class="style10">::</span></td>
<td><label>
<input name="RecordReference" type="text" id="RecordReference" value=<?php echo $RecordReference; ?> >
</label></td>
</tr>
<tr>
<td align="right">Date of Record Creation<span class="style10">::</span></td>
<td><label>
<input type="text" name="Dateofrecordcreation" id="Dateofrecordcreation" value=<?php echo $Dateofrecordcreation; ?> >
</label></td>
</tr>
<tr>
<td width="222" align="right"><span class="style15"><span class="style14">Company Status<span class="style10">:</span></span></span></td>
<td width="186"><select name="Status" id="Status">
<option selected><?php echo $Status; ?></option>
<option value="ACTIVE">ACTIVE</option>
<option value="CLOSED">CLOSED</option>
<option value="DORMANT">DORMANT</option>
<option value="PHOENIX">PHOENIX</option>
<option value="NO LONGER A CUSTOMER">NO LONGER A CUSTOMER</option>
</select></td>
</tr>
<tr>
<td align="right"><span class="style14">Agent Name<span class="style10">:</span>:</span></td>
<td><label>
<input name="AgentName" type="text" id="AgentName" value=<?php echo $AgentName; ?> >
</label></td>
</tr>
</table>
<span class="style1"></span></td>
<td width="420" valign="top" bgcolor="#F4F2A4"><p class="style3">Return Details</p>
<table width="418" border="0">
<tr>
<td width="263" align="right"><span class="style14">Date Return Filed</span><span class="style17">::</span></td>
<td width="145"><label>
<input name="DateReturnFiled" type="text" id="DateReturnFiled" value=<?php echo $ReturnFiledOn; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">Is this information online?</span><span class="style9">::</span></span></td>
<td><label>
<select name="Online" id="Online">
<option><?php echo $InfoOnline; ?></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
</label></td>
</tr>
</table></td>
</tr>
<tr>
<td valign="top" bgcolor="#D3D3D3"><p class="style3">Details</p>
<table width="418" border="0">
<tr>
<td width="268" align="right"><span class="style14">Surname</span><span class="style16">::</span></td>
<td width="140"><label>
<input name="Surname" type="text" id="Surname" value=<?php echo $Surname; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">Forename</span><span class="style11">::</span></span></td>
<td><label>
<input name="Forename" type="text" id="Forename" value=<?php echo $Forename; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">Date of Birth</span><span class="style11">::</span></span></td>
<td><label>
<input name="DateofBirth" type="text" id="DateofBirth" value=<?php echo $DateofBirth; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">UTR</span><span class="style11">::</span></span></td>
<td><label>
<input name="UTR" type="text" id="UTR" value=<?php echo $UTR; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">National Insurance No</span><span class="style11"></span></span></td>
<td><label>
<input name="NINO" type="text" id="NINO" value=<?php echo $NINO; ?> >
</label></td>
</tr>
<tr>
<td align="right" valign="top"><span class="style15"><span class="style1">Address<span class="style11">::</span></span></span></td>
<td><label>
<textarea name="Address" id="Address" cols="25" value=<?php echo $Address; ?> rows="3"></textarea>
</label></td>
</tr>
<tr>
<td align="right" valign="top"><span class="style15"><span class="style1">Postcode</span><span class="style11">::</span></span></td>
<td><label>
<input name="Postcode" type="text" id="Postcode" value=<?php echo $Postcode; ?> >
</label></td>
</tr>
<tr>
<td align="right" valign="top"><span class="style15"><span class="style1">Address Affective From</span><span class="style11">::</span></span></td>
<td><input name="AddressAffectiveFrom" type="text" id="AddressAffectiveFrom" value=<?php echo $AddressAffectiveFrom; ?> ></td>
</tr>
<tr>
<td align="right" valign="top"><span class="style15"><span class="style1">Mobile</span><span class="style11">::</span></span></td>
<td><label>
<input name="Mobile" type="text" id="Mobile" value=<?php echo $Mobile; ?> >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">Landline</span><span class="style11">::</span></span></td>
<td><label>
<input name="Landline" type="text" id="Landline" value="<?php echo $Landline; ?>" >
</label></td>
</tr>
<tr>
<td align="right"><span class="style15"><span class="style1">Email</span><span class="style11">::</span></span></td>
<td><label>
<input name="Email" type="text" id="Email" value=<?php echo $Email; ?> >
</label></td>
</tr>
<tr>
<td align="right"> </td>
<td><label></label></td>
</tr>
</table></td>
<td valign="top" bgcolor="#ABDEB2"><p class="style3">Balance</p>
<table width="418" border="0">
<tr>
<td width="261" align="right"><span class="style14">Outstanding Balance<span class="style8">::</span></span></td>
<td width="147"><label>
<input name="Balance" type="text" id="Balance" value=<?php echo $Balance; ?> >
</label></td>
</tr>
</table>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p>
<p class="style1"> </p></td>
</tr>
<tr>
<td> </td>
<td align="right"><label>
<input type="submit" name="Submit" id="Update" value="Update Record">
<input type="hidden" name="id" value"<?php echo $RecordReference; ?>">
</label></td>
</tr>
</table>
</form>
<span class="style18">Current File Content</span>
<table>
<tr><td>Record Reference</td> <td><?php echo $RecordReference; ?></td></tr>
<tr><td>Date of Record Creation</td> <td><?php echo $Dateofrecordcreation; ?></td>
</tr>
<tr><td>Status</td> <td><?php echo $Status; ?></td></tr>
<tr><td>Agent Name</td> <td><?php echo $AgentName; ?></td></tr>
<tr><td>Return Filed On</td> <td><?php echo $ReturnFiledOn; ?></td></tr>
<tr><td>Surname</td> <td><?php echo $Surname; ?></td></tr>
<tr><td>Forename</td> <td><?php echo $Forename; ?></td></tr>
<tr><td>Date of Birth</td> <td><?php echo $DateofBirth; ?></td></tr>
<tr><td>UTR</td> <td><?php echo $UTR; ?></td>
</tr>
<tr><td>NINO</td> <td><?php echo $NINO; ?></td>
</tr>
<tr><td>Address</td> <td><?php echo $Address; ?></td></tr>
<tr><td>Postcode</td> <td><?php echo $Postcode; ?></td></tr>
<tr><td>AddressAffectiveFrom</td> <td><?php echo $AddressAffectiveFrom; ?></td></tr>
<tr><td>Mobile</td> <td><?php echo $Mobile; ?></td></tr>
<tr><td>Landline</td> <td><?php echo $Landline; ?></td></tr>
<tr><td>Email</td> <td><?php echo $Email; ?></td></tr>
<tr><td>Balance</td> <td><?php echo $Balance; ?></td></tr>
</table>
</body>
</html>
Here is the update code
<?php
$RecordReference = $_POST['RecordReference'];
$date = date('d/m/Y h:i:s', time());
$Status = $_POST['Status'];
$AgentName = $_POST['AgentName'];
$ReturnFiledOn = $_POST['DateReturnFiled'];
$InfoOnline = $_POST['Online'];
$Surname = $_POST['Surname'];
$Forename =$_POST['Forename'];
$DateofBirth = $_POST['DateofBirth'];
$UTR = $_POST['UTR'];
$NINO = $_POST['NINO'];
$Address = $_POST['Address'];
$Postcode = $_POST['Postcode'];
$AddressAffectiveFrom = $_POST['AddressAffectiveFrom'];
$Mobile = $_POST['Mobile'];
$Landline = $_POST['Landline'];
$Email = $_POST['Email'];
$Balance = $_POST['Balance'];
// Connect to the database
require_once "config.php";
// update data in mysqli database
$sql = ("UPDATE selfemployed SET RecordReference = '$RecordReference', Dateofrecordcreation = '$date', Status = '$Status', AgentName = '$AgentName', ReturnFiledOn = '$ReturnFiledOn', InfoOnline = '$InfoOnline', Surname = '$Surname', Forename = '$Forename', DateofBirth = '$DateofBirth', UTR = '$UTR', NINO = '$NINO', Address = '$Address', Postcode = '$Postcode', AddressAffectiveFrom = '$AddressAffectiveFrom', Mobile = '$Mobile', Landline = '$Landline', Email = '$Email', Balance = '$Balance' WHERE RecordReference = '$RecordReference'");
// Close our connection to the database
mysqli_close($connection);
?>
<script type="text/javascript">
window.history.go(-2);
</script>
Any help with this is very much appreciated as I am at a loss as to what is wrong.
// update data in mysqli database
$sql = "UPDATE selfemployed SET RecordReference = '$RecordReference', Dateofrecordcreation = '$date', Status = '$Status', AgentName = '$AgentName', ReturnFiledOn = '$ReturnFiledOn', InfoOnline = '$InfoOnline', Surname = '$Surname', Forename = '$Forename', DateofBirth = '$DateofBirth', UTR = '$UTR', NINO = '$NINO', Address = '$Address', Postcode = '$Postcode', AddressAffectiveFrom = '$AddressAffectiveFrom', Mobile = '$Mobile', Landline = '$Landline', Email = '$Email', Balance = '$Balance' WHERE RecordReference = '$RecordReference'";
//Send query
mysqli_query($connection, $sql);
// Close our connection to the database
mysqli_close($connection);
Please try to use Prepared Statements (mysqli stmts or PDOs) to avoid SQL Injections.
It turns out that when I put everything on one page all I needed to do was change the update button ID and Name from Update to update it then worked perfectly.
You never run update query please run update query like below
$sql = "UPDATE selfemployed SET RecordReference = '$RecordReference', Dateofrecordcreation = '$date', Status = '$Status', AgentName = '$AgentName', ReturnFiledOn = '$ReturnFiledOn', InfoOnline = '$InfoOnline', Surname = '$Surname', Forename = '$Forename', DateofBirth = '$DateofBirth', UTR = '$UTR', NINO = '$NINO', Address = '$Address', Postcode = '$Postcode', AddressAffectiveFrom = '$AddressAffectiveFrom', Mobile = '$Mobile', Landline = '$Landline', Email = '$Email', Balance = '$Balance' WHERE RecordReference = '$RecordReference'";
// Update Qquery
mysqli_query($connection, $sql);
// Close our connection to the database
mysqli_close($connection);
customer_register.php
<?php
session_start();
?>
<form action="customer_register.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_usrname']) && isset($_POST['c_password']) && isset($_POST['c_country']) && isset($_POST['c_city']) && isset($_POST['c_contact']) && isset($_POST['c_address']) && isset($_FILES['c_image']['name'])) {
$c_ip_add = getIp();
$c_name = $_POST['c_name'];
$c_email = $_POST['c_email'];
$c_username = $_POST['c_usrname'];
$c_password = $_POST['c_password'];
$c_country = $_POST['c_country'];
$c_city = $_POST['c_city'];
$c_contact = $_POST['c_contact'];
$c_address = $_POST['c_address'];
$c_image = #$_FILES['c_image']['name'];
$c_tmp_name = #$_FILES['c_image']['tmp_name'];
$location = 'customer/customer_images/';
if (!empty($c_name) && !empty($c_email) && !empty($c_username) && !empty($c_password) && !empty($c_country) && !empty($c_city) && !empty($c_contact) && !empty($c_address) && !empty($c_image)) {
move_uploaded_file($c_tmp_name, $location.$c_image);
$select_user = "SELECT customers_username FROM customers WHERE customers_username = '$c_username'";
$run_select_user = mysqli_query($conn, $select_user);
if (mysqli_num_rows($run_select_user) == NULL) {
$insert_customer = "INSERT INTO customers(customers_ip, customers_name, customers_email, customers_username, customers_pass, customers_country, customers_city, customers_contact, customers_address, customers_image) VALUES ('$c_ip_add', '$c_name', '$c_email', '$c_username', '$c_password', '$c_country', '$c_city', '$c_contact', '$c_address', '$c_image')";
$run_insert_customer = mysqli_query($conn, $insert_customer);
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($check_cart == 0) {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("customer/my_account.php","_self")</script>';
} else {
$_SESSION['customer_email'] = $c_email;
$_SESSION['username'] = $c_username;
echo '<script>alert("Account has been successfully created")</script>';
echo '<script>window.open("checkout.php","_self")</script>';
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>The Username already exists. Please try another username.</b></div>";
}
} else {
echo "<div align='center' style='color:white; font-size:20px; padding:20px 0px;'><b>All Fileds are required</b></div>";
}
}
?>
<table align="center" width="750">
<thead>
<tr align="center">
<th colspan="3"><h1>Create an Account</h1></th>
</tr>
</thead>
<tbody>
<tr>
<td id="label" align="right">Name:</td>
<td><input type="text" name="c_name" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Email:</td>
<td><input type="text" name="c_email" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Username:</td>
<td><input type="text" name="c_usrname" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Password:</td>
<td><input type="password" name="c_password" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Image:</td>
<td><input type="file" name="c_image" required></td>
</tr>
<tr>
<td id="label" align="right">Country:</td>
<td>
<select name="c_country">
<option size="50">Select Country</option>
<?php countries(); ?>
</select>
</td>
</tr>
<tr>
<td id="label" align="right">City:</td>
<td><input type="text" name="c_city" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Contact:</td>
<td><input type="text" name="c_contact" size="40" required></td>
</tr>
<tr>
<td id="label" align="right">Address:</td>
<td><input type="text" name="c_address" size="40" required></td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="register" value="Create Account"></td>
</tr>
</tbody>
</table>
</form>
customer_login.php
<?php
session_start();
?>
<form method="post" action="">
<table width="500" align="center" bgcolor="skyblue">
<thead>
<tr align="center">
<th colspan="4"><h2>Login or Register to Buy!</h2></th>
</tr>
</thead>
<tbody>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="text" name="email" placeholder="Enter Email"></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" placeholder="Enter Password"></td>
</tr>
<tr align="center">
<td colspan="4">Forgot Password?</td>
</tr>
<tr align="center">
<td colspan="3"><input type="submit" name="login" value="Login"></td>
</tr>
</tbody>
</table>
<h2 style="float:right; padding:10px;">New? Register Here</h2>
</form>
<?php
if (isset($_POST['email']) && isset($_POST['pass'])) {
$email = $_POST['email'];
$pass = $_POST['pass'];
if (!empty($email) && !empty($pass)) {
$select_id = "SELECT * FROM customers WHERE customers_email = '$email' AND customers_pass = '$pass'";
$run_select_id = mysqli_query($conn, $select_id);
foreach ($run_select_id as $details) {
$usrname = $details['customers_username'];
$id = $details['customers_id'];
}
$num_run_select = mysqli_num_rows($run_select_id);
if ($num_run_select == NULL) {
echo '<script>alert("Invalid : Email/Password combination")</script>';
exit();
}
$c_ip_add = getIp();
$select_cart = "SELECT * FROM cart WHERE ip_add = '$c_ip_add'";
$run_select_cart = mysqli_query($conn, $select_cart);
$check_cart = mysqli_num_rows($run_select_cart);
if ($num_run_select > 0 AND $check_cart == 0) {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('customer/my_account.php','_self')</script>";
exit();
} else {
$_SESSION['customer_email'] = $email;
$_SESSION['username'] = $usrname;
$_SESSION['id'] = $id;
echo "<script>alert('You Have Logged In Succesfully')</script>";
echo "<script>window.open('checkout.php','_self')</script>";
}
} else {
echo 'Please enter valid email ID';
}
}
?>
my_account.php
<?php
session_start();
?>
<ul id="categories">
<?php
$location = 'customer_images/';
$usr_email = $_SESSION['customer_email'];
$user_name = #$_SESSION['username'];
$usr_id = $_SESSION['id'];
$select_image = "SELECT * FROM customers WHERE customers_id = '$usr_id'";
$run_image = mysqli_query($conn,$select_image);
foreach ($run_image as $select_all_data) {
$id = $select_all_data['customers_id'];
$name = $select_all_data['customers_name'];
$username = $select_all_data['customers_username'];
$email = $select_all_data['customers_email'];
$country = $select_all_data['customers_country'];
$city = $select_all_data['customers_city'];
$contact = $select_all_data['customers_contact'];
$address = $select_all_data['customers_address'];
$image = $select_all_data['customers_image'];
echo "<li style=''><img src='$location$image' height='150' width='174' style='text-align:center; border:3px solid black; padding:4px; border-radius: 109px;'></li>";
}
?>
<li>My Orders</li>
<li>Edit Account</li>
<li>Change Password</li>
<li>Delete Account</li>
<li>Logout</li>
</ul>
</div>
<div class="content_area2">
<?php cart(); ?>
<div id="my_account_menu">
<span>
<?php
if (isset($_SESSION['customer_email'])) {
echo "Welcome <i style='color:orange;'>" . $_SESSION['username']. ' </i>';
}
?>
<?php
if (!isset($_SESSION['customer_email'])) {
echo "<a href='../checkout.php' style='color:white;'>Login</a>";
} else {
echo "<a href='../logout.php' style='color:orange;'>Logout</a>";
}
?>
</span>
</div>
<?php getIp(); ?>
<div id="products_box">
<?php
if (!isset($_GET['my_orders']) && !isset($_GET['edit_account']) && !isset($_GET['change_pass']) && !isset($_GET['delete_account'])) {
?>
<div style="text-align:center;">
<table>
<tbody>
<tr>
<td id="label">Name : </td>
<td id="detail"><?php echo #$name; ?></td>
</tr>
<tr>
<td id="label">Username (Display Name) : </td>
<td id="detail"><?php echo #$username; ?></td>
</tr>
<tr>
<td id="label">Email : </td>
<td id="detail"><?php echo #$email; ?></td>
</tr>
<tr>
<td id="label">City : </td>
<td id="detail"><?php echo #$city; ?></td>
</tr>
<tr>
<td id="label">Contact : </td>
<td id="detail"><?php echo #$contact; ?></td>
</tr>
<tr>
<td id="label">Address : </td>
<td id="detail"><?php echo #$address; ?></td>
</tr>
</tbody>
</table>
</div>
<div style="padding:20px;"><b>You can see your orders by clicking this link</b></div>
<?php
}
?>
The problem is when I login it is working fine but when I register the user it gives the error undefined
$usr_id = $_SESSION['id'];
in my_account.php and all the information about the user is not displayed
I HAVE STARTED THE SESSION
I think you forget to call session_start before to do anything, even when there is no existing session.
<?php
session_start()
// your code...
You may want to look how it works with the basic example from the session_start function
As stated within the PHP session_start documentation:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
So you may want to include this call after PHP opening tag <?php as I wrote above
You have to initiate the session by using session_start() on every page where you want to use the session. And this is missing on my_account.php
Ex:
<?php
session_start();
// your code
nowhere in your customer_register.php file do you actually set $_SESSION['id'].
in addition to this:
there are no form tags around your register form, so its hard to see how any data is getting into the script anyway.
your'e also silencing (#) errors. If this is a learning task, which from your comments I assume it is, thats a very counterproductive thing to do.
As you only set $_SESSION['id'] in the login handing script, its not going to be available across pages unless they go through that form. Its hard to tell from your code what your'e intended user journey is, but as it stands at the moment it looks like your'e expecting them to register, then be able to see the account page as a logged in user.
Just set $_SESSION['id'] in the register script, or dispense with it entirely and use the username (seeing as you validate it as unique anyway).
Also, your'e query in the my_account.php is looking for a column customer_id which (as far as I can see) you dont actually set in the insert statement.
This is the trouble with programming, it only does what you tell it to do.
Please help not able to resolve, trying since three days but not able to know what the reason its throwing me such message. (below is my complete code).
<!DOCTYPE html>
<html>
<head>
<title>Insert New Post</title>
</head>
<body>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<table align="center" border="10" width="600">
<tr>
<td align="center" colspan="5" bgcolor="yellow"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="40"></td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td align="right">Post image:</td>
<td><input type="file" name="image_name"></td>
</tr>
<tr>
<td align="right">Post Content:</td>
<td><textarea name="content" cols="50" rows="20"></textarea></td>
</tr>
<tr>
<td align="center" colspan="5"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
Above Form is to insert and submit data in Database
// PHP
<?php
include("includes/connect.php");
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$datenow = date('Y/m/d');
$author = $_POST['author'];
$content = $_POST['content'];
$image_name = $_FILES['image_name']['name'];
$image_type = $_FILES['image_name']['type'];
$image_size = $_FILES['image_name']['size'];
$image_tmp = $_FILES['image_name']['tmp_name'];
if ($title =='' || $author =='' || $content =='') {
echo "<script>alert('Any feild is empty')</script>";
exit();
}
if ($image_type =='image/jpeg' || $image_type =='image/png' || $image_type =='image/gif') {
if ($image_size<=5000000000) {
move_uploaded_file($image_tmp, "images/$image_name");
}
else{
echo "<script>alert('Image is larger, only 50kb size is allowed') </script>";
}
}
else{
echo "<script>alert('image type is invalid')</script>";
}
// insert query
$sth = $con->prepare(" INSERT INTO posts (post_title, post_date, post_author, post_image, post_content) VALUE (:title,:datenow,:author,:image_name,:content) ");
$sth->bindParam(':post_title', $title);
$sth->bindParam(':post_date', $datenow);
$sth->bindParam(':post_author', $author);
$sth->bindParam(':post_image', $image_name);
$sth->bindParam(':post_content', $content);
$sth->execute();
echo "<h1>Form Submited Successfully</h1>";
}
?>
// $sth->execute(); is throwing error massage as above
You are binding wrong values.You haven't bind the post_* values. See below:
$sth = $con->prepare(" INSERT INTO posts (post_title, post_date, post_author, post_image, post_content) VALUES (:post_title,:post_date,:post_author,:post_image,:post_content) ");
$sth->bindParam(':post_title', $title);
$sth->bindParam(':post_date', $datenow);
$sth->bindParam(':post_author', $author);
$sth->bindParam(':post_image', $image_name);
$sth->bindParam(':post_content', $content);
So I'm having a challenge with a subscription system that I've been building.
I'm using a simple login php page to validate the username and password of the user against the DB, once authenticated the script creates a secure session and calls the edit_subscription.php file and passes the ID of the user through the Url.
The edit_subscription.php file takes the ID and pulls the user info using MYsql
and loads their info into a form. The user can then edit or modify their subscription details and press the submit button to update the DB.
Everything works except the mysql Update back to the DB.
I've managed to narrow the problem down to the ID variable
If I hardcode the variable into the update command it works and the db is updated
If I hardcode the ID into a variable used in the update command, it works up to a point. if I move that hardcoded variable in front of line 42 the update command will no longer work.
I think it's something to do with the post command, but even when I load the old ID into a hidden form and try to have it repost for the update command it still doesn't work and treats the variable as if it's empty.
I've tried for hours to get this working, and just can seem to get it going.
anyone have any suggestions pertaining to specifically this issue
(please don't comment of security or, best practices unless it relates specifically to the issue described thanks)
<?
$id = htmlspecialchars($_GET['ID']);
$username="****";
$database="****";
$host="****";
$pass ="****";
mysql_connect($host,$username,$pass);
#mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT * FROM `****`.`****` WHERE `Subscriber ID` = '$id' LIMIT 1");
$name_old=mysql_result($result,0,"Name");
$address1_old=mysql_result($result,0,"Address 1");
$address2_old=mysql_result($result,0,"Address 2");
$city_old=mysql_result($result,0,"City");
$prov_old=mysql_result($result,0,"Prov");
$postal_old=mysql_result($result,0,"Postal");
$country_old=mysql_result($result,0,"Country");
$email_old=mysql_result($result,0,"Email");
$qty_old=mysql_result($result,0,"qty");
$status_old=mysql_result($result,0,"Status");
$ezine_old=mysql_result($result,0,"Ezine");
$mailout_old=mysql_result($result,0,"Mailout");
$password_old=mysql_result($result,0,"Password");
$nameErr = $emailErr = $passwordErr = "";
$name=$_POST['name'];
$email=$_POST['email'];
$address1=$_POST['address1'];
$address2=$_POST['address2'];
$city=$_POST['city'];
$province=$_POST['prov'];
$postal=$_POST['postal'];
$country=$_POST['country'];
$password=$_POST['password'];
$mailout=$_POST['mailout'];
$ezine=$_POST['ezine'];
$status="Subscribed";
$qty=$_POST['qty'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passwordErr = "* Password is required";
}
if (empty($_POST["name"])) {
$nameErr = "* Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "* Invalid Characters";
}
}
if(isset($_POST['mailout'])){}
else{
$mailout="NO";
}
if(isset($_POST['ezine'])){}
else{
$ezine="NO";
}
if (empty($_POST["email"])) {
$emailErr = "* Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid email";
}
}
if($name != NULL AND $nameErr == ""){
if($email != NULL AND $emailErr == ""){
if($password != NULL AND $passwordErr == ""){
mysql_query("UPDATE `Subscribers` SET
`Name` ='$name',
`Email` = '$email',
`Address 1` = '$address1',
`Address 2` = '$address2',
`City` = '$city',
`Prov` = '$province',
`Postal` = '$postal',
`Country` = '$country',
`Password` = '$password',
`qty` = '$qty',
`Status` = '$status',
`Mailout` = '$mailout',
`Ezine` = '$ezine',
WHERE `Subscriber ID` = $id");
mysql_close();
echo ("<p align=\"center\"><font color=\"red\">Thank you for updating your subscription, you should receive an email confirmation shortly</font></p>");
}
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="100%" border="0">
<tr>
<td width="11%" align="right">Name</td>
<td width="3%"> </td>
<td width="47%"><input type="text" name="name" value="<?php echo $name_old;?>">
<font color="red"> <?php echo $nameErr;?></font></td>
<td width="39%" bgcolor="#CCCCCC"><input type="checkbox" name="ezine" value="YES"
<? if($ezine_old =="YES"){echo "checked";} ?>>
Subscribe by email</td>
</tr>
<tr>
<td width="11%" align="right">Address 1</td>
<td> </td>
<td width="47%"><input type="text" name="address1" value="<?php echo $address1_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="checkbox" name="mailout" value="YES" <? if($mailout_old =="YES"){echo "checked";} ?>>
Subscribe by Post </td>
</tr>
<tr>
<td width="11%" align="right">Address 2</td>
<td> </td>
<td width="47%"><input type="text" name="address2" value="<?php echo $address2_old;?>"></td>
<td bgcolor="#CCCCCC"><input type="text" name="qty" value="<?php echo $qty_old;?>" size="5">
# of copies.</td>
</tr>
<tr>
<td align="right">City</td>
<td> </td>
<td><input type="text" name="city" value="<?php echo $city_old;?>"></td>
<td> </td>
</tr>
<tr>
<td align="right">Province</td>
<td> </td>
<td><input type="text" name="prov" value="<?php echo $prov_old;?>" >
<td> </td>
</tr>
<tr>
<td align="right">Postal</td>
<td> </td>
<td><input type="text" name="postal"value="<?php echo $postal_old;?>" ></td>
<td></td>
</tr>
<tr>
<td align="right">Country</td>
<td> </td>
<td><input type="text" name="country" value="<?php echo $country_old;?>" ></td>
<td> </td>
</tr>
<tr>
<td align="right">Email</td>
<td> </td>
<td colspan="2"><input type="text" name="email" value="<?php echo $email_old;?>">
<font color="red"><?php echo $emailErr;?></font></td>
</tr>
<tr>
<td align="right">Password</td>
<td> </td>
<td colspan="2"><input type="password" name="password" value="<?php echo $password_old;?>">
<font color="red"> <?php echo $passwordErr;?></font></td>
</tr>
<tr>
<td align="right"> </td>
<td> </td>
<td> </td>
<td></td>
</tr>
<tr>
<td align="right"> </td>
<td><img src="images/shim.png" width="20" height="20" /></td>
<td><input type="Submit" ></td>
<td> </td>
</tr>
</table>
<p> </p>
</form>
There is a comma after
Ezine = '$ezine' ,
Remove it. Also you shall also use mysqli extension or PDO sql . mysql_ is deprecated
As you said, there is a lot wrong with that code.. however to satisfy your question here is the simple answer:
You left an extra comma in your update statement.
`Ezine` = '$ezine',
In the future try always checking if the query went through.
$result = mysql_query(..);
if($result) {
// it worked
} else {
// it failed
echo mysql_error(); // or mysqli_error($link); or $link->error, etc.
}
Best of luck
I'm trying to insert data to custom table from frontend as well as backend in wordpress.
Below is my code, its working if i insert the data from backend but its giving me Error 404 if i try to insert from frontend.
<?php
/*
Plugin Name: Custom Form
Description: Custom Plugin
Author: Bijay Luitel
*/
// Create the table if not exixts
?>
<style>
p {
display:block;
}
h3 {
height:20px;
padding:10px 5px;
}
</style>
<?php
//Short Codes
add_shortcode('form_bands','form_bands');
function form_bands(){
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$query1 = "SELECT * FROM grade";
$result1 = $wpdb->get_results($query1);
$query2 = "SELECT * FROM branch";
$result2 = $wpdb->get_results($query2);
if($_POST['action']==1 && $_POST['name'] != '' ){
$page_one_table = 'band';
$name =$_POST['name'];
$mailingAddress = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$url = $_POST['url'];
$telephone = $_POST['telephone'];
$gradeId = $_POST['grade'];
$branchId = $_POST['branch'];
$insertMe="INSERT INTO band ('Name', 'MailingAddress', 'City', 'State', 'Zip', 'Email', 'URL', 'Telephone', 'GradeID', 'BranchID') VALUES('$name', '$mailingAddress', '$city', '$state', '$zip', '$email', '$url', '$telephone', '$gradeId', '$branchId')";
$insert_page_one = $wpdb->query($insertMe);
//$insert_page_one = $wpdb->insert($page_one_table, $page_one_inputs);
$form_id = $wpdb->insert_id;
if($insert_page_one)
{
echo '<div id="successMsg" class="updated below-h2"><p>Operation Successful</p></div>';
}
else{
echo '<div id="successMsg" class="updated below-h2"><p>Error ! Recheck and tryagain.</p></div>';
}
}
elseif ($_POST['action']==1 && $_POST['name'] == ''){
echo '<div id="successMsg" class="updated below-h2"><p>Error ! Recheck and tryagain.</p></div>';
}
?>
<h2>Bands</h2>
<div class="postbox">
<form action="" method="post">
<div class="inside">
<table class="form-table">
<tr>
<th>Name :</th>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<th>Address :</th>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<th>City :</th>
<td><input type="text" name="city" /></td>
</tr>
<tr>
<th>State :</th>
<td><input type="text" name="state" /></td>
</tr>
<tr>
<th>Zip :</th>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<th>Telephone :</th>
<td><input type="text" name="telephone" /></td>
</tr>
<tr>
<th>Email :</th>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<th>Url :</th>
<td><input type="text" name="url" /></td>
</tr>
<tr>
<th>Grade :</th>
<td><select name="grade">
<?php foreach($result1 as $row){
$value = $row->GradeID;
echo '<option value="'.$value.'">';
echo $row->Grade;
echo "</option>";
}?>
</select></td>
</tr>
<tr>
<th>Branch :</th>
<td><select name="branch">
<?php foreach($result2 as $row){
$value = $row->BranchID;
echo '<option value="'.$value.'">';
echo $row->Name;
echo "</option>";
}?>
</select></td>
</tr>
</table>
<p class="submit">
<input type="submit" name="add_form" class="button-primary" value="Submit" />
</p>
<input type="hidden" name="action" value="1" />
</form>
</div>
</div>
<?php
}
function myForm ()
{
add_menu_page('Forms', 'Forms', '','forms', '');
add_submenu_page("forms", "Bands", "Bands", 0, "Bands", "form_bands");
}
add_action('admin_menu','myForm');
How can i solve this problem? Please Help me
I expect the issue you're having relates to your use of a "reserved" post variable name, of 'name'.
The WordPress Codex page for Register_Taxonomy() contains the list of "reserved terms".
Further, your action attribute on your form tag is missing your URL. That's handled OK in current browsers, but may cause unexpected behavior in some older browsers, and isn't guaranteed to work in future.
Better practice is to remove this attribute altogether, if you're not going to use it, because the spec strongly discourages authors from leaving it empty:
The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.
(This info re the action attribute thanks to #mercator with this answer )