标题可能看起来很模糊,很抱歉我真的不知道如何表达我的问题。
我试图让一个 PHP 变量在按下按钮时被赋予按钮类的值。有点像这样:
<input id="button-id" class="button-1" type="button" onclick="<?php $variable=class of button-id; // Assign the variable here ?>"
显然语法是错误的,因为我不知道该怎么做,也不知道是否可行。
我需要这个的原因是因为我正在做一个依赖于 $variable
的 MySQL 查询,如下所示:
$query = "SELECT * FROM table WHERE name='{$variable}'";
由于查询的用途,这需要像这样。
感谢您的帮助。
最佳答案
简而言之:你不能那样做。
您可能想要做的是使用隐藏字段通过提交表单将数据传递给 PHP 脚本。例如:
<form method="post" action="form.php">
<input type="hidden" name="variable" value="button-1" />
<input type="submit" class="button" />
</form>
您的 form.php
文件看起来像这样:
<?php
$user = 'example';
$pass = 'example';
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use a prepared statement!
$stmt = $dbh->prepare("SELECT * FROM table WHERE name = ?");
// the user input is automatically quoted, so no risk of SQL injection
if ($stmt->execute(array($_POST['variable']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
当然,您可能希望将它们存储在变量中以备后用,而不是直接在此处打印查询结果。请注意,您还可以将脚本合并到与表单相同的页面上。
关于php - 如何将 HTML 标签的类值传递给 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560205/