因此,我正在尝试为用户创建一个界面,他们可以在其中通过 php UX 插入、删除和更新他们在 sql db 中的表。我已经掌握了基础知识,但是我遇到了试图保持动态感觉的墙壁。因此,假设假设地说,一个新列被添加到他们试图从 sql 方面更新的特定表中。现在我有了它,它会显示添加的新列,但是如何在我的 UPDATE sql 查询中包含该新列。我为每一列指定了变量(即 $user、$pass、$email),但我的问题是,如果他们添加了一个新列,我们如何设置代码以便它自动添加一个新变量并保持动态?我快疯了,真的需要别人的帮助,因为这听起来很简单。
谢谢你们所有的帮助!请让我知道如何为任何人澄清这个问题。
以下是我更新具有固定列的表的工作代码。请告知我需要添加或更改的内容。
<?php
$result = sqlsrv_query($con,"SELECT * FROM table");
$colresult = sqlsrv_query($con,"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'table' AND TABLE_SCHEMA='schema'");
$serverName = xxx";
$connectionInfo = array("Database"=>"db", "UID"=>"user", "PWD"=>"pass", 'ReturnDatesAsStrings'=> true, "CharacterSet" => 'utf-8');
$con = sqlsrv_connect( $serverName, $connectionInfo);
$numfields = sqlsrv_num_fields($result);
if( $con ) {
echo "Connection established.<br />";
}
else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
if (isset($_POST['updatemarked']))
{
foreach($_POST["id"] AS $id){
**$user = $_POST["username"][$id];
$pass = $_POST["password"][$id];
$email = $_POST["email"][$id];**
if(!$user){
}
else{
$sqlupdate= sqlsrv_query($con,"UPDATE table SET username = '$user' WHERE id = $id");
}
if(!$pass){
//$pass = 'empty';//$row['password'];
}
else{
$sqlupdate= sqlsrv_query($con,"UPDATE table SET password = '$pass' WHERE id = $id");
}
if(!$email){
//$email = 'empty';//$row['email'];
}
else{
$sqlupdate= sqlsrv_query($con,"UPDATE table SET email = '$email' WHERE id = $id");
}
}
}
echo '
<form action="table.php" method="post">
<table table class="dynamicTable tableTools table table-striped table-bordered table- condensed table-white">';
echo '<tr>';
echo '<th width="50" align="center"><span style=color:black><strong>Select(s)</strong> </span></th>';
while($row = sqlsrv_fetch($colresult)){
$fieldname = sqlsrv_get_field($colresult, $i);
echo "<th>".$fieldname."</th>";
}
echo "</tr>";
while ($row = sqlsrv_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="id[]" value="'.$row['id'].'" /></td>';
echo "<td>".$row['id']."</td>";
echo '<td><input type="text" name="username['.$row['id'].']" placeholder="'.$row['username'].'"/></td>';
echo '<td><input type="text" name="password['.$row['id'].']" placeholder="'.$row['password'].'"/></td>';
echo '<td><input type="text" name="email['.$row['id'].']" placeholder="'.$row['email'].'"/></td>';
echo "</tr>";
}
echo'</table>';
echo'<br />';
echo '<div align="center">';
echo '<input type="submit" name="updatemarked" value="Update Selected" />';
echo '</div>';
echo '</form>';
?>