Server error from else if condition - php

I keep getting a server error and I have limited it down to this code block. I must not be familiar with syntax. Can someone point out why I am getting a server error?? I posted all the code. HERE IT IS.....
<?php
// this starts the session
session_start();
$id = $_SESSION['userid'];
//this connects to the database
$con = mysql_connect("example","example","example");
mysql_select_db("example", $con);
//this is the info the user entered stored as variables
$leaguename = $_POST["leaguename"];
$members = $_POST["members"];
$leaguepassword = $_POST["leaguepassword"];
//this filters throught the variables to check against mysql injections
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_STRING));
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_URL));
$members = (filter_var($members, FILTER_SANITIZE_STRING));
$members = (filter_var($members, FILTER_SANITIZE_URL));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_STRING));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_URL));
//this is the variables that displays errors
$errors = "";
$result = mysql_query("SELECT * FROM League_Info WHERE League = '$leaguename'");
$result2 = mysql_fetch_array($result);
$result3 = $result2['League'];
$result4 = mysql_query("SELECT * FROM League_Info WHERE User_ID = '$id'");
$result5 = mysql_fetch_array($result4);
$result6 = $result5['User_ID'];
if ($id == "") {
$errors .= "<li>You must register or login to create a league!"; break;
} elseif ($result3 != "") {
$errors .= "<li>League Name already in use!"; break;
} elseif ($result6 != "") {
$errors .= "<li>You already have a league!"; break;
} else {
}
// no errors
if ($errors == "") {
$sql="INSERT INTO League_Info (League, User_ID, Commissioner, Year, Members, League_Password)
VALUES('$leaguename', '$id', 'y', '2012', '$members', '$leaguepassword')";
mysql_query($sql);
/* Redirect browser */
header("Location: http://www.yourfantasyfootballreality.com/invite.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
} else {
}
?>
<html><head><title>Create a League</title></head>
<body>
<center><h1>Create a League</h1></center>
<center>
<div class="form" style= "width:500px; height:200px; background-color:gray; ">
<form action="createleaguevalidation.php" method="POST">
League Name: <input style="margin-left:0px;" type="text" name="leaguename" value="<?=$leaguename?>" /><br />
Number of Members: <input type="text" name="members" value="<?=$members?>"/><br>
League Password: <input type="password" name="leaguepassword" value="<?=$leaguepassword?>"><br>
<input type="submit" value="Create League" name="action">
<input type="reset" value="Reset">
</form>
<div style="background-color:#ffcccc; height:80px; width:500px;">
<?=$errors?>
</div>
</div>
<center>
</body>
</html>

If this code isn't inside a loop, then break is an error.

Your code is fine, just take out break;
To break the loop, put break; at the end of all the if statements.

Related

Can I handle a form with php if else statement in action attribute of HTML form?

I am writing a form to create a login username and password.
If the account creation is successful, I would like the user to then be taken to the actual LOGIN form.
I have created a series of checks with the variable $errcheck being passed so the program knows what to do. If there is an error, $errcheck will be set to 1. Its default is 0.
If there are errors in the input fields, the account creation form will be displayed again and if everything is fine then it will INSERT user details into the table and take the user to the LOGIN page.
However, I can only get the page to reload itself each time after the info is added to the table. Is what I'm doing with the action part of the form even allowed? I went ahead and included all of my code in case there were any questions about it. Thank you.
<!DOCTYPE html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$busow_namef = $busow_namel= $owner_email = $bus_psswd = $psswd_confirm = "";
$busname_ERR = $busowname_ERR = $owneremail_ERR = $psswd_ERR =
$psswdconfirm_ERR = "";
$errcheck = 0;
if ($_SERVER["REQUEST_METHOD"]=="POST") {
//??????????????????? Check Login information ???????????????????
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["busow_namef"])) {
$busowname_ERR = "Business owner's name is required";
$errcheck = 1;
} else {
$busownamef = test_input($_POST["busow_namef"]);
}
if (empty($_POST["busow_namel"])) {
$busowname_ERR = "business owner's name is required";
$errcheck = 1;
} else {
$busownamel = test_input($_POST["busow_namel"]);
}
if (empty($_POST["bus_psswd"])) {
$psswd_ERR = "You must enter a password.";
$errcheck = 1;
} else if ((mb_strlen($_POST["bus_psswd"])) < 8) {
$psswd_ERR = "The password must be 8-10 characters long and only include numbers and letters.";
$errcheck = 1;
} else {
$bus_psswd = test_input($_POST["bus_psswd"]);
}
if (empty($_POST["psswd_confirm"])) {
$psswdconfirm_ERR = "Please confirm password.";
$errcheck= 1;
} else if ($_POST["psswd_confirm"] != $_POST["bus_psswd"]) {
$psswdconfirm_ERR = "The passwords do not match.";
$errcheck = 1;
} else {
$psswd = test_input($_POST["psswd_confirm"]);
$h_psswd = password_hash($psswd, PASSWORD_DEFAULT);
}
if (empty($_POST["tandc"])) {
$checktandc_ERR= "You must accept the terms and conditions.";
$errcheck= 1;
} else {
$tandc = test_input($_POST["tandc"]);
}
if (empty($_POST["owner_email"])) {
$owneremail_ERR = "Please enter an email address.";
$errcheck = 1;
} else {
$_POST["owner_email"] = (filter_var($_POST["owner_email"], FILTER_SANITIZE_EMAIL));
}
if (filter_var($_POST["owner_email"] , FILTER_VALIDATE_EMAIL)){
$owneremail = $_POST["owner_email"];
} else {
$owneremail_ERR = "Please enter a valid email address.";
$errcheck = 1;
}
//???????????????? Connect to database ??????????????????????????
$link = mysqli_connect('domain', 'user', 'passwd');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db(database, $link);
if (!mysqli_select_db(louisville_ky1, $link)) {
echo "database not selected";
} else {
$sql = "SELECT owner_email FROM 3bus_owners WHERE owner_email = '$owneremail' ";
$result = mysql_query($sql, $link);
if (mysql_num_rows($result) > 0 ) {
$errcheck = 1;
$owneremail_ERR = "This email is already registered. Please register with another address or click login.";
} else {
$errcheck = 0;
$query = "INSERT INTO 3bus_owners (owner_email, h_psswd, busow_namef, busow_namel) VALUES ('$owneremail', '$h_psswd', '$busownamef',
'$busownamel')";
$result2 = mysql_query($query, $link);
} //end if num rows >0
}//end connection check
} // ???????????????????? end if server request method ????????????????
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php if ($errcheck = 1) { echo
htmlspecialchars($_SERVER["PHP_SELF"]);
} else { echo 'ownersignin.php'; }?>">
Business Owner's Name:<br>
First Name:<br><input type="text" name="busow_namef" value="<?php echo
$busow_namef;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Last Name:<br><input type="text" name="busow_namel"value="<?php echo
$busow_namel;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Business Owner's E-mail: *this will be your username for login and does not have to be posted in listing
<br>
<input type="text" name="owner_email" size="40"value="<?php echo
$owner_email;?>">
<span class="error">*<?php echo $owneremail_ERR;?></span>
<br><br>
Password: <input type="password" name="bus_psswd" size="11" maxlength="10">
<span class="error">*<?php echo $psswd_ERR;?></span>
<br>
Confirm Password: <input type="password" name="psswd_confirm" size="11" maxlength="10">
<span class="error">*<?php echo $psswdconfirm_ERR;?></span>
<br>
<br>
<input type="checkbox" name="tandc">I have read and accept the
<a href="/termsandconditions.php" target= "_blank">Terms and
Conditions</a>.
<span class="error">*<?php echo $checktandc_ERR;?></span>
<br>
<br>
<input type="submit" name="submit" value="Create Login">
</form>
</body>
snippit from above:
<form method="post" action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["PHP_SELF"]); } else { echo 'ownersignin.php'; }?>">
I have never seen a form action attribute written like this, but... try changing the "double quotes" around "PHP_SELF" to single quotes: $_SERVER['PHP_SELF']. That could be causing a problem because it might be getting interpreted as:
action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["
Then, verify that this code sample didn't come from the page: "ownersignin.php". It just sounds like that would be the name of this page instead of the name of the page the form would redirect to.
echo 'ownersignin.php';
If this is the name of the page your code is in, it would send you in an infinite loop.
You shouldn't reprint the registration form when the registration is successful. Instead, redirect the user to the signin form.
After all the validation checks, do:
if (!$errcheck) {
header("Location: ownersignup.php");
exit;
}
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
...

PHP Insert into MySQL Database doesn't work

I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/> 
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";

How do i verify query record with form input

In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance

PHP function showing blank screen?

I am copying a youtube video tutorial for private messaging. The rest of the tutorial works fine, but as soon as I add this function to my site, my entire site goes blank and nothing is shown? No errors or anything, just a white screen? Have I done something wrong here? Here is the function:
<?php
function fetch_user_ids($usernames){
foreach ($usernames as &$name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
$names = array();
while (($row = mysql_fetch_assoc($result)) !== false){
$names[$row['username']] = $row['userid'];
}
return $names;
}
?>
Here is the script to send the information:
<?php
if (isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if (empty($_POST['to'])){
$errors[] = 'You must enter atleast one name.';
}else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
}else{
$usernames = explode(',', $_POST['to']);
foreach ($usernames as &$name){
$name = trim($name);
}
$user_ids = fetch_user_ids($usernames);
if (count($user_ids) !== count($usernames)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($usernames, array_keys($user_ids)));
}
}
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty';
}
if (empty($_POST['body'])){
$errors[] = 'You body must have some text!';
}
if (empty($errors)){
//Send message
}
}
if (isset($errors)){
if (empty($errors)){
echo '<div class="msg success">Your message has been sent ! return</div>';
}else{
foreach ($errors as $error){
echo '<div class="msg error">', $error, '</div>';
}
}
}
?>
<form action="" method="POST">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" />
</div>
<div>
<textarea name="body" rows="10" cols="110"></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</form>
If I take away the "function" part, I can print the data, so it must be something to do with the function element?
I would suggest changing the !== to != and seeeing if that works, it could be interpreting it has a number and not as a bool
Make it simpler. Inside foreach, get rid of &$name and replace it with $name. Also check if your database is returning nothing.
foreach ($usernames as $name){
$name = mysql_real_escape_string($name);
}
$result = mysql_query("SELECT `userid`, `username` FROM `users` WHERE `username` IN ('" . implode("', '", $usernames) . "')");
// Check if the query itself is failing or not here:
if(!$result) die("Failed to perform query");
$names = array();
// Check if the database is returning any rows or not:
print_r(mysql_num_rows($result));
while($row = mysql_fetch_assoc($result)){
$names[$row['username']] = $row['userid'];
}
return $names;

Unable to submit form, Just hit First Validation Error

When i submit my form i just hit my first validation error. No data ever posts.
I'm new to all this stackOverflow stuff and new to all the database scene. To get what I've got i used some TUT's and Books.
Hope someone can help me.
$itemid = $_GET['page_id'];
$itemid = mysql_real_escape_string($itemid);
//get data from database that needs editing
$sql = mysql_query("SELECT * FROM content WHERE `page_id`='{$itemid}'")or die(mysql_error());
//if(!$sql) die ("Database access failed" . mysql_error());
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($pagetitle)) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit
//input validation checks input not empty
if (isset($error['page_title'])) {
echo "<p><span class=\"warning\">" . $error['page_title']."</span><p> ";
}
if (isset($error['page_content'])) {
echo "<p><span class=\"warning\">" . $error['page_content']."</span><p> ";
}
?>
<div>
<?php while ($row = mysql_fetch_object($sql)) { ?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<input type="hidden" name="page_id" value="<?php echo $row->page_id; ?>" />
<div class="edit-title">
<h2><label>Page Title</label></h2>
<p><textarea name="page_title"><?php echo $row->page_title; ?></textarea></p>
</div><!-- end edit title -->
<div class="edit-content">
<h2><label>Page Content</label></h2>
<p><textarea name="page_content"><?php echo $row->page_content; ?></textarea></p>
</div><!-- end edit content -->
<div class="submit-form">
<input type="submit" name="submit" value="Update" />
</div>
</form>
<?php } ?>
</div>
You check if $pagetitle exists but you don't initialize it, you should have put :
if(empty($_POST['page_title'])) { ... }
EDIT :
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($_POST['page_title'])) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit

Categories