开发者

Inserting PHP into a HTML Button

How do I insert PHP code into a HTML Button? Here's what I have:

<input type="submit" value="Buy" onclick="
<?php
    $sq = mysql_query("SELECT * FROM accounts WHERE Username='$usr'");
    $ar = mysql_fetch_array($sq);

    if ($ar['Beevals'] >= 250){
         mysql_query("U开发者_开发知识库PDATE `accounts` SET `Beevals`=`Beevals`-250 WHERE Username='$usr'");
         mysql_query("UPDATE `accounts` SET `Skin`=`WorkersDream` WHERE Username='$usr'");

    }

?>
" />

But it doesn't work. So, I'm wandering how exactly can you insert PHP code into a HTML Button?


"Inserting PHP into an HTML button" doesn't make any sense. HTML is for the client's browser, PHP executes on the server.

Take a look at the PHP tutorial to see a very basic example of how to make a form interact with PHP. To crib from there:

action.php

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>


It is not possible. You should understand that PHP is purely a scripting language which runs only server side.

HTML is a client side markup language, which is sent from the server to the client. By the time that PHP has ran over your script, it has now left the server and is with the client. At which point no more PHP can execute without loading a new page again through another request.


You have 2 ways to go:

either process the form ON the server, meaning you'll need a form tag:

<form action="PHP_FILE.php" method="post/get">
<!-- INPUT TYPES -->
</form>

where method is either post or get (which means they'll be stored in the superglobal vars)

Using an ajax request, to send the request to a PHP file, which will handle the input, this is done using JavaScript's AJAX (or one of the many libraries for ease), I personally use jquery for those sorts of things.

Good luck!


On your way is no way to affect HTML with PHP.

You should use a Form <form></form>

For example:

<?php
if (isset($_GET["myButton"]))
{
    $sq = mysql_query("SELECT * FROM accounts WHERE Username='$usr'");
    $ar = mysql_fetch_array($sq);

    if ($ar['Beevals'] >= 250){
         mysql_query("UPDATE `accounts` SET `Beevals`=`Beevals`-250 WHERE Username='$usr'");
         mysql_query("UPDATE `accounts` SET `Skin`=`WorkersDream` WHERE Username='$usr'");

    }

}
?>

<form action="readTheForm.php" method="get">
<input type="submit" name="myButton" value="Do it!"/>
</form>


You have to execute the PHP-Code using AJAX or a normal request, defined by the action of the form-tag the button is in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜