我正在尝试根据用户输入更新我的sql表。因此,用户从选择列表中选择他们想要更新的列。然后他们输入行中的数据,然后输入他们要更新的数据。所以说选择列teamname,然后将通过文本框输入他们想要更改的团队名称,然后通过另一个文本框输入新名称。这就是我想要发生的事情。
我尝试复制并粘贴用户删除数据并修改数据的代码。我尝试过几个不同的东西,我试过的第一件事给了我这个错误:
UPDATE团队SET rockets =:value1 WHERE teamname = rockets SQLSTATE [42S22]:未找到列:1054未知列'火箭'在' where子句'
我的sql语句如下所示:
$sql = "UPDATE teams SET $selectData = :value1 WHERE $columnSelect = $selectData";
然后,我尝试做这样的事情:
下面的整个代码,如上所述,我尝试了$sql
变量的几个不同的代码:
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$columnSelect = $_POST['selectColumn2'];
$selectData = $_POST['selectData'];
$updateData = $_POST['updateData'];
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 = "UPDATE teams SET :value1 = :value2 WHERE $columnSelect = :value1";
// use exec() because no results are returned
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$selectData, ':value2'=>$updateData));
if ($stmt->rowCount() > 0) {
echo 'Updated '.$stmt->rowCount().' rows';
} else {
echo 'No rows updated';
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
HTML
<form method='post' action='addData.php'>
Select a column name, then enter which data to update.
<br>
<br>
<label for='option2'>
<select name='selectColumn2'>
<option value='teamname' id='team2'>teamname</option>
<option value='city' id='city2'>city</option>
<option value='bestplayer' id='best2'>bestplayer</option>
<option value='yearformed' id='year2'>year</option>
<option value='website' id='website2'>website</option>
</select>
</label>
<label for='option2'>
select data to change: <input type='text' name='selectData'>
enter new data: <input type='text' name='updateData'>
</label>
<br><br>
<input type='submit' value='Submit New Entry'>
</form>
基本上我要做的是取$columnSelect
,在该列中找到$selectData
,然后使用PDO方法将其替换为$updateData
。我做错了什么?
答案 0 :(得分:2)
这应该有效:UPDATE teams SET $columnSelect = :value1 WHERE $columnSelect = $selectData
答案 1 :(得分:-1)
像这样更改您的查询,
$sql = "UPDATE teams SET `$selectData` = ':value1' WHERE `$columnSelect` = '$selectData'";
插入或更新时为字符串值添加单引号。并为表名或列名添加了背景。
修改强>
$sql = "UPDATE teams SET `$columnSelect` = ':value1' WHERE `$columnSelect` = '$selectData'";