Adding multiple checkbox items to database - php

I am new to php/mysql and I am learning quite a bit. I have hit a snag with my checkboxes.
I have looked and everything I have come across is not making sense to me.
Pretty much I am doing a site where the admin can add a user and there are checkboxes that will say what the user is interested in. (more than one can be selected.
Example
Interested in what sports. (these are checkboxes users can select)
Baseball
Football
Hockey
and so on
How can I have it where the choices are stored in the database?
Here is what I have so far.
HTML
<div class="col-md-8">
<label style="margin-right:10px; width:130px"><input name="interested[]" type="checkbox" value="a6"><span class="cats">Baseball</span></label>
<label style="margin-right:10px; width:130px"><input name="interested[]" type="checkbox" value="a6"><span class="cats">Football</span></label>
<label style="margin-right:10px; width:130px"><input name="interested[]" type="checkbox" value="a6"><span class="cats">Hockey</span></label>
</div>
PHP
<?php
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
// Pick up the form data and assign it to variables
$id = #$_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$altemail = $_POST['altemail'];
$notes = $_POST['notes'];
$company = $_POST['company'];
$address = $_POST['address'];
$home = $_POST['home'];
$cell = $_POST['cell'];
$telephone = $_POST['telephone'];
$category = $_POST['category'];
$usertype = $_POST['usertype'];
$assigned = $_POST['assigned'];
$othercat = $_POST['othercat'];
$interested=$_POST['interested'];
//Get data in local variable
$id = #$_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$altemail = $_POST['altemail'];
$notes = $_POST['notes'];
$company = $_POST['company'];
$address = $_POST['address'];
$home = $_POST['home'];
$cell = $_POST['cell'];
$telephone = $_POST['telephone'];
$category = $_POST['category'];
$usertype = $_POST['usertype'];
$assigned = $_POST['assigned'];
$othercat = $_POST['othercat'];
$interested=$_POST['interested'];
// You have to loop through the array of checked box values ...
$interested="";
foreach($interested as $entry){
$interested .= $entry.",";
}
if ($fname=="" || $email=="")
{
echo "All fields must be entered, hit back button and re-enter information";
}else{
$query="INSERT INTO users(`id`, `fname`, `lname`, `email`, `notes`,`company`,`address`,`cell`,`home`,`telephone`,`category`,`usertype`,`assigned`,`altemail`,`othercat`,`interested`) VALUES('$id','$fname','$lname','$email','$notes','$company','$address','$telephone','$category','$usertype','$assigned','$altemail','$othercat','$cell','$home','$interested')";
Like I mentioned, I am brand new to PHP/Mysql. I have only been doing it for about 8 days now. I have come quite a ways with it but this has me stumped.
Any help would be appreciated. Not trying to put myself down, but with all the others that I have looked at and no being able to grasp, please kind of dumb it down for me.
Thanks in advance.

Related

How to end PHP process if variable is blank/null

I have a form submission page that POSTS the fields to a confirmation page that sends an email using PHP but I keep getting blank emails when the page is ran as a stand alone page instead of from the form submission page. The form has 'required', but I want to add a statement to the PHP that stops the process if the $email variable is blank/null.
<?php
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = "Thank you for registering you team";
$message = "<html>...
In addition to stopping the process if the $email variable is blank/null, I also want to redirect the user to our home page.
You should be able to do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = 'Thank you for registering you team';
$message = '<html>...';
} else {
header('Location: https://example.com');
}
Simplest way:
...
// variables end
if( ! (!isset($email) || trim($email) === '') ){
header("Location: homepage.php");
exit();
}
// email start
...
Note the exit() statement after the redirection: without exit() or die() the PHP script could be continue the execution resulting in possible unexpected behaviour.

PHP error posting form data to database

I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....

Post Form data to Update MySQL get 500 Server Error

I am trying to put together a form that is populated from data in a MySQL. Then I want to allow the visitor to change information in that form and by pressing a button, update the database with the new information. This is going to be used by only about 700 people or less to update their member information and access to the form will be through an email that the member gets, so it doesn't have to be a bullet proof system.
I am giving the member a link that displays their member information (that part works) It is just when I attempt to send them to the last page that would do the update is where I get the 500 Server Error. Here is some of my code from the form for them to update. It populates the fields from the database and allows the member to edit the field :
<form name="update" action="submitupdate.php" method="POST" />
<input type="hidden" name="id" value="<?=$record['id']?>"
<tr><b>Business Name: </b></br><input type="text" size="55" name="business_name" value="<?=$record['business_name']?>" ></tr></br></br>
Here is my submitupdate.php (That I get the 500 Server error on):
$con = mysql_connect("lxxxxx", "xxxxxx", "xxxxx");
mysql_select_db("xxxxxx", $con);
if(!$con){
die("Can not connect " . mysql_error());
}
$id = $_POST['id'];
$business_name = $_POST['business_name'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$website = $_POST['website'];
$contact = $_POST['contact'];
$email = $_POST['email'];
if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]', email='$_POST[email]', update_flag='$_POST[update_flag]', WHERE id='$id'";
mysql_query($UpdateQuery, $con);
$retval = mysql_query($UpdateQuery, $con);
if ($retval )
{
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);
while($record = mysql_fetch_array($my_Data)) {
?>
</br>
Then I just want to display the updated record
<tr><b>Business Name: </b></br><input type="text" size="55" name="business_name" value="<?=$record['business_name']?>" ></tr></br></br>
<tr><b>Phone: </b></br><input type="text" size="55" name="phone" value="<?=$record['phone']?>" > </tr></br></br>

Run multiple variables through the same function

This is the first time I have been dumbfounded on what to search for to find my answer. I generally don't ever create a post because there are umpteen thousand posts on the internet with my answer; certainly this is no exception. My problem with finding the answer is, I'm not quite sure what to even search for.
The below code works. That's not the problem. My problem is, what if I wanted to run this one thousand times. Surely I do not need to write this entire expression so many times to get the desired affect do I?
I have a feeling it has to do with an array, but I'm still at a point where I understand arrays one day and the next they are greek.
But anyway, long post for a simple question. Hopefully someone can help me out with this.
This is PHP.
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
This is the entire page:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
And the class:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
I don't know what are you want, but maybe:
$values = array("firstname", "lastname", "email", "password1", "password2");
foreach($values AS $value) {
$$value = $validate->stripExcess($$value);
}
Yes. If you have quite a few variables you can use an array of variables. Basically, the array is a very common structure in PHP. When you get values from $_GET and $_POST you also work with arrays. Nested Arrays and Arrays of objects, Nested arrays of objects all of these are widely used in php.
Try to var_dump $_GET and $_POST (when you send some values to the server) and analyze how the are formed when they have values.

Can only create a new user when a current user is signed in

So I am creating a forum and currently working on the sign up script. I have the sign up form in the signup.php page and the processing part in the signup_process.php
I have an issue where only a current user is able to sign up a new user when they are signed in, any suggestions on how to fix this. I am not able to sign up a new user when I am not logged in as a current one.
Below is my signup_process.php page:
<?php
include "includes/pagetop.php";
include "includes/header.php";
include "includes/nav.php";
?>
<?php
$_SESSION['username'] = $_POST['username'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['surname'] = $_POST['surname'];
$_SESSION['dob'] = $_POST['dob'];
$_SESSION['emailaddress'] = $_POST['emailaddress'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['gender'] = $_POST['gender'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['sports'] = $_POST['sports'];
$username = $_POST['username'];
$fname = $_POST['fname'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
$city = $_POST['city'];
$query = "INSERT INTO user
(
user_username,
user_firstname,
user_surname,
user_dob,
user_email,
user_password,
user_gender,
user_city,
user_active
)
VALUES(
'".$_POST['username']."',
'".$_POST['firstname']."',
'".$_POST['surname']."',
'".$_POST['dob']."',
'".$_POST['email']."',
'".$_POST['password']."',
'".$_POST['gender']."',
'".$_POST['city']."',
'1'
) ";
mysql_query($query) or die (mysql_error());
$lastid = mysql_insert_id();
$sports = $_POST['sports'];
foreach ($sports as $key => $value){
$query2 = " INSERT INTO usersport
(
usersport_user_id,
usersport_sport_id
)
VALUES(
'".$lastid."',
'".$value."'
)";
mysql_query($query2) or die (mysql_error());
}
?>
If you are talking about inserting duplicate users, you could solve this making on the database a primary key on username and an unique index on emailaddress.
If you are talking about the sign up page being served while a user is currently authenticated, you could create a session variable that is set to true when the current user authenticates into the system. Them you could check if this variable is false to serve the sign up page, or give a error otherwise.
And you have a sql injection vulnerability in your code, you should consider using prepared statements instead of plain text.

Categories