【发布时间】:2015-10-30 00:37:53
【问题描述】:
我正在尝试各种方法来循环遍历 MySQL 调用过程查询 (PDO)
在以下示例中,我将更新表/数据库中的 一列。通过表单内的 HTML 表提交的 $_POST 数据。
我计划做一些其他的“表格数据”表格,并循环通过 MySQL 调用过程,其中要更新的列不止一列
所有更新查询都将基于WHERE ID = $id
我在学校使用嵌套的 foreach 循环做过类似的事情,但我在某处读到,在将数据发布到 mysql 时应该避免使用嵌套的 foreach 循环
在这种情况下,有大量表格数据的最佳方法是什么 要通过他们的主键 id 更新?
是否可以对 MySql 查询进行大规模循环,如果可以
这里最好使用哪些循环? While vs Foreach、For、Do 等?那么什么是最好的 bindParam 与 bindValue,占位符?对比 姓名等?
/* Call up data based on some criteria while loop fetch it etc */
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) // Works and echoes some tabular data O.K
/* Snippet of the POST data concerned */
<td>
<input type="text" name="allocate[]">
<input type="hidden" name="id[]" value="<?php echo $ID; ?>">
</td>
/* Echoes something of the following HTML table inside form O.K */
<tr>
<td><input type="text" name="allocate[]"><input type="hidden" name="id[]" value="1244"></td>
<td>echo stuff</td>
<td>echo unrelated</td>
</tr>
<tr>
<td><input type="text" name="allocate[]"><input type="hidden" name="id[]" value="1255"></td>
<td>echo stuff</td>
<td>echo unrelated</td>
</tr>
<tr>
<td><input type="text" name="allocate[]"><input type="hidden" name="id[]" value="1399"></td>
<td>echo stuff</td>
<td>echo unrelated</td>
</tr>
/* The submitted form part */
<?php
$db = DBConn::getConnection(); // config files etc etc
if ( isset( $_POST['id'] ) && isset( $_POST['allocate'] )) { // works
// NOTE: no validation required for trusted "In-house" data entry
/* Simple method/varibles OR ?? */
$id = $_POST['id'];
$allot = $_POST['allocate'];
/* OR ?? implode and explode array etc etc version-method (execute(array(.. ?? */
$id = explode(",",$_POST['id']);
$allot = explode(",",$_POST['allocate']);
/* The Update Query */
//$sql = "UPDATE propertyStats SET allot = :allot WHERE ps_id = :ps_id";
//$sql = "UPDATE propertyStats SET allot = ? WHERE ps_id = ?";
$sql = 'CALL updatePropSat(?,?)'; // Call procedure tested & works OK in phpMyAdmin
$stmt = $db->prepare($sql);
/* executing in an array rather foreach loop method? */
$stmt->execute(array($allot, $id));
/* FOREACH ATTEMPT /* NOTE: Form HTML was different to above HTML example */
foreach ($_POST['allocate'] as $ids => $value) {
$sql = 'CALL updatePropSat(?,?)';
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $value, PDO::PARAM_STR);
$stmt->bindValue(2, $ids, PDO::PARAM_INT);
$stmt->execute();
/* OR ALTERNATELY ?? */
$stmt->execute(array($allot, $id));
}
/* WHILE LOOP ATTEMPT ( a flop I can few )*/
$loopit = count($id); // did return correct number rows in the table/form
$i = 0;
while($i < $loopit) {
$stmt->bindParam(':allot', $allot[$i]);
$stmt->bindParam(':ps_id', $id[$i]);
$stmt->execute();
$i++;
}
【问题讨论】:
标签: mysql pdo foreach while-loop http-post