有没有一种方法可以用php更新mysql表,而无需事先知道这些值?

时间:2018-12-19 19:23:01

标签: php mysql

我正在使用以下代码来获取我的mysql表的行和列标题,而无需事先知道它们并格式化表格。我正在创建一项服务,该服务允许用户生成表并将其保存到mysql数据库中,因此我需要能够以这种方式检索数据。

我正在尝试更新和编辑他的表格并使之生效。通常,这是通过在知道所有列值的情况下分别更新每个值来完成的。

这是我获取值的代码

<?php
 try {
 $con= new PDO('mysql:host=localhost;dbname=xxx', "", "");
 $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $query = "SELECT * FROM ``
 //first pass just gets the column names
 print "<table>";
 $result = $con->query($query);
 //return only the first row (we only need field names)
 $row = $result->fetch(PDO::FETCH_ASSOC);
 print " <tr>";
 foreach ($row as $field => $value){
 print " <th>$field</th>";
 } // end foreach
 print " </tr>";
 //second query gets the data
 $data = $con->query($query);
 $data->setFetchMode(PDO::FETCH_ASSOC);
 foreach($data as $row){
 print " <tr>";
 foreach ($row as $name=>$value){
 print " <td>$value</td>";
 } // end field loop
 print " </tr>";
 } // end record loop
 print "</table>";
 } catch(PDOException $e) {
 echo 'ERROR: ' . $e->getMessage();
 } // end try
?>

我正在尝试使用以下内容来更新值:

foreach($_POST as $name=>$value)
{
    if($value != '')
{
    echo "$name: $value\n";
}
}

但是,行值根本没有更新。有什么方法可以在每次编辑值时扫描表并更新值?

1 个答案:

答案 0 :(得分:0)

您不需要执行两次查询。您可以使用columnCount()getColumnMeta()方法来获取所有列名。

$result = $con->query($query);
$colCount = $result->columnCount();
echo "<tr>";
for ($i = 0; $i < colCount; $i++) {
    $name = $result->getColumnMeta()["name"];
    echo "<th>$name</th>";
}
echo "</tr>";