Jump to content

Radio Button not working/ inserting image help [Solved]


Recommended Posts

I have a hard time trying to make my radio buttons work. I know that radio buttons are a special case whereby if the user did not click on them, the value will not be taken in. Thus, i have made all my radio buttons to be set per group. However, i can't seem to get the validating right.

This is my current validating code as of now:

	if ((isset($data['specialization']) && $data['specialization'] = "specialization_1")) {		$data['specialization'] = "IS";		 $skillset =($data['ISgrp1'].",".$data['ISgrp2'].",".$data['ISgrp3'].",".$data['ISgrp4'].",".$data['ISgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] = "specialization_2")) {		 $data['specialization'] = "IM";		 $skillset = ($data['IMgrp1'].",".$data['IMgrp2'].",".$data['IMgrp3'].",".$data['IMgrp4'].",".$data['IMgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] = "specialization_3")) {		 $data['specialization']= "CNET";		 $skillset = ($data['CNETgrp1'].",".$data['CNETgrp2'].",".$data['CNETgrp3'].",".$data['CNETgrp4'].",".$data['CNETgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] = "specialization_4")) {		 $data['specialization'] = "ITSM";		 $skillset = ($data['ITSMgrp1'].",".$data['ITSMgrp2'].",".$data['ITSMgrp3'].",".$data['ITSMgrp4'].",".$data['ITSMgrp5']);		}		

I have set my specialization radio group to correspond together with my $skillset. However, my $specialization is somehow always set to "ITSM" although I click on IS" and $skillset is showing only ",,,," in the database. (it used to be nothing as i have to declare $skillset = "" for they can't read my $skillset inside the {} , I'm not sure what i have done to the piece of code o.o).

 

I've heard about imploding (since it's in an array), and this is what I came up with:

	//assign skillsets based on the specialization	if (!$data['specialization'] = "" && isset($data['specialization'])) {		if ($data['specialization']= "specialization_1") {			$data['specialization'] = "IS";		 $skillset = (implode(",",($data['ISgrp1']).",".($data['ISgrp2']).",".($data['ISgrp3']).",".($data['ISgrp4']).",".($data['ISgrp5'])));		}		if ($data['specialization']= "specialization_2") {		 $data['specialization'] = "IM";		 $skillset = (implode(",",($data['IMgrp1']).",".($data['IMgrp2']).",".($data['IMgrp3']).",".($data['IMgrp4']).",".($data['IMgrp5'])));		}		if ($data['specialization']= "specialization_3") {		 $data['specialization']= "CNET";		 $skillset = (implode(",",($data['CNETgrp1']).",".($data['CNETgrp2']).",".($data['CNETgrp3']).",".($data['CNETgrp4']).",".($data['CNETgrp5'])));		}		if ($data['specialization']= "specialization_4") {		 $data['specialization'] = "ITSM";		 $skillset = (implode(",",($data['ITSMgrp1']).",".($data['ITSMgrp2']).",".($data['ITSMgrp3']).",".($data['ITSMgrp4']).",".($data['ITSMgrp5'])));		}			}

However, they are showing undefined $skillset and the $data[''] inside the $skillset. Please tell me where i've gone wrong, I have been searching for some examples but the examples are only those with male/female gender type of option (simple type). Why is it that they can't get the $skillset defined in that validation? Also, can someone give me a link to a good image uploading tutorial? I can't seem to get it right as it always goes to a blank page when i hit the submit><

This is my page(my html form and my php codes ): addProfile.php

Edited by Silence~
Link to post
Share on other sites

The if conditions are currently setting variable when using a single '=' they not comparing when they should be using double '==' to compare value or triple '===' to compare value and type.

I actually used the '==' but they do not take in the value(?), the word "array" is inserted into my database and not the value. Same for the '===' although I do not think the type matters in this case since they are a radio button group ><

Link to post
Share on other sites

I know that radio buttons are a special case whereby if the user did not click on them, the value will not be taken in.

You can use a hidden type input using same name attribute value placed above radio type inputs to give you a default value, when radio button selected it will be overridden by it value.
Link to post
Share on other sites

What are $data and $skillset, how do you use $skillset?

the word "array" is inserted into my database and not the value.

That happens when you try to use an array as a single value, you're not doing something right. You should show the code where that happens.As far as blank pages go, that's usually a fatal error that is going to a log or something instead of being displayed. If you're testing this on your own server then I would recommend going through php.ini and looking at the various config options, especially the options for error reporting. When you're developing it's common to set display_errors to 1 or on with error_reporting set to E_ALL. You don't want to hide error messages, you want to show them so you can fix them. You could also use the error logging settings to log all errors if you'd rather check a log file than see the error messages in the browser. You need to find the error messages though, you can't fix problems otherwise. To change error settings at runtime for a single script you can use ini_set and error_reporting, e.g.:
ini_set('display_errors', 1);error_reporting(E_ALL);
Link to post
Share on other sites

You can use a hidden type input using same name attribute value placed above radio type inputs to give you a default value, when radio button selected it will be overridden by it value.

I'm not sure if I understand but this is so I do not need to "checked" every one radio button of the group, am I right?

 

 

What are $data and $skillset, how do you use $skillset?That happens when you try to use an array as a single value, you're not doing something right. You should show the code where that happens.As far as blank pages go, that's usually a fatal error that is going to a log or something instead of being displayed. If you're testing this on your own server then I would recommend going through php.ini and looking at the various config options, especially the options for error reporting. When you're developing it's common to set display_errors to 1 or on with error_reporting set to E_ALL. You don't want to hide error messages, you want to show them so you can fix them. You could also use the error logging settings to log all errors if you'd rather check a log file than see the error messages in the browser. You need to find the error messages though, you can't fix problems otherwise. To change error settings at runtime for a single script you can use ini_set and error_reporting, e.g.:

ini_set('display_errors', 1);error_reporting(E_ALL);

 

$data is actually an array for all my inputs to put through. It's just to trim all inputs actually.

$data = array();//array_map('trim',$_POST); array_walk_recursive($data,'trim'); 

$Skillset is a new variable that I declare where I want to assign to the selected radio group set, meaning if I chose specialization "IS", the radio buttons that are based on "IS" is the one I wanted to store in the database. I would like to clarify something though: radio buttons will store in the values am I right? If I did not declare the $data['specilaization'] inside the validation bracket (my first post), the id will be taken to store in the database. I am not sure what you meant by this: "That happens when you try to use an array as a single value, you're not doing something right. You should show the code where that happens. " Did this happen because I declare i declare the $data['specialization'] instead of getting the actual value? Now, it gives me undefined index for all the rows inside the $skillset. I'm kind of bummed now. Am i not suppose to use implode? How do i use implode in this case? ><

Link to post
Share on other sites

I am not sure what you meant by this: "That happens when you try to use an array as a single value, you're not doing something right. You should show the code where that happens. "

This is what I mean:
$ar = array(1, 2, 3);echo 'The array is ' . $ar;
That's going to print "The array is Array". When you try to use an array in a string, like a database query, it just uses the word "Array". So if your query has "Array" in it then that's what you're doing wrong. You didn't show the code that inserts data in the database though, so I don't know how the code you did show fits in. Where is the rest of your code?

Am i not suppose to use implode?

There aren't rules like that. You can use implode wherever you want, if using implode is the right thing to do. Why do you think you need to use it? Do you have an array of values that you're trying to join? You didn't use it correctly above, because you didn't pass it an array of values, you passed it 2 strings. Instead of asking if you're not supposed to use it, ask why you think you need to use it. If you can't answer that then you probably don't need to use it. Don't just try things without understanding what you're doing, if you're programming you need to understand what you're doing and why you're doing it. Look things up in the manual if you have questions about how they work.And make sure you're using the correct operators. In your original code it is not correct to use = inside those if statements.http://php.net/manual/en/language.operators.comparison.phpAlso, instead of a series of if statements which all check the same variable, you could use a switch statement instead.http://php.net/manual/en/control-structures.switch.php
Link to post
Share on other sites

This is what I mean:

$ar = array(1, 2, 3);echo 'The array is ' . $ar;
That's going to print "The array is Array". When you try to use an array in a string, like a database query, it just uses the word "Array". So if your query has "Array" in it then that's what you're doing wrong. You didn't show the code that inserts data in the database though, so I don't know how the code you did show fits in. Where is the rest of your code?

Okay, I somewhat get what you mean by this but I don't think this is what I have in mind. I have about 12 radio groups and I thought using $_POST['radiobutton_groupname'] would already take in the value?(i declare this inside $data['radiobutton_groupname'] = $_POST['radiobutton_groupname']) I'm not sure why I would have to create this array when it will automatically get the value. But if this is the only way, i will post my codes later after i try implementing this.

My codes before the insert query you see below(this is also what i meant by the $_POST['radiobutton_groupname']):

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {		// array to hold errors        $errors = array(); 		// copy and trim all post data (if the form has any arrays, you need to use a function like array_walk_recursive() instead of array_map())		//variables here 		$data = array();//array_map('trim',$_POST); 		array_walk_recursive($data,'trim');          <-------------------cut out unneccessary codes----------------------------->        // if no errors at this point, continue with validation        if(empty($errors)){        // all your form field validation code would go here, using elements in the $data array (a trimmed copy of the $_POST data) //validate here after declaring them		 <-------cut out unneccessary codes of other inputs------------>		 //taking relevant data only, below is all the radio buttons		 $data['specialization'] = $_POST['specialization'];    		 $data['ISGrp1'] = $_POST['ISgrp1'];		 $data['ISGrp2'] = $_POST['ISgrp2'];		 $data['ISGrp3'] = $_POST['ISgrp3'];		 $data['ISGrp4'] = $_POST['ISgrp4'];		 $data['ISGrp5'] = $_POST['ISgrp5'];		 $data['IMGrp1'] = $_POST['IMgrp1'];		 $data['IMGrp2'] = $_POST['IMgrp2'];		 $data['IMGrp3'] = $_POST['IMgrp3'];		 $data['IMGrp4'] = $_POST['IMgrp4'];		 $data['IMGrp5'] = $_POST['IMgrp5'];		 $data['CNETGrp1'] = $_POST['CNETgrp1'];		 $data['CNETGrp2'] = $_POST['CNETgrp2'];		 $data['CNETGrp3'] = $_POST['CNETgrp3'];		 $data['CNETGrp4'] = $_POST['CNETgrp4'];		 $data['CNETGrp5'] = $_POST['CNETgrp5'];		 $data['ITSMGrp1'] = $_POST['ITSMgrp1'];		 $data['ITSMGrp2'] = $_POST['ITSMgrp2'];		 $data['ITSMGrp3'] = $_POST['ITSMgrp3'];		 $data['ITSMGrp4'] = $_POST['ITSMgrp4'];		 $data['ITSMGrp5'] = $_POST['ITSMgrp5'];//$data['skillset'] =  "";$skillset = "";<--------------cut out unneccessary codes of other inputs-------------->//tried this out yesterday but they could find the variable declared//check if specialization is not checked (use the hidden input to access this)if ($data['specialization'] == "false") {$errors[] = ("Please select your specialization! Specialization is required!");}//	    //validate for IS//	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_1')) {//		//$data['specialization'] = "IS";//		if (($data['ISgrp1'] == "false") || ($data['ISgrp2'] == "false") || ($data['ISgrp3'] == "false") || ($data['ISgrp4'] == "false") || ($data['ISgrp5'] == "false")) {//			$errors[] = ("Please select your skillsets!");//		}//		else {//		//set them to $skillset//		 $skillset = array_merge($data['ISgrp1'],$data['ISgrp2'],$data['ISgrp3'],$data['ISgrp4'],$data['ISgrp5']);//		// $skillset = ($data['ISgrp1'].",".$data['ISgrp2'].",".$data['ISgrp3'].",".$data['ISgrp4'].",".$data['ISgrp5']);//		}//		}//		//validate for IM//	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_2')) {//		//$data['specialization'] = "IM";//		if (($data['IMgrp1'] == "false") || ($data['IMgrp2'] == "false") || ($data['IMgrp3'] == "false") || ($data['IMgrp4'] == "false") || ($data['IMgrp5'] == "false")) {//			$errors[] = ("Please select your skillsets!");//		}//		else {//		//set them to $skillset//		 $skillset = array_merge($data['IMgrp1'],$data['IMgrp2'],$data['IMgrp3'],$data['IMgrp4'],$data['IMgrp5']);//		// $skillset = ($data['IMgrp1'].",".$data['IMgrp2'].",".$data['IMgrp3'].",".$data['IMgrp4'].",".$data['IMgrp5']);//		}//		}//		//validate for CNET//	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_3')) {//		// $data['specialization']= "CNET";//		if (($data['CNETgrp1'] == "false") || ($data['CNETgrp2'] == "false") || ($data['CNETgrp3'] == "false") || ($data['CNETgrp4'] == "false") || ($data['CNETgrp5'] == "false")) {//			$errors[] = ("Please select your skillsets!");//		}//		else {//		 $skillset = array_merge($data['CNETgrp1'],$data['CNETgrp2'],$data['CNETgrp3'],$data['CNETgrp4'],$data['CNETgrp5']);//		// $skillset = ($data['CNETgrp1'].",".$data['CNETgrp2'].",".$data['CNETgrp3'].",".$data['CNETgrp4'].",".$data['CNETgrp5']);//		}//		}//		//Check for ITSM//	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_4')) {//		 //$data['specialization'] = "ITSM";//		if (($data['ITSMgrp1'] == "false") || ($data['ITSMgrp2'] == "false") || ($data['ITSMgrp3'] == "false") || ($data['ITSMgrp4'] == "false") || ($data['ITSMgrp5'] == "false")) {//			$errors[] = ("Please select your skillsets!");//		}//		else {		 //		 $skillset = array_merge($data['ITSMgrp1'],$data['ITSMgrp2'],$data['ITSMgrp3'],$data['ITSMgrp4'],$data['ITSMgrp5']);//		 //$skillset = ($data['ITSMgrp1'].",".$data['ITSMgrp2'].",".$data['ITSMgrp3'].",".$data['ITSMgrp4'].",".$data['ITSMgrp5']);//		}//		}					  <---codes before any changes--->	  //	//assign skillsets based on the specialization//	if (!$data['specialization'] = "" && isset($data['specialization'])) {//		if ($data['specialization']== "specialization_1") {//			$data['specialization'] = "IS";//		 $skillset = (implode(",",($data['ISgrp1']).",".($data['ISgrp2']).",".($data['ISgrp3']).",".($data['ISgrp4']).",".($data['ISgrp5'])));//		}//		if ($data['specialization']== "specialization_2") {//		 $data['specialization'] = "IM";//		 $skillset = (implode(",",($data['IMgrp1']).",".($data['IMgrp2']).",".($data['IMgrp3']).",".($data['IMgrp4']).",".($data['IMgrp5'])));//		}//		if ($data['specialization']== "specialization_3") {//		 $data['specialization']= "CNET";//		 $skillset = (implode(",",($data['CNETgrp1']).",".($data['CNETgrp2']).",".($data['CNETgrp3']).",".($data['CNETgrp4']).",".($data['CNETgrp5'])));//		}//		if ($data['specialization']== "specialization_4") {//		 $data['specialization'] = "ITSM";//		 $skillset = (implode(",",($data['ITSMgrp1']).",".($data['ITSMgrp2']).",".($data['ITSMgrp3']).",".($data['ITSMgrp4']).",".($data['ITSMgrp5'])));//		}		//	}        //try without implode	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_1')) {		$data['specialization'] = "IS";		 $skillset = ($data['ISgrp1'].",".$data['ISgrp2'].",".$data['ISgrp3'].",".$data['ISgrp4'].",".$data['ISgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_2')) {		 $data['specialization'] = "IM";		 $skillset = ($data['IMgrp1'].",".$data['IMgrp2'].",".$data['IMgrp3'].",".$data['IMgrp4'].",".$data['IMgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_3')) {		 $data['specialization']= "CNET";		 $skillset = ($data['CNETgrp1'].",".$data['CNETgrp2'].",".$data['CNETgrp3'].",".$data['CNETgrp4'].",".$data['CNETgrp5']);		}	if ((isset($data['specialization']) && $data['specialization'] == 'specialization_4')) {		 $data['specialization'] = "ITSM";		 $skillset = ($data['ITSMgrp1'].",".$data['ITSMgrp2'].",".$data['ITSMgrp3'].",".$data['ITSMgrp4'].",".$data['ITSMgrp5']);		}		

 

 

My insert data goes like this(after doing all validation):

        // done with validation, if no errors, use the data -        if(empty($errors)){            // your code to insert the data and move the uploaded file would go here...			$stmt = $database->prepare("INSERT INTO userProfile (username, Name, introduction, Specialization,skillset, Email, ContactNo, user_Id) VALUES 	  (:username,:Name,:introduction,:Specialization,:skillset,:Email,:ContactNo,:user_Id)");//$stmt->bindValue(':picName',$_FILES['image']['name']);//$stmt->bindValue(':picPath', $imgDir);$stmt->bindValue(':username',$data['username']);$stmt->bindValue(':Name', $data['name']);$stmt->bindValue(':introduction',$data['introduction']);$stmt->bindValue(':Specialization',$data['specialization']);$stmt->bindValue(':skillset',$skillset);$stmt->bindValue(':Email',$data['email']);$stmt->bindValue(':ContactNo',$data['contactNo']);$stmt->bindValue(':user_Id',$_SESSION['user_id']);$stmt->execute();        }       // if no errors at this point, redirect to the exact same url of this page to prevent the browser from resubmitting the data by causing a get request for the page        if(empty($errors)){            $host = $_SERVER['HTTP_HOST'];            $uri = $_SERVER['REQUEST_URI'];            header("Location:addProfile.php?success=1");            exit;        }        // if there were errors in any of the above form processing code, continue on this page, displaying any errors, redisplay form, (re)populate the form fields with data...foreach($errors as $error)    {        printf("<li>%s</li>", $error);//exit();    }    } // end of post method form processing        // get method/display code (if any) - get/produce data that's needed to display the page    // to edit existing data, if the $data array is empty at this point, retrieve any existing data from the database table} catch(PDOException $e){ // end of database dependent code, handle any errors    $status = empty($query) ? 'Connection failed':" Query failed: $query";    // application message    trigger_error("$status, Error: {$e->getMessage()}, File: {$e->getFile()}, Line: {$e->getLine()}");    // user message    $errors[] = 'Sorry, this page is not working at this time.';}// done with the database, destroy any pdostatment resource and close connection$stmt = null;$database = null;

 

There aren't rules like that. You can use implode wherever you want, if using implode is the right thing to do. Why do you think you need to use it? Do you have an array of values that you're trying to join? You didn't use it correctly above, because you didn't pass it an array of values, you passed it 2 strings. Instead of asking if you're not supposed to use it, ask why you think you need to use it. If you can't answer that then you probably don't need to use it. Don't just try things without understanding what you're doing, if you're programming you need to understand what you're doing and why you're doing it. Look things up in the manual if you have questions about how they work.

And make sure you're using the correct operators. In your original code it is not correct to use = inside those if statements.http://php.net/manual/en/language.operators.comparison.phpAlso, instead of a series of if statements which all check the same variable, you could use a switch statement instead.http://php.net/manual/en/control-structures.switch.php

 

I believe I do need to implode it because I want to join 4 arrays(radio button groups) into 1(string) to store in one column in the database. What I am confused now is that implode joins all array values in each array, but I do not want that since I only need the value the user click. I will then create a new variable and have the 4 values from those 4 arrays, joining it together and then I can get it to store it in database.

Pardon for my lack of knowledge and thank you for the link. I'll be sure to read it up :)

Link to post
Share on other sites

This is what I have tried using the case statement:

	switch ($data['specialization'] == true) {    case 'specialization_1':	 $data['specialization']= print_r($data['specialization'],true);	 //$data['specialization']= print_r($_POST['specialization'], true);	 //declare skillset	// $skillset = extract($data['ISgrp1'].",".$data['ISgrp2'].",".$data['ISgrp3'].",".$data['ISgrp4'].",".$data['ISgrp5']);	 //$skillset = print_r($_POST['ISgrp1'].",".$_POST['ISgrp2'].",".$_POST['ISgrp3'].",".$_POST['ISgrp4'].",".$_POST['ISgrp5']);	 $skillset = implode(",", $_POST['ISgrp1'] .$_POST['ISgrp1']. $_POST['ISgrp1'] .$_POST['ISgrp1']. $_POST['ISgrp1'] );    case 'specialization_2':	$data['specialization']= print_r($data['specialization'],true);	 //declare skillset	 $skillset = implode(",",$data['IMgrp1'].$data['IMgrp2'].$data['IMgrp3'].$data['IMgrp4'].$data['IMgrp5']);    case 'specialization_3':	 $data['specialization']= print_r($data['specialization'],true);	  //declare skillset	 $skillset = print_r(",",$data['CNETgrp1'].$data['CNETgrp2'].$data['CNETgrp3'].$data['CNETgrp4'].$data['CNETgrp5']);	case 'specialization_4':	 $data['specialization']= print_r($data['specialization'],true);	  //declare skillset	 $skillset = print_r(",",$data['ITSMgrp1'].$data['ITSMgrp2'].$data['ITSMgrp3'].$data['ITSMgrp4'].$data['ITSMgrp5']);	  }

The database now shows that the specialization is Array( [0]=>false, [1]=>IS ) while the skillset column shows 1. The problem is, I choose IS and all "3" for the $skillsets(ISgrp1, ISgrp2,ISgrp3, ISgrp4,ISgrp5). Where am I going wrong? Was it my form or my php? Below is my part of table html for IS :

<!--- Specialization Radio Buttons--->                <td><table width="auto">                    <tr>                      <td>                      <input type="hidden" name="specialization[]" value="false">                      <input name="specialization[]" type="radio" id="specialization_1" value="IS" checked="CHECKED">                        IS</td>                      <td><input type="radio" name="specialization[]" value="IM" id="specialization_2">                        IM</td>                    </tr>                    <tr>                      <td><input type="radio" name="specialization[]" value="CNET" id="specialization_3">                        CNET</td>                      <td><input type="radio" name="specialization[]" value="ITSM" id="specialization_4">                        ITSM</td>                    </tr>                  </table></td><!--- Skillsets Radio Buttons---><!--- IS Radio Buttons Radio Buttons--->                  <tr id="ISrow1">                    <td width="auto"><div align="left">C#</div></td>                    <td width="auto">                    <input type="hidden" name="ISgrp1[]" value="false">                    <label>                        <input name="ISgrp1[]" type="radio" id="IS_table_1" value="C#-0">                        0</label></td>                    <td width="auto"><label>                        <input type="radio" name="ISgrp1[]" value="C#-1" id="IS_table_2">                        1</label></td>                    <td width="auto"><label>                        <input type="radio" name="ISgrp1[]" value="C#-2" id="IS_table_3">                        2</label>                      <label></label></td>                    <td width="auto"><label>                        <input type="radio" name="ISgrp1[]" value="C#-3" id="IS_table_4">                        3</label></td>                    <td width="auto"><label>                        <input type="radio" name="ISgrp1[]" value="C#-4" id="IS_table_5">                        4</label></td>                    <td width="auto"><label>                        <input type="radio" name="ISgrp1[]" value="C#-5" id="IS_table_6">                        5</label></td>                  </tr>                  <tr id="ISrow2">                    <td><div align="left">PHP/SQL</div></td>                    <td>                    <input type="hidden" name="ISgrp2[]" value="false">                    <label>                        <input name="ISgrp2[]" type="radio" id="IS_table_7" value="PHP/SQL-0">                        0</label></td>                    <td><input type="radio" name="ISgrp2[]" value="PHP/SQL-1" id="IS_table_8">                      1</td>                    <td><label>                        <input type="radio" name="ISgrp2[]" value="PHP/SQL-2" id="IS_table_9">                        2</label></td>                    <td><label>                        <input type="radio" name="ISgrp2[]" value="PHP/SQL-3" id="IS_table_10">                        3</label></td>                    <td><label>                        <input type="radio" name="ISgrp2[]" value="PHP/SQL-4" id="IS_table_11">                        4</label></td>                    <td><label>                        <input type="radio" name="ISgrp2[]" value="PHP/SQL-5" id="IS_table_12">                        5</label></td>                  </tr>                  <tr id="ISrow3">                    <td><div align="left">HTML/CSS</div></td>                    <td>                  <input type="hidden" name="ISgrp3[]" value="false">                    <label>                        <input name="ISgrp3[]" type="radio" id="IS_table_13" value="HTML/CSS-0">                        0</label></td>                    <td><input type="radio" name="ISgrp3[]" value="HTML/CSS-1" id="IS_table_14">                      1</td>                    <td><label>                        <input type="radio" name="ISgrp3[]" value="HTML/CSS-2" id="IS_table_15">                        2</label></td>                    <td><label>                        <input type="radio" name="ISgrp3[]" value="HTML/CSS-3" id="IS_table_16">                        3</label></td>                    <td><label>                        <input type="radio" name="ISgrp3[]" value="HTML/CSS-4" id="IS_table_17">                        4</label></td>                    <td><input type="radio" name="ISgrp3[]" value="HTML/CSS-5" id="IS_table_18">                      5</td>                  </tr>                  <tr id="ISrow4">                    <td><div align="left">Java Enterprise Development</div></td>                    <td>                    <input type="hidden" name="ISgrp4[]" value="false">                    <label>                        <input name="ISgrp4[]" type="radio" id="IS_table_19" value="Java Enterprise Development-0">                        0</label></td>                    <td><label>                        <input type="radio" name="ISgrp4[]" value="Java Enterprise Development-1" id="IS_table_20">                        1</label></td>                    <td><input type="radio" name="ISgrp4[]" value="Java Enterprise Development-2" id="IS_table_21">                      2</td>                    <td><label>                        <input type="radio" name="ISgrp4[]" value="Java Enterprise Development-3" id="IS_table_22">                        3</label></td>                    <td><label>                        <input type="radio" name="ISgrp4[]" value="Java Enterprise Development-4" id="IS_table_23">                        4</label></td>                    <td><input type="radio" name="ISgrp4[]" value="Java Enterprise Development-5" id="IS_table_24">                      5</td>                  </tr>                  <tr id="ISrow5">                    <td><div align="left">Mobile Application Development</div></td>                    <td>                    <input type="hidden" name="ISgrp5[]" value="false">                    <label>                        <input name="ISgrp5[]" type="radio" id="IS_table_25" value="Mobile Application Development-0">                        0</label></td>                    <td><label>                        <input type="radio" name="ISgrp5[]" value="Mobile Application Development-1" id="IS_table_26">                        1</label></td>                    <td><input type="radio" name="ISgrp5[]" value="Mobile Application Development-2" id="IS_table_27">                      2</td>                    <td><label>                        <input type="radio" name="ISgrp5[]" value="Mobile Application Development-3" id="IS_table_28">                        3</label></td>                    <td><label>                        <input type="radio" name="ISgrp5[]" value="Mobile Application Development-4" id="IS_table_29">                        4</label></td>                    <td><input type="radio" name="ISgrp5[]" value="Mobile Application Development-5" id="IS_table_30">                      5</td>                  </tr>

That's going to print "The array is Array". When you try to use an array in a string, like a database query, it just uses the word "Array". So if your query has "Array" in it then that's what you're doing wrong. You didn't show the code that inserts data in the database though, so I don't know how the code you did show fits in. Where is the rest of your code?

After googling more ways to make this array to string, I found out that this was due to the changes they made these changes in version 5.4 where the arrays will still be arrays? http://php.net/manual/en/migration54.incompatible.php So, most of the ones that using implode,extract etc are not valid anymore?

Link to post
Share on other sites

radio buttons on submit only send one value only, by using 'ISgrp1[]' (which is usually for checkboxs that accept multiple values) with hidden input you are sending more than one, always 'false' and radio button selected value, by removing '[]' it will send 'false' only if a radio button option is not selected, else the button value itself only.

 

Where is the value of 'specialization_1' coming from? all i see is id ref of that name, which does not get sent only the value is sent on submission.

  • Like 1
Link to post
Share on other sites

First, don't use $data at all, just use $_POST. You don't gain anything by copying everything from $_POST to $data, the only thing you've done is double the memory required to hold it.

//check if specialization is not checked (use the hidden input to access this)

If you want to determine if a checkbox or radio button group was selected or not, then you use isset. If a checkbox or radio button group was not checked then the browser will not submit it at all, so it will not be set in $_POST. It will only be set in $_POST if it was checked, so you can use isset to check if something in $_POST was set or not.http://php.net/manual/en/function.isset.php

I believe I do need to implode it because I want to join 4 arrays(radio button groups) into 1(string) to store in one column in the database.

They should not be submitting arrays, they should be submitting single values. Do not use a hidden input or any other input with the same name as the radio button group, that name should only be for the radio buttons that are part of the group. Like I said, you use isset if you want to check if something was selected, not mess around and try to get clever with hidden inputs. Take the square brackets off the radio group names and just use those names for the radio groups, not any other inputs.

After googling more ways to make this array to string, I found out that this was due to the changes they made these changes in version 5.4 where the arrays will still be arrays? http://php.net/manua...ncompatible.php So, most of the ones that using implode,extract etc are not valid anymore?

That's not what that page says, it just says that trying to convert an array to a string will now emit a notice error, where it did not previously. It still converts to the word "Array".Speaking of notices, you should add this to the top of your code, it might help point to other problems:
ini_set('display_errors', 1);error_reporting(E_ALL);
If you're getting any notices, warnings, etc then those need to be fixed.And, if you want to verify everything that got submitted in the form then you can use var_dump:
echo '<pre>';var_dump($_POST);echo '</pre>';
  • Like 1
Link to post
Share on other sites

There is no reason why a hidden input cannot be used to set default value for radio name group, messing about? You just place hidden input above radio name group, not much messing around there, it would save having to adjust php code to adjust default value which could be more decriptive value than a true/false value used here, you would just adjust hidden value and done!

Link to post
Share on other sites

There is no reason why a hidden input cannot be used to set default value for radio name group

There's no reason to do it.
$val = 'default';if (isset($_POST['radio'])) {  $val = $_POST['radio'];}
That is clear to any programmer what the intent is. This isn't very clear:
if (count($_POST['radio']) > 1) {  $val = $_POST['radio'][1];}else {  $val = $_POST['radio'][0];}
The first version is clearer and shorter (the PHP code is shorter and it does not require the extra HTML markup of a hidden field).

it would save having to adjust php code

It just moves the task from changing the PHP code to changing the HTML markup. It doesn't save anything, it only moves, and it does so with more code that is less clear.
  • Like 1
Link to post
Share on other sites

There is no reason why a hidden input cannot be used to set default value for radio name group, messing about? You just place hidden input above radio name group, not much messing around there, it would save having to adjust php code to adjust default value which could be more decriptive value than a true/false value used here, you would just adjust hidden value and done!

Ah, well this was just a testing out from the previous posts that's been suggested to use >< I have taken that down now and use justsomeguy's example in use. Thank you dsonesuk and justsomeguy! :D I didn't realised that the "[]" in the form plays the part too >< I managed to get them insert to the database now ^^ :good: I shall now work on the images, I will have to post that later after trying it out :)

Edited by Silence~
Link to post
Share on other sites
$val = 'default';if (isset($_POST['radio'])) {  $val = $_POST['radio'];}
Fine if you want to be constrained to default value being equal to 'default' without the flexibility of default value being determined by what is used in hidden input.
if (count($_POST['radio']) > 1) {  $val = $_POST['radio'][1];}else {  $val = $_POST['radio'][0];}
Well this is obsolete because only one value will be posted, the hidden value, if NO radio button is selected OR just the value of selected radio button which WILL take the place of default hidden input.SO recap the only php code involved would be actually
$val = $_POST['radio'];
Which has gone from 6 to 4 to one line of code, with the flexibility to define whatever default value by using a hidden input.
Link to post
Share on other sites

IF you have difficulty getting you head round how the hidden input will work, I've included a little example for you

<!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <form action="#" method="post">            <input type="hidden" name="ISgrp1" value="Hi I'm the default value for ISgrp1,  I am so  flexible because i can be whatever you want compared to default value set by php code on submission">            <label>                <input name="ISgrp1" type="radio" id="IS_table_1" value="C#-0">                0</label>            <label>                <input type="radio" name="ISgrp1" value="C#-1" id="IS_table_2">                1</label>            <label>                <input type="radio" name="ISgrp1" value="C#-2" id="IS_table_3">                2</label>            <label></label>            <label>                <input type="radio" name="ISgrp1" value="C#-3" id="IS_table_4">                3</label>            <label>                <input type="radio" name="ISgrp1" value="C#-4" id="IS_table_5">                4</label>            <label>                <input type="radio" name="ISgrp1" value="C#-5" id="IS_table_6">                5</label>            <input type="submit">        </form>        <?php        echo var_dump($_POST);        ?>    </body></html>
Link to post
Share on other sites

Fine if you want to be constrained to default value being equal to 'default' without the flexibility of default value being determined by what is used in hidden input.

Et voila:
$value = $_POST['radio_default'];

Well this is obsolete because only one value will be posted, the hidden value, if NO radio button is selected OR just the value of selected radio button which WILL take the place of default hidden input.

It will ONLY do THAT if the input NAME does not have THE square brackets AT the end. If the code was given like above then it most definitely will submit as an array.

Which has gone from 6 to 4 to one line of code, with the flexibility to define whatever default value by using a hidden input.

What's the point of "flexibility to define the default value" when the only purpose of the default value in this case is to determine if a radio button was selected? You can leave out the hidden input and just use isset like it's supposed to be used. Or, if you want a default value for a radio button group, then how about making it another radio button that is selected by default? What possible use case requires a hidden input with the same name as a radio button group? If you want to know if a radio button was selected, use isset. If you want a default value, then make a radio button that is selected by default.You're coming up with solutions for problems that don't exist.
Link to post
Share on other sites

It will ONLY do THAT if the input NAME does not have THE square brackets AT the end. If the code was given like above then it most definitely will submit as an array.

I had already established that YOU HAVE TO REMOVE THE SQUARE BRACKETS in post #10, that resulted in Array( [0]=>false, [1]=>IS ) showing 'false' and 'IS' for 'specialization' radio group as shown in post #9.And finally you don't require default selected radio button, you don't require to check if radio has been set, as this will always be set, what is required is the user to actually select radio button so it will override default, you then have the added option in future if required to adjust default value to whatever value you require without the need change php code. You are basically having the same option of setting the default value for other html form elements by setting the value. Edited by dsonesuk
Link to post
Share on other sites

I'm still not hearing a use case for why you would need to do that. If you want a radio group to have a default value, why exactly would you not use a radio button selected by default? If the purpose is not a default value, if the purpose is just to check if they selected any button, then the solution for that is isset. I don't see how adding more HTML markup and more data across the wire is better than a line or two in PHP to check that. Adding a hidden input is also completely unnecessary for Javascript-based validation which still needs to loop over the radio buttons and check them individually, it wouldn't even use the hidden input at all. It's pointless.Like I said, it's a solution in search of a problem.

Link to post
Share on other sites

Because the default value may not be one constant set value, the user DID NOT WANT a default set radio button, and this value could easily be set using php or JavaScript.

 

JavaScript validation? what difference does that make, if there was validation to check if radio button from named group was selected, it can STILL do that.

 

Just because its your method of retrieve/set the default value using php, does not make it de facto ONLY method.

 

I came up with solution, which is valid, flexible on being able to set a default value, which requires no extra coding using isset.

 

Yes! your solution works, mine solution works, i think my method is better cause I have more control of what the default value can be.

Link to post
Share on other sites

So, I tried coding for the image uploading and I have some difficulty on the MIME type. If I did not declare anything of that, I am able to insert to the database(the directory and the name of the file) but the picture would not be inserted to the folder. This are my code:

		//Declare variables and start validation        $fileMaxSize = $_POST['MAX_FILE_SIZE'];	$filename = $_FILES['userfile']['name'];	$filetype = $_FILES['userfile']['type'];	$filesize = $_FILES['userfile']['size'];	$filetmp = $_FILES['userfile']['tmp_name'];	$fileError = $_FILES['userfile']['error'];	$uploaddir = '/profilePics/';	$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);//Check if file is uploaded/issetswitch ($fileError) {	case UPLOAD_ERR_OK:	//no error, so move on to the uploading process	break;	case UPLOAD_ERR_INI_SIZE:  //This is from the php max size	$errors[] = ('The file you attempt to upload exceeds the max size. Please upload a smaller size');	break;	case UPLOAD_ERR_FORM_SIZE: //This is from the html form max size we declared.	$errors[] = ('The file you attempt to upload exceeds the max size. Please upload a smaller size');	break;	case UPLOAD_ERR_PARTIAL:	$errors[] = ('The file is partially uploaded. Please try again.');	break;	case UPLOAD_ERR_NO_FILE: //no file is uploaded	$errors[] = ('File is not uploaded.');	break;	case UPLOAD_ERR_NO_TMP_DIR:	$errors[] = ('Temporary folder is missing or do not exist. Please contact administrator.');	break;	case UPLOAD_ERR_CANT_WRITE:	$errors[] = ('Unable to write into the folder. Please try again.');	break;	case UPLOAD_ERR_EXTENSION:	$errors[] = ('Unable to detect the cause of error. Please try again and if error persist, contact the administrator.');	break;}// if the upload is okay, proceed to move the file.if ($_FILES['userfile']['error'] === UPLOAD_ERR_OK) {       //check if the type is correct	  $finfo = finfo_open(FILEINFO_MIME); // return mime type ala mimetype extension//if not able to return mime typeif (!$finfo) {    $errors[] = ('Opening fileinfo database failed');}/* get mime-type for a specific file *///$filename = "/usr/local/something.txt";if (!finfo_file($finfo, $filename)) {	$errors[] = ('not sure what to do here.');		}else {         move_uploaded_file($filename,$uploadfile);		 }/* close connection */finfo_close($finfo);}//Insert statement after checking if no errors  if(empty($errors)){	$stmt = $database->prepare("INSERT INTO userProfile (picName,picPath,username, Name, introduction, Specialization,skillset, Email, ContactNo, user_Id) VALUES (:picName, :picPath,:username,:Name,:introduction,:Specialization,:skillset,:Email,:ContactNo,:user_Id)");$stmt->bindValue(':picName',$_FILES['userfile']['name']);$stmt->bindValue(':picPath', $uploadfile);$stmt->bindValue(':username',$username);$stmt->bindValue(':Name', $name);$stmt->bindValue(':introduction',$introduction);$stmt->bindValue(':Specialization',$specialization);$stmt->bindValue(':skillset',$skillset);$stmt->bindValue(':Email',$email);$stmt->bindValue(':ContactNo',$contactNo);$stmt->bindValue(':user_Id',$_SESSION['user_id']);$stmt->execute();

I am not sure how to validate the type in line 51. Since this is for profile picture, I wanted it to validate PNG and JPG/jpeg only. I can't seem to achieve that either.

My HTML Form:

            <tr>              <th scope="row"><div align="left">Profile Picture:</div></th>              <td><!-- MAX_FILE_SIZE must precede the file input field -->                                <input type="hidden" name="MAX_FILE_SIZE" value="100000" />                                <!-- Name of input element determines name in $_FILES array -->                 Send this file:                <input name="userfile" type="file" /></td>            </tr>

(PS: I'm not sure if I should continue posting here since it will get lengthy, but my title already includes the image.. ;-; )

Edited by Silence~
Link to post
Share on other sites

There are so many ways to do this, but pathiinfo() http://php.net/manual/en/function.pathinfo.php seems the better option.

I did another try(before you posted this) and I'm stuck at the same place where they would not detect the extension. Here's my tries :

//First Try//tried with 'jpg','png' and 'gif' for both too$allowedTypes = array('image/jpg', 'image/png', 'image/gif');  $ext = explode(".", $filename);$extension = strtolower(end($ext));$finfo = new finfo(FILEINFO_MIME_TYPE);$mimetype = $finfo->file($filetmp);var_dump($mimetype);if (!in_array($mimetype, $allowedTypes) || !in_array($extension, $allowedTypes)) {    $errors[] = ('File uploaded does not meet the types criteria(PNG/JPG/GIF). Please check.');}else {      move_uploaded_file($filename,$uploadfile);		 }//Second Try$allowedTypes = array('image/jpg', 'image/png', 'image/gif');$fileInfo = pathinfo($filename, PATHINFO_EXTENSION);if (!in_array($fileInfo,$allowedTypes)) {    $errors[] = ('File uploaded does not meet the types criteria(PNG/JPG/GIF). Please check.');}else {      move_uploaded_file($filename,$uploadfile);		 }

I tried uploading a png file but I'm not sure where I go wrong, there's no errors except for the $errors I declared in that code. Perhaps I'm missing something logical? ><

Edited by Silence~
Link to post
Share on other sites

There never going to match, one is checking against 'image/png' while the other checks for 'png', yes 'png' is in the earlier comparison but its not 'png'

 

 

You need to compare mimetype AND extension, also 'jpg' can be 'jpeg', 'jpe' as well

  <?php        $errors = "";        $filename = "images/test.png";        $filetmp = "tmp/test.png";        $allowedTypes = array('image/jpg', 'image/png', 'image/gif');        $allowedExtensions = array('jpg', 'png', 'gif');        //$ext = explode(".", $filename);        // $extension = strtolower(end($ext));        $extension = pathinfo($filename, PATHINFO_EXTENSION);        $finfo = new finfo(FILEINFO_MIME_TYPE);        $mimetype = $finfo->file($filename); // or $filetmp        var_dump($mimetype);        if (!in_array($mimetype, $allowedTypes)) { // check mimetype            // if (!in_array($extension, $allowedExtensions)) {  // check extensions            $errors = 'File uploaded does not meet the Type criteria(PNG/JPG/GIF). Please check. #1<br />';        } else {//move_uploaded_file($filename,$uploadfile);            $errors = 'File uploaded DOES MEET the Type criteria(PNG/JPG/GIF). #1<br />';        }        echo $errors;        ?>  
Edited by dsonesuk
  • Like 1
Link to post
Share on other sites

 

There never going to match, one is checking against 'image/png' while the other checks for 'png', yes 'png' is in the earlier comparison but its not 'png'

 

 

You need to compare mimetype AND extension, also 'jpg' can be 'jpeg', 'jpe' as well

  <?php        $errors = "";        $filename = "images/test.png";        $filetmp = "tmp/test.png";        $allowedTypes = array('image/jpg', 'image/png', 'image/gif');        $allowedExtensions = array('jpg', 'png', 'gif');        //$ext = explode(".", $filename);        // $extension = strtolower(end($ext));        $extension = pathinfo($filename, PATHINFO_EXTENSION);        $finfo = new finfo(FILEINFO_MIME_TYPE);        $mimetype = $finfo->file($filename); // or $filetmp        var_dump($mimetype);        if (!in_array($mimetype, $allowedTypes)) { // check mimetype            // if (!in_array($extension, $allowedExtensions)) {  // check extensions            $errors = 'File uploaded does not meet the Type criteria(PNG/JPG/GIF). Please check. #1<br />';        } else {//move_uploaded_file($filename,$uploadfile);            $errors = 'File uploaded DOES MEET the Type criteria(PNG/JPG/GIF). #1<br />';        }        echo $errors;        ?>  

 

I'm not sure if i understand it correctly.

This is what I've added in :

	//Allowed typpes to pass through validation        $allowedTypes = array('image/jpg', 'image/jpeg', 'imagae/jpe', 'image/png', 'image/gif');	$allowedExtensions = array('jpg', 'jpeg', 'jpe' , 'png', 'gif');	//$ext = explode(".", $filename);	// $extension = strtolower(end($ext));    //gets the info of ther file, in this case, extension	$extension = pathinfo($filename, PATHINFO_EXTENSION);	//return the file mime type	$finfo = new finfo(FILEINFO_MIME_TYPE);	//check th file for the information (tmp or name)	$mimetype = $finfo->file($filetmp); 	var_dump($mimetype);	//Check mimetype and extensions	if ((!in_array($mimetype, $allowedTypes)) || (!in_array($extension, $allowedExtensions))) { 		$errors[] = 'File uploaded does not meet the Type criteria(PNG/JPG/GIF). Please check.';	} else {        if (!move_uploaded_file($filetmp,$uploadfile)) {		$errors[] = 'File uploaded DOES NOT move to another folder.';		}		if(move_uploaded_file($filetmp,$uploadfile)) {			return $uploadfile;		}	}

Since I have to compare mimetype and extension, shouldn't this works too? You have put the commented validation $extension below the validation $mimetype, I'm just wondering why though, it can be put together in one line doesn't it? It still shows the $errors inside, still not getting it ><

 

I also have a problem about the move_uploaded_file after playing with the codes(the one you give as an example. I uncomment it). It would trigger the cannot modify headers, headers not sent errors. I have 2 headers , one before validating the user's inputs and another one after inserting it to database:

        // if no errors at this point, redirect to the exact same url of this page to prevent the browser from resubmitting the data by causing a get request for the page        if(empty($errors)){            $host = $_SERVER['HTTP_HOST'];            $uri = $_SERVER['REQUEST_URI'];            header("Location:addProfile.php?success=1");            exit;        }

It will always point out the error at the beginning of this code:

    <?php            //This must be out of that form validation.            //set error array            $errors = array();            if (( isset($_GET['success']) && $_GET['success'] == 1 ))            {              echo "Successfully added your profile! Please check out your updated profile page.";            //   if(empty($errors)){            //		include ('mailer.php');	            //			            //        }            }            if (( isset($_GET['failure']) && $_GET['failure'] == 1 )) {            echo "You have an existing record. Either delete your record, or update/edit your record.";            }            foreach($errors as $error)            {            printf("<li>%s</li>", $error);            //exit();            }        ?> 

EDIT: I actually am able to save the picture name and path in the database and also in the relative folder. However, it keeps sends the error :" Warning: Cannot modify header information - headers already sent by (output started at... ". I'm not sure what had happen as I only changed this particular codes and the relative path to this:

//create the relative folder$uploaddir = 'profilePics/';  //<-- Found a / in the front of /profilePics/ , which keeps giving error that could not move upload file.. (It's gone now though, after I fix it)$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);if ($_FILES['userfile']['error'] === UPLOAD_ERR_OK) {         $allowedTypes = array('image/jpg', 'image/jpeg', 'imagae/jpe', 'image/png');	$allowedExtensions = array('jpg', 'jpeg', 'jpe' , 'JPEG', 'JPG', 'JPE', 'PNG', 'png');	//$ext = explode(".", $filename);	// $extension = strtolower(end($ext));    //gets the info of ther file, in this case, extension	$extension = pathinfo($filename, PATHINFO_EXTENSION);		//return the file mime type	$finfo = new finfo(FILEINFO_MIME_TYPE);	//check th file for the information (tmp or name)	$mimetype = $finfo->file($filetmp); 	var_dump($mimetype);	//Check mimetype and extensions in the arrays.	if ((!in_array($mimetype, $allowedTypes)) || (!in_array($extension, $allowedExtensions))) { 		$errors[] = 'File uploaded does not meet the Type criteria(PNG/JPG). Please check.';	} 	else {               if (!move_uploaded_file($filetmp,$uploadfile)) {		$errors[] = 'File uploaded DOES NOT move to another folder.';		}		if(move_uploaded_file($filetmp,$uploadfile)) {			//get the destination now		$errors[] = 'File uploaded is '.$filetype.' to another folder.';			//return $uploadfile;		}	}}

I've googled for answers (Here is the reference I checked :http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php/8028979#8028979 , but I am still clueless as ever. There were no missing ; or any whitespaces at the php tags as far as I've checked >< Could anyone tell me what is wrong here? I really suspect the error would've been the move_uploaded_file , but it did save it to the folder/database so I can't say that my suspicion is correct ><

Edited by Silence~
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...