2013-07-09 41 views
1

標題可能看起來很模糊,對不起,我不知道如何說出我的問題。如何將HTML標記的類值傳遞給一個php變量

我試圖讓一個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}'"; 

這需要像這樣由於什麼查詢被用於。

感謝您的任何幫助。

+0

必須有一個更好的方法,但需要更多的內容,一個隱藏的表單域會想到 – 2013-07-09 23:57:33

+0

你能回答我將如何做到這一點。 – RedJax

+0

把id放在一個隱藏的表單域中,當按下按鈕時將會提交。 – 2013-07-10 00:00:17

回答

0

總之:你不能那樣做。

您可能想要做的是使用隱藏字段通過提交表單將數據傳遞給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); 
    } 
} 

當然,而不是打印查詢結果就在那裏,你可能會想將它們存儲在一個變量供以後使用。請注意,您也可以將該腳本與表單合併到同一頁面上。

+0

實際上,這是我做到這一點的方式。我使用了表單和發佈方法 – RedJax

-1

嗯,試試這個:我使用Jquery將按鈕類傳遞給下面的php文件的Ajax請求。

編輯:請確保您正確解析和篩選您的數據以防止注入攻擊。這只是顯示你可以將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); 
?> 

希望幫助!

+1

-1超級簡單的SQL注入 –

+0

即將進行編輯。 –

+0

是的。切勿通過將變量連接到部分語句字符串來構建SQL語句。決不。 –

相關問題