PHP:
单击按钮时如何执行SQL?
我会使用JavaScript onClick()
函数或其他方式吗?
我试图在循环内执行此操作,并且只在单击按钮的行上执行sql ...
谢谢!
@PHPnoOb 代码帮助: 好的,所以现在我把所有这些都整理好了,但是当点击按钮时,它会为每一行执行一次...而不是只按一次按钮被点击的行!我只想要点击按钮的行...我的代码:
while($row = mysqli_fetch_array($result)) {
//FAULTY CODE!!! EXECUTES ONCE FOR EACH ROW!
//I WANT IT TO ONLY EXECUTE FOR THE ROW THE
//BUTTON WAS CLICKED ON
if(isset($_POST['delete'])){
echo "You clicked on: ".$row['subject'];
//eventually i will have sql query up here
}
//echo all the results into a table... messy
echo"
<tr><td><div align='center'><font color='grey'>".$row['date']."</font></div></td><td><div align='center'> ".$row['sender']."</div></td><td><div align='center'> ".$row['subject']."</div></td><td><div align='center'><input type='button' value='open' onClick='window.alert(\"On ".$row['date']." ".$row['sender']." wrote:\\n".$row['message']."\")'/></div></td><td><div align='center'><form method='post'><input type='submit' value='delete' name='delete'/></form></div></td></tr>
";
}
echo '</table>'; //ends the table.
答案 0 :(得分:8)
Update: 2017
此答案已过时,请使用更好的库PDO来完成以下功能。
好的,只需将整个代码复制/粘贴到普通的PHP文本中即可。它有效,我刚刚尝试过。
您只需要一个名为test
的表格,其中包含文件id
,username
,或者您可以按照自己喜欢的方式对脚本进行成本核算。并且不要忘记更改数据库密码,用户名详细信息..
<form action='' method='POST'>
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$query = "SELECT * FROM users";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo " To delete user <b>" . $row['username'] . "</b> Click on the number <input type='submit' name='delete' value='" . $row['id'] . "' /><br/>";
}
if (isset($_POST['delete'])) {
$user = $_POST['delete'];
$delet_query = mysql_query("DELETE FROM users WHERE id = $user ") or die(mysql_error());
if ($delet_query) {
echo 'user with id ' . $user . ' is removed from your table, to refresh your page, click' . '<a href=' . $_SERVER["PHP_SELF"] . ' > here </a>';
}
}
?>
</form>
答案 1 :(得分:4)
您可以执行以下操作来保存输入/提交btn中的值。
<!-- your html form -->
<form action="POST">
<input type='text' name='username' />
<input type='text' value='submit' />
</form>
<?php
// your php code
if($_POST && isset($_POST['username'])){
$db = new \PDO('......'); // enter your db details
$stmt = $db->prepare("INSERT INTO table (username) VALUES (?)");
$result = $stmt->execute(array($_POST['username']);
echo $result->rowCount() ? 'Username saved in db' : 'Unknown error occured';
}
答案 2 :(得分:1)
使用an AJAX library向执行查询的服务器端脚本发出请求。把它作为你在Javascript中的onClick()处理程序,并且presto,Bob是你的叔叔!