根据用户要求用户删除哪一行 选择列表中选择的值和包含的文本框中的值 匹配数据。例如,selected item ='city'和textbox = “波士顿”。包括一个从表中删除行的按钮。
这些是我要遵循的指示。我有两个问题,第一个问题是如果我说..选择团队名称并从表中输入一个团队我得到一个错误说:
DELETE FROM teams WHERE teamname = rockets
未找到专栏:1054未知专栏'火箭'在' where子句'
它试图使用火箭作为列名而不是需要删除的行。第二个问题是,如果我选择年份并输入正确的年份,它将删除该年份的行。如果我输入的年份不存在,我的代码表示记录已成功删除,但实际上没有删除任何内容。
我想我在这里混淆了一些事情,并且不确定它是如何为一年生工作而中途,而不是其他专栏......
HTML
<form method='post' action='phpfiles/deleteData.php'>
Select a column name, then enter which data to delete.
<br>
<br>
<label for='option1'>
<select name='selectColumn'>
<option value='teamname' id='team'>teamname</option>
<option value='city' id='city'>city</option>
<option value='bestplayer' id='best'>bestplayer</option>
<option value='yearformed' id='year'>year</option>
<option value='website' id='website'>website</option>
</select>
</label>
<label for='option2'>
Data to delete: <input type='text' name='dataDelete'>
</label>
<br><br>
<input type='submit' value='Submit Delete'>
</form>
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "root";
$password = "enigma";
$dbname = "program09";
$columnSelect = $_POST['selectColumn'];
$deleteData = $_POST['dataDelete'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM teams WHERE $columnSelect = $deleteData";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
答案 0 :(得分:0)
您需要单引号:
$sql = "DELETE FROM teams WHERE $columnSelect = '$deleteData'";
但最好使用预准备语句来避免SQL注入。还可以使用白名单作为列名。
$sql = "DELETE FROM teams WHERE $columnSelect = :value1";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$deleteData));