[英]How to pass class value of HTML tag into a php variable
標題似乎很模糊,很抱歉,我真的不知道該怎么說。
我試圖讓一個PHP變量在按下按鈕時被分配一個按鈕類的值。 有點像這樣:
<input id="button-id" class="button-1" type="button" onclick="<?php $variable=class of button-id; // Assign the variable here ?>"
顯然語法不正確,因為我不知道該怎么做,或者是否可行。
我需要這個的原因是因為我正在執行一個MySQL查詢,該查詢將依賴於$variable
如下所示:
$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);
}
}
當然,您可能希望將它們存儲在變量中以備后用,而不是在此處打印查詢結果。 請注意,您還可以將腳本與表單合並在同一頁面上。
嗯,試試看:我使用Jquery將按鈕類傳遞給Ajax請求,該請求轉到下面的php文件。
編輯:請確保您正確地解析和過濾數據以防止注入攻擊。 這只是說明您可以將html類傳遞給PHP。
HTML文件
<html>
<head>
<script type="text/javascript">
// Assign your button an on click event using jquery
$('#button-id').click(function(){
//Store our current elements class value
var buttonclass = $(this).attr("class");
//Create an ajax request that goes to aphp file and will receive your class value
$.ajax({
url: 'ajaxfile.php?buttonclass='+buttonclass,
success:function(data){
alert(data);
}
});
});
</script>
</head>
<body>
<input id="button-id" class="button-1" type="button" />
</body>
</html>
PHP文件
<?php
$pdo = new PDO("mysql:dbname=newdbnaem;host=1.1.1.1:1111", "owner", "passwordlulz");
$buttonclass = $_GET['buttonclass'];
$query = $pdo->prepare("SELECT * FROM table WHERE name = :name");
$query->execute(array(':name' => $buttonclass));
?>
Success
<?php exit(0);
?>
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.