使用PHP变量作为HTML表单输入属性

Is it possible to use PHP variables as attributes in form inputs?

I have the following variable already declared:

$InStock //number of items in stock

I would like to use this variable per below, but the code isn't working (the max constraint is not being applied to the field):

print "<td><input type='number' name='product1' id='product1' min='0' max='<?php echo $InStock ?>' value='0'></td>";

Is this legal, or am I attempting something syntactically impossible? Sorry if this is a stupid question - I'm new at this, and I embarrass myself frequently. : /

dsgnsdjk26586
dsgnsdjk26586 非常欢迎你,继续工作:)
5 年多之前 回复
drvjlec1767
drvjlec1767 谢谢,@KA_lin-这显然是一个愚蠢的问题。感谢阅读材料和耐心回答我的问题!:)
5 年多之前 回复
dtqf81594
dtqf81594 更改为:print“<td><inputtype='number'name='product1'id='product1'min='0'max='$InStock'...阅读一些关于引号vs双引号的文章,ex:scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP
5 年多之前 回复

2个回答

It's possible, your syntax is incorrect though. You're double dipping on the php brackets.

I usually prefer to do something like this instead of using print, it's easier to read, especially if your IDE is doing syntax highlighting:

?><td><input type='number' name='product1' id='product1' min='0' max='<?php echo $InStock ?>' value='0'></td><?php

You could also do it within a print/echo statement, but you need to have the variable inline without the extra brackets:

echo "<td><input type='number' name='product1' id='product1' min='0' max='$InStock' value='0'></td>";

Note that without concatenation, this only works with double quotes.

doukuipai8544
doukuipai8544 感谢您抽出宝贵时间回答这个问题 - 我显然需要了解我的语法基础知识! :)
5 年多之前 回复

Instead of your:

print "<td><input type='number' name='product1' id='product1' min='0' max='<?php echo $InStock ?>' value='0'></td>";

Use:

print "<td><input type='number' name='product1' id='product1' min='0' max='$InStock' value='0'></td>";

This is because PHP will insert the values of variables into a string if you put the variable name into the string and PHP will replace this with the value of your variable. For example print "Hi there, $name"could produce "Hi there, James" when executed - assuming $name is equal to "James".

Please check this Muddal: http://muddal.com/muddaltut.php?id=163

dp13668681869
dp13668681869 没问题,我很高兴你找到了答案:)
5 年多之前 回复
douangzhao4108
douangzhao4108 谢谢,Xanco - 我感谢你花时间回应! :)
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐