前端form-data传String数组后端如何接收size=1的空字符串

前端formdata传一个String数组, 后端用List接收, 如果是传长度为1的空字符串, 后端接收到的是size为0怎么办? 下面是前端传的:

图片说明

后端接收到的就是size为0, 然后我用postman试也是这样:

图片说明

图片说明

但是如果我传长度为2的空字符串, 后端就接收到了, 长度为2的空字符串数组.

图片说明

图片说明

问: 为什么传长度为1的空字符串后端接收却是size为0? 如果我想接收长度为1的空字符串数组该怎么办? 请大佬赐教!

m0_37772518
哆啦A梦陈 已解决, 如果遇到这个问题可以参考:https://blog.csdn.net/m0_37772518/article/details/100988401
9 个月之前 回复

1个回答

m0_37772518
哆啦A梦陈 这是我之后写的O(∩_∩)O
9 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Laravel Validator从数组中删除空字段

<div class="post-text" itemprop="text"> <p>I'm writing a test case to simulate a creation of a product. When creating the product, I'm passing an array of formats, and for some reasons, when validating with the controller, the <code>thumbnail</code> key is missing from the data.</p> <p>This is the data I'm sending:</p> <pre><code>"formats" =&gt; array:1 [ 0 =&gt; array:3 [ "upc" =&gt; "584979099857" "vcode" =&gt; "VX43V14FN910479274209" "thumbnail" =&gt; null ] ] </code></pre> <p>And I send it like the following in my test case:</p> <pre><code>$response = $this-&gt;post(route('products.store'), $product); </code></pre> <p>For some reasons, when sending the request, the <code>thumbnail =&gt; null</code> disappears from the formats attribute.</p> <p>Therefore, when validating the request, I always get the error that the thumbnail has to be present.</p> <pre><code>request()-&gt;validate([ 'formats' =&gt; 'bail|required|array', 'formats.*.upc' =&gt; 'bail|required|string|max:255', 'formats.*.vcode' =&gt; 'bail|required|string|max:255', 'formats.*.thumbnail' =&gt; 'bail|present|image' ]); </code></pre> <p>I've also tried changing the rules of thumbnail to:</p> <pre><code>bail|required|nullable|image </code></pre> <p>Or</p> <pre><code>bail|nullable|required|image </code></pre> <p>But then I get the required error.</p> <p>Does anyone know why the <code>thumbnail</code> key is getting removed from the <code>formats</code> array upon sending the request?</p> </div>

Golang中二进制字节数组的终止指示符?

<div class="post-text" itemprop="text"> <p>In Golang if I have a byte array of binary data how do I determine the termination of actual data if it is in a larger array. For example if I do the following, reading a file when it is plain text:</p> <pre><code> chunk := make([]byte, 1024) ..read some data into the chunk but only 10 bytes are filled from the file... </code></pre> <p>I can then determine the actual size of the data by doing the following: </p> <pre><code>n := bytes.IndexByte(chunk, 0) </code></pre> <p>When it is plain text n will give me the end of the actual data - how do I do that if the data is binary? </p> </div>

<form:form modelAttribute="inMain"/>中对象修改,表单中没有的属性为空。怎么解决

我数据库中有这个对象,我想对inMani这个对象进行编辑或者修改。这个对象的有些属性,如createTime(创建时间),lastModifyTime(最后修改时间),这些东西,对于客户来说是不能编辑的。所以就不显示了。也不设为隐藏属性即:<form:hidden path="createTime" />。 我在后台接收用的是: spring mvc: @RequestMapping(value="/save") public String save(Model model,InMain inMain){} 这时有个问题就是: 我保存imMain这个对象时,发现,createTime,lastModifyTime 这些没有在表单中出现的属性,都是null. 请问怎么不让他修改这些值(createTime,lastModifyTime)。谢谢

Symfony2 - 使用空字段提交表单时使用实体值作为默认值

<div class="post-text" itemprop="text"> <p>I'm building a web application in Symfony 2 where I have a User entity class for holding registered users. </p> <p>Every user should have at least a username and a password of course, hence, I use the <code>@Assert\NotBlank</code> validation rule for both fields in the entity. The username is static, however, being able to change the password is desirable. </p> <p>Thus, I'm building a form where signed in users can change their password (among other things). This form utilizes the repeated field type in Symfony for password confirmation purposes. </p> <p>Now, in most cases I guess users are not looking to change their password, but rather update other fields in their profile. Therefore, I would want it to be possible for them to leave the password field blank. However, that will interfere with the <code>NotBlank</code> validation rule. </p> <p>Removing the <code>NotBlank</code> validation rule is of course an option. Although, hardly the solution I'm looking for since that incures the problem of users ending up with a blank password. </p> <p>Finally, As I understand it the symfony Request object autofills the form data back into the User entity on form submission. </p> <p>Now, my question is: Is there any way to, upon empty password-field, make Symfony refill the User entity with the existing password from the database rather than a blank value? This would allow validation to follow through and won't cause any undesired changes to the password upon saving. </p> <p>This is the code for the password field in the entity</p> <pre><code>/** * @var string * * @ORM\Column(name="password",type="string",length=255) * @Assert\NotBlank() * @Assert\Type(type="string") * @Assert\Length(max="255") * @Assert\NotEqualTo(value="password") */ private $password; </code></pre> <p>This is the code for generating the form</p> <pre><code>private function initForm($user) { return $this-&gt;createFormBuilder($user) -&gt;add('name', 'text') -&gt;add('mail', 'email') -&gt;add('password', 'repeated', [ 'type' =&gt; 'password', 'invalid_message' =&gt; 'The password fields must match.', 'first_options' =&gt; ['label' =&gt; false], 'second_options' =&gt; ['label' =&gt; false] //set to false to hide label in view ]) -&gt;add('save', 'submit')-&gt;getForm(); } </code></pre> <p>This is the Action-code for the <code>/profile/edit</code> page:</p> <pre><code>/** * @ParamConverter("user",class="MyBundle:User") */ public function editAction(User $user, Request $request) { $form = $this-&gt;initForm($user); $form-&gt;handleRequest($request); if ($form-&gt;isValid()) { //update to database and redirect user back to profile_view $this-&gt;getDoctrine()-&gt;getManager()-&gt;flush(); return $this-&gt;redirect($this-&gt;generateUrl('profile_view')); } return $this-&gt;render('MyBundle:User:edit.html.twig', array('form' =&gt; $form-&gt;createView())); } </code></pre> <p>Thanks in advance for any help!</p> <h1>EDIT</h1> <p>I did try the "obvious" approach, i.e. temporarilly storing the original password in a variable and "putting" it back if it was blank after the form was submitted:</p> <pre><code>/** * @ParamConverter("user", class="MyBundle:User") */ public function editAction(User $user, Request $request) { $password = $user-&gt;getPassword(); $form = $this-&gt;initForm($user)-&gt;getForm(); $form-&gt;handleRequest($request); if ( $user-&gt;getPassword() == NULL ) { $user-&gt;setPassword($password); $form = $this-&gt;initForm($user)-&gt;getForm(); //this is the problem } if ( $form-&gt;isValid() ) { //update to database and redirect user back to profile view $this-&gt;getDoctrine()-&gt;getManager()-&gt;flush(); return $this-&gt;redirect($this-&gt;generateUrl('profile_view')); } return $this-&gt;render('MyBundle:User:edit.html.twig', array('form' =&gt; $form-&gt;createView())); } </code></pre> <p>However, this did not work for apparent reasons. When the form is reinitialised within the <code>if</code> statement, Symfony finds the form has never been submitted in the first place, i.e. no validation is performed. And adding the <code>$form-&gt;handleRequest($request)</code> leaves us back with the first problem where the password field might be blank.</p> <p>What I do find peculiar though. Symfony validates the Entity and not the form. But removing the problem row <code>$form-&gt;initForm($user)-&gt;getForm()</code> still didn't work, although the entity should be valid.</p> </div>

如果为空,则将值分配给struct中的字段

<div class="post-text" itemprop="text"> <p>I have a struct defined</p> <pre><code>type data struct { invitecode string fname string lname string } </code></pre> <p>which I populate from retrieving form data after parsing</p> <pre><code>... r.ParseForm() new user := &amp;data{ invitecode: r.FormValue("invitecode"), fname: r.FormValue("fname") lname: r.FormValue("lname") } </code></pre> <p>I did like to check if the <code>invitecode</code> field obtained from the form is empty and if so, populate it by calling a function but if it is not, to populate it with the retrieved value (invitecode: if newUser.invitecode == "" {"Mr"} else {lnames.title},). I understand go doesn't have a tenary operator which I thought of using and reading the questions <a href="https://stackoverflow.com/questions/45710188/assign-default-value-for-struct-field-in-golang">here</a>, <a href="https://stackoverflow.com/questions/37135193/how-to-set-default-values-in-golang-structs">here</a>, <a href="https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct">here</a> &amp; <a href="https://stackoverflow.com/questions/19979178/what-is-the-idiomatic-go-equivalent-of-cs-ternary-operator">here</a> implies using an if else statement but I can't seem to get it to work. Preferable, I am looking for a solution that check's while assigning a new variable. Trying the code below doesn't seem to work. Any help would be appreciated.</p> <pre><code>package main import ( "fmt" ) type data struct { invitecode string fname string lname string } func main() { var user data newUser := map[string]string{"invitecode": "", "fname": "Dude", "lname": "Did"} user = &amp;data{ invitecode: if newUser.invitecode == "" {"Mr"} else {lnames.title}, fname: newUser.fname, lname: newUser.lname, } fmt.Println(user) } </code></pre> </div>

如果在php中提交表单后没有空字段,如何显示成功消息

<div class="post-text" itemprop="text"> <p>I have made an html form and validate it with php or more precisely part of validation (just check rquired field) Here is the html codes:</p> <pre><code>&lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt; &lt;h3&gt;Registration Form&lt;/h3&gt;&lt;br&gt; &lt;form action="#" method="post"&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Name : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $nameErr; ?&gt;&lt;/span&gt; &lt;input id="name" type="text" name="name" class="form-control" placeholder="Type your name here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="username"&gt;Username : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $usernameErr; ?&gt;&lt;/span&gt; &lt;input id="username" type="text" name="username" class="form-control" placeholder="Type your username here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="password"&gt;Password : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $passwordErr; ?&gt;&lt;/span&gt; &lt;input id="password" type="password" name="password" class="form-control" placeholder="Type password here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="rpassword"&gt;Retype Password : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $rpasswordErr; ?&gt;&lt;/span&gt; &lt;input id="rpassword" type="password" name="rpassword" class="form-control" placeholder="Retype password here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Email : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $emailErr; ?&gt;&lt;/span&gt; &lt;input id="email" type="email" name="email" class="form-control" placeholder="Type your email here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="phone"&gt;Phone No : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $phoneErr; ?&gt;&lt;/span&gt; &lt;input id="phone" type="text" name="phone" class="form-control" placeholder="Type your phone here"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="dob"&gt;Date of Birth : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $dobErr; ?&gt;&lt;/span&gt; &lt;input id="dob" type="date" name="dob" class="form-control"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Select A Country : * &lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $countryErr; ?&gt;&lt;/span&gt; &lt;input id="country" type="text" name="country" class="form-control not-me"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="gender"&gt;Please Select Your Gender : *&lt;/label&gt;&lt;span class="error"&gt;&lt;?php echo $genderErr; ?&gt;&lt;/span&gt; &lt;div class="form-control gender"&gt; &lt;input type="radio" id="male" name="gender"&gt; &lt;label for="male" class="exclude"&gt;Male&lt;/label&gt; &lt;input type="radio" id="female" name="gender"&gt; &lt;label for="female" class="exclude"&gt;Female&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;input type="submit" name="submit" class="custom-btn" value="Submit" name="reg-form"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And here is the php code to check if any of the field is empty:</p> <pre><code>&lt;?php $nameErr = $usernameErr = $passwordErr = $rpasswordErr = $emailErr = $phoneErr = $dobErr = $countryErr = $genderErr = ""; $name = $username = $password = $rpassword = $email = $phone = $dob = $country = $gender = ""; if(isset($_POST["submit"])) { if (empty($_POST["name"])) { $nameErr = " This field is required"; } else { $name = $_POST["name"]; } if (empty($_POST["username"])) { $usernameErr = " You must enter a username"; } else { $username = $_POST["username"]; } if (empty($_POST["password"])) { $passwordErr = " You must type a strong password"; } else { $password = $_POST["password"]; } if (empty($_POST["rpassword"])) { $rpasswordErr = " Your password didn't match"; } else { $rpassword = $_POST["rpassword"]; } if (empty($_POST["email"])) { $emailErr = " This is not a valid email address"; } else { $email = $_POST["email"]; } if (empty($_POST["phone"])) { $phoneErr = " Please enter your contact number"; } else { $phone = $_POST["phone"]; } if (empty($_POST["dob"])) { $dobErr = " You must fill your Date of Birth"; } else { $dob = $_POST["dob"]; } if (empty($_POST["country"])) { $countryErr = " You didn't select a country"; } else { $country = $_POST["country"]; } if (empty($_POST["gender"])) { $genderErr = " You can not leave this field empty"; } else { $gender = $_POST["gender"]; } } ?&gt; </code></pre> <p>Now I simply want to show a success message after submission the form if there is no empty field.<br> N.B: This is my first php work. Thanks in advance!</p> </div>

cakephp - 不要在更新时更改空字段

<div class="post-text" itemprop="text"> <p>i use cakephp 2.5.4 and want when update record in database, fields that is null, do not change</p> <p>this is my update function</p> <pre><code>... if ($this-&gt;User-&gt;save($this-&gt;request-&gt;data)) { return $this-&gt;User-&gt;id; } ... </code></pre> </div>

自定义json unmarshaler返回空字段

<div class="post-text" itemprop="text"> <p>I've implemented a custom JSON unmarshaler, but for some reason it won't return the proper value -all fields come back nil.</p> <p>For example:</p> <pre><code>type test struct { t string } func New(data string) (*test, error) { return &amp;test{t: data}, nil } func (t *test) UnmarshalJSON(b []byte) error { tt, err := New(string(b)) if err != nil { return err } t = tt return nil } func main() { str := `"hello"` b := []byte(str) t := &amp;test{} err := json.Unmarshal(b, t) if err != nil { fmt.Printf("unmarshal error occurred: %#v", err) } fmt.Printf("%#v", t) } </code></pre> <p><a href="https://play.golang.org/p/LuXkZQZHWz" rel="nofollow noreferrer">https://play.golang.org/p/LuXkZQZHWz</a></p> <p>The above code shows the output: <code>&amp;main.test{t:""}</code><br> Why doesn't it unmarshal the fields? i.e <code>&amp;main.test{t:"hello"}</code></p> <p>Only when I dereference the pointers above, do I get the desired result.</p> <p>i.e -</p> <pre><code>func (t *test) UnmarshalJSON(b []byte) error { tt, err := New(string(b)) if err != nil { return err } *t = *tt return nil } </code></pre> </div>

在Golang中执行json解组时为空字段

<div class="post-text" itemprop="text"> <p>I have written this piece of code. I can't figure out why it is giving empty fields when i run it. I have tried Uppercase variables. Still doesn't work. </p> <pre><code>package main import ( "encoding/json" "fmt" ) type FirstName struct { Name1 string } type SecondName struct { Name2 string } type Person struct { Details FirstName MoreDetails SecondName } func main() { var someGuy Person var data = []byte(`{"details": {"firstName": "alan"}, "moreDetails": {"surName": "Turing"}}`) json.Unmarshal(data, &amp;someGuy) fmt.Println(someGuy) } </code></pre> </div>

java 后台对前台的表单做非空验证,有必要吗

如果前台已经使用了JS做了非空等相关的验证操作,那么后台还有必要再去做一次验证吗? 如果有必要,为什么呢?

调用JSON.parse ()函数对字符串对象进行转化的时候,报错Unexpected end of JSON input

具体的代码如下:先从前端读取的json文件中获取内容再进行转化: ``` function handleFiles() { var selectedFile = document.getElementById("files").files[0];//获取读取的File对象 var name = selectedFile.name;//读取选中文件的文件名 var size = selectedFile.size;//读取选中文件的大小 console.log("文件名:"+name+"大小:"+size); var reader = new FileReader(); reader.readAsText(selectedFile);//读取文件的内容 // 下面这一行报错了!!!! var json = JSON.parse(reader.result.toString().replace(/\n/g, '')); var temp = 0; for(i=0;i< length(json);i++){ for(j=0;j<length(json)-i-1;j++){ if(json[j+1].value>json[j].value){ temp = json[j+1]; json[j+1] = json[j]; json[j] = temp; } } } return json; ``` 但如果设置断点调试则可以进行,是为什么?

解析数据时出错org.json.JSONException:类型org.json.JSONObject $ 1的lat值为null无法转换为double

<div class="post-text" itemprop="text"> <p>I am getting the following error with andoroid trying to return data from PHP</p> <pre><code>try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try { JSONArray jArray = new JSONArray(result); //----------------------------------------- //---------------------------------------- for(int i=0;i&lt;jArray.length();i++) { JSONObject json_data = jArray.getJSONObject(i); map = new HashMap&lt;String, String&gt;(); map.put("nomclt", (String) json_data.get("nomclt")); map.put("prenomclt", (String) json_data.get("prenomclt")); // map.put("adresse", (String) json_data.get("adresse")); //enfin on ajoute cette hashMap dans la arrayList listItem.add(map) </code></pre> <p>Script php</p> <pre><code>&lt;?php header('Content-type: application/json'); mysql_connect("localhost","root",""); mysql_select_db("test"); $sql=mysql_query("SELECT * FROM client"); $output = array(); while($row=mysql_fetch_array($sql)) $output[]=$row; print(json_encode($output)); mysql_close(); ?&gt; </code></pre> </div>

Vuejs和axios添加空字段而不是插入数据

<div class="post-text" itemprop="text"> <p>I have been trying to build a crud using vuejs,axios and php i am working with separate xampp server and Node server everything is working fine except the insert whenever i insert any data an empty field is also added into the database along with the data Here is my vue and axios code</p> <pre><code>export default{ data(){ return{ title:'Insert Record', Lname:'', Fname:'' } } },methods:{ insert(){ this.$router.push('/') axios.post('http://localhost/insert.php', {Fname:this.Fname,Lname:this.Lname }) .then(function(response){ if(response) { console.log(response) alert('Data Has Been inserted') } }); } } } &lt;/script&gt; </code></pre> <p>And Here is my php code</p> <pre><code>&lt;?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); $conn = mysqli_connect('localhost','root','','ajax'); $data = json_decode(file_get_contents("php://input"), true); $Fname = $data['Fname']; $Lname = $data['Lname']; json_encode(array('Fname'=&gt;$data['Fname'],'Lname'=&gt;$data['Lname'])); $userData = mysqli_query($conn,"INSERT INTO names (Fname,Lname) VALUES ('$Fname','$Lname')"); if($userData){ echo json_encode(array('inserted'=&gt;true)); } </code></pre> </div>

JSON解组中缺失字段和空字段之间的区别

<div class="post-text" itemprop="text"> <p>So I have this struct in Go:</p> <pre><code>type Car struct { Name string `json:"name"` Speed int `json:"speed"` } </code></pre> <p>And I have two JSON samples that I unmarshal:</p> <pre><code>str := `{"name": "", "speed": 0}` strTwo := `{}` </code></pre> <p>I do the unmarshaling in this way:</p> <pre><code>car := Car{} _ = json.Unmarshal([]byte(str), &amp;car) carTwo := Car{} _ = json.Unmarshal([]byte(strTwo), &amp;carTwo) </code></pre> <p>Now because of the way Go deals with default value types, when I try to print the structure, I get the same result:</p> <pre><code>car - { 0} carTwo - { 0} </code></pre> <p>So I can't see the difference between a missing value in JSON and when a default value is passed. How can I solve this problem?</p> <p>One way is to use pointers in struct:</p> <pre><code>type Car struct { Name *string `json:"name"` Speed *int `json:"speed"` } </code></pre> <p>But I get a very ugly code when using this values, I have to do pointer dereferencing everywhere</p> </div>

c#函数后面的“【】”代表什么意思呢?

大神你们好!我在看别人的代码风格是发现一个不熟悉的c#用法请大声指点一下! public enum FileType { image = 1, video = 2, ppt = 3, word = 4, excel = 5, pdf = 6, other = 0, } -------------------------------------------------------------------- public static Dictionary<FileType, List<string>> getTypeDic() { Dictionary<FileType, List<string>> fileExtensionDic = new Dictionary<FileType, List<string>>() { {FileType.image , new List<string>(){"jpg","jpeg","bmp","gif","png","tiff"}}, {FileType.video , new List<string>(){"mp4","avi","wmv","rmvb","rm","mpeg","mpg","dat","flv","3pg","mov"}}, {FileType.word , new List<string>(){"txt","text","doc","docx","docm","dot","dotx","dotm","rtf"}}, {FileType.ppt , new List<string>(){"ppt","pptx","pptm","ppsx","potx","pot","ppam"}}, {FileType.excel , new List<string>(){"xls","xlsm","xlts","xltx","xltm","xlsb","xlam"}}, {FileType.pdf , new List<string>(){"pdf"}}, {FileType.other , new List<string>(){"*"}}//TODO:这里可能会有问题,是否应该应用空字串来表达 }; return fileExtensionDic; } --------------------------------------------------------------------------- public static List<string> getFileExtensions(FileType type) { return getTypeDic()[type]; //!!这里 函数名()[] 很怪异??? }

空字段消息无法正确显示

<div class="post-text" itemprop="text"> <p>When user trying to edit his blog post and left some fields empty, he should get empty fields error, but, code that should do that get ignored and i get completely different error message instead.</p> <p>My question: how to display empty fields error message properly?</p> <p>Code snippets from editpost.php file:</p> <p>1. Checking for empty fields:</p> <pre><code>// Check for empty fields if (empty($title) || empty($body)) { // Save correct data into fields header('Location: editpost.php?error=emptyeditpostfield&amp;title='.$title.'&amp;body='.$body); // Stop script exit(); } else { $query = "UPDATE posts SET title='$title', body='$body' WHERE id = {$update_id}"; } </code></pre> <p>2. Desired message:</p> <pre><code>&lt;!-- Check if user has rights to editing post --&gt; &lt;?php if (isset($_SESSION['id'])) : ?&gt; &lt;?php if ($_SESSION['name'] == $post['author']) : ?&gt; &lt;div class="container"&gt; &lt;h1&gt;Edit Post&lt;/h1&gt; &lt;?php // Message I want to show if (isset($_GET['error'])) { if ($_GET['error'] == 'emptyeditpostfield') { echo '&lt;p class="text-warning"&gt;Fill in all fields!&lt;/p&gt;'; } } ?&gt; &lt;!-- Edit post form... --&gt; </code></pre> <p>3. Message I receive:</p> <pre><code>&lt;!-- /Edit post form... --&gt; &lt;/div&gt; &lt;?php else : header('Location: index.php?error=accessdenied'); exit(); // Message I got ?&gt; &lt;?php endif; ?&gt; &lt;?php else : header('Location: index.php?error=accessdenied'); exit(); ?&gt; &lt;?php endif; ?&gt; </code></pre> <p><strong>Edited (Nov 30).</strong></p> <p>4. Code that is a part of this issue as well:</p> <pre><code> // Get ID $id = mysqli_real_escape_string($conn, $_GET['id']); // Create Query $query = "SELECT * FROM posts WHERE id = $id"; // Get Result $result = mysqli_query($conn, $query); // Fetch Data $post = mysqli_fetch_assoc($result); // var_dump($posts); // Free Result mysqli_free_result($result); // Close Connection mysqli_close($conn); </code></pre> <p>Picture 1. Warnings after Submit with empty fields.</p> <p><a href="https://i.stack.imgur.com/exOPv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/exOPv.png" alt="Warnings"></a></p> <p>Picture 2. Edit post page.</p> <p><a href="https://i.stack.imgur.com/PomNT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PomNT.png" alt="Edit Post Page"></a></p> </div>

如果表单字段为空,则将替代值插入到mysql数据库中

<div class="post-text" itemprop="text"> <p>The following form collects data about the color preference of the visitors.</p> <p>how to insert a predefined alternative value into mysql database if the users submit the blank form. </p> <p>the thing is to consider here is i don't want to prevent user from submitting the blank form using form validation.</p> <p>my present backend codes are as following:</p> <pre><code>if ((isset($_POST["MM_insert"])) &amp;&amp; ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO users (color_name) VALUES (%s)", GetSQLValueString($_POST['color_name'], "text")), mysql_select_db($database_x, $x); $Result1 = mysql_query($insertSQL, $x) or die(mysql_error()); $insertGoTo = "choicecolor.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } </code></pre> <hr> <pre><code>&lt;form action="&lt;?php echo $editFormAction; ?&gt;" method="post" name="form1" id="form1"&gt; &lt;table align="center"&gt; &lt;tr valign="baseline"&gt; &lt;td align="right" nowrap="nowrap"&gt;Enter Color Name:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="color_name" value="" size="32" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="baseline"&gt; &lt;td nowrap="nowrap" align="right"&gt;&lt;input type="hidden" name="MM_insert" value="form1" /&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="submit" value="Submit Color Name" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>if the visitors submit a blank form without entering any value, a predefined value (for example, <code>"no choice"</code>) shall be inserted into database and if the visitors submit a filled form with the inputted value <code>"yellow"</code>, the value <code>"yellow"</code>, shall be inserted into database.</p> <p>how to predefine the value in this case using PHP?</p> </div>

停止提交空字段

<div class="post-text" itemprop="text"> <p>Need to stop empty field from submitting and display error message on the same page.</p> <p>I would appreciate any assistance. Here's the entire shopping cart code. Part in question between lines of asterisks. Thanks!</p> <p> </p><pre><code>// If no cart exists, create $_SESSION['cart'] array if(!isset($_SESSION['cart'])){ $_SESSION['cart'] = array(); } // Add item to array if(isset($_POST['action']) &amp;&amp; $_POST['action'] === 'add'){ /*******************************************************/ // Check if input is empty / null if(($_POST['id']) == ''){ $error = '*Please enter an ID number.'; include 'error.html.php'; exit(); } /*******************************************************/ // Check if form data exists if(isset($_POST['id'])){ $id = $_POST['id']; } // Check if ID already in cart if(isset($_SESSION['cart'][$id])){ $error = '*Item already in cart.'; } // Add new ID to array (hard-code some data for test file) $newitem = array( 'id' =&gt; $id, 'part_number' =&gt; '369A7170-11', 'quantity' =&gt; '1' ); // Add new data to cart with ID as key $_SESSION['cart'][$id] = $newitem; } // Remove item from array if(isset($_POST['action']) &amp;&amp; $_POST['action'] === 'remove'){ // Check if form data exists if(isset($_POST['id'])){ $id = $_POST['id']; } unset($_SESSION['cart'][$id]); } // Empty cart if(isset($_POST['action']) &amp;&amp; $_POST['action'] === 'empty'){ unset($_SESSION['cart']); } // Initialize $count variable; get item count $count = ''; if(isset($_SESSION['cart'])) $count = count($_SESSION['cart']); // Display results if(isset($_SESSION['cart'])){ $show_cart = var_dump($_SESSION['cart']); echo $show_cart; } /************** TEST ******************************/ //$_SESSION['quantity'][$id] = $quantity; if(isset($_SESSION['cart'])) echo 'ID: ' . $_SESSION['cart'][$_POST['id']]['id'] . '&lt;br&gt;'; if(isset($_SESSION['cart'])) echo 'Qty: ' . $_SESSION['cart'][$_POST['id']]['quantity'] . '&lt;br&gt;'; $new_quantity = 5; if(isset($_SESSION['cart'])) $_SESSION['cart'][$_POST['id']]['quantity'] = $new_quantity; if(isset($_SESSION['cart'])) echo 'Updated Qty: ' . $_SESSION['cart'][$_POST['id']]['quantity']; /************** // END TEST ***********************/ ?&gt;&lt;!DOCTYPE hml&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Cart&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Cart Management&lt;/h3&gt; &lt;p style="color:#ff0000;"&gt;&lt;?php if(isset($error)) echo htmlentities($error, ENT_QUOTES); ?&gt;&lt;/p&gt; &lt;p&gt;Items in cart: &lt;?php if(isset($count) &amp;&amp; $count &gt; 0)echo htmlentities($count, ENT_QUOTES); else echo 'none'; ?&gt;&lt;/p&gt; &lt;form action="" method="post"&gt; &lt;label for="id"&gt;ID:&lt;/label&gt; &lt;input type="text" name="id" id="id" autofocus&gt; &lt;input type="hidden" name="action" value="add"&gt; &lt;input type="submit" value="Add"&gt; &lt;/form&gt; &lt;form action="" method="post"&gt; &lt;label for="id"&gt;By ID:&lt;/label&gt; &lt;select name="id" id="id"&gt; &lt;option value=""&gt;Select ID&lt;/option&gt; &lt;?php foreach($_SESSION['cart'] as $key =&gt; $item): ?&gt; &lt;option value="&lt;?php echo htmlentities($item['id'], ENT_QUOTES); ?&gt;"&gt;&lt;?php echo htmlentities($item['id'], ENT_QUOTES); ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;input type="hidden" name="action" value="remove"&gt; &lt;input type="submit" value="Remove"&gt; &lt;/form&gt; &lt;form action="" method="post"&gt; &lt;input type="hidden" name="action" value="empty"&gt; &lt;input onclick="return confirm('Are you sure you want to empty the cart?');" type="submit" value="Empty cart"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div>

PHP剥离空字节

<div class="post-text" itemprop="text"> <p>I have an application where I need to be able to let the users put anything into an input field and am having issues with null bytes. I am passing the data via AJAX to PHP 5.5 and can see it's being passed from the AJAX request correctly, but when I immediately var_dump the $_POST on the PHP side, a string that contained '%00' comes through as ''. As an aside, I'm protecting my database from injection by using query bindings. Also, the user base is exclusively internal to my company. So, I'm not really concerned with the security aspect of it. How can I get PHP to let these null bytes through?</p> </div>

如何在Symfony表单约束中设置有效日期或空字段

<div class="post-text" itemprop="text"> <p>how to validate date with constraints to allow date in format yyyy-mm-dd or leave date blank in this code?</p> <pre><code>use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; class ArticleType extends AbstractType { public function getName() { return 'article'; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('date', 'date', array( 'label' =&gt; 'Date', 'input' =&gt; 'string', 'widget' =&gt; 'single_text', 'format' =&gt; 'yyyy-MM-dd', 'html5' =&gt; false, 'constraints' =&gt; array( new Assert\NotBlank(), new Assert\Date(), ), )) } } </code></pre> <p>Is it possible to validate without create custom validator?</p> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐