0

我正在尝试将此代码从 Java 复制到 php 中,但我无法完全弄清楚如何获取行/列的内容?

这是java代码:

ResultSet resultsRS = statement.executeQuery("select distinct snum from shipments where quantity >= 100");

int rowCount=0;

while(resultsRS.next()){
    statement2.executeUpdate("UPDATE suppliers SET status = status + 5 WHERE snum = "+"\""+resultsRS.getString(1)+"\"");
    rowCount++;  
}

到目前为止,我在 php 中有这个:

$result2 = mysqli_query($database,"select distinct snum from shipments where quantity >= 100");

$rowCount = 0;

foreach($result2 as $shipment){
    mysqli_query($database,"UPDATE suppliers SET status = status + 5 WHERE snum = "."\"".$shipment."\"");
    rowCount++;
}

但是,这并没有按预期工作。

另外,如果您注意到我想要的只是要更新一个特定的列。

编辑:让它工作

对于阅读的每个人,我都可以通过以下代码得到我想要的东西:

for($counter=0; $row = mysqli_fetch_row($result2);$counter++){              
   foreach($row as $key=> $value){  
       mysqli_query($database,"UPDATE suppliers SET status = status + 5 WHERE snum = "."\"".$value."\"");
       $rowCount++;
   }                            
}
4

3 回答 3

1

你应该阅读 PHP MYSQLI 文档:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Mysqli 获取

于 2013-08-02T08:15:36.007 回答
1

正如您可以在 php.net 站点 ( http://php.net/manual/en/mysqli.query.php )上阅读的那样,它mysqli_query返回一个mysqli_result对象 ( http://www.php.net/manual/en/class。 mysqli-result.php)。

fetch_*您必须使用其中一个函数从结果中获取行。

例如:

$result2 = mysqli_query($database,"select distinct snum from shipments where quantity >= 100");

$rowCount = 0;

while($shipment = $result2->fetch_assoc()){
    mysqli_query($database,"UPDATE suppliers SET status = status + 5 WHERE snum = "."\"".$shipment['snum']."\"");
    rowCount++;
}
于 2013-08-02T08:16:39.843 回答
0

处理这种情况的“最佳实践”解决方案是首先在循环之外“准备”查询,然后在循环期间将参数绑定到它。这避免了 SQL 注入;虽然在这种可能不是问题的特定情况下,最好不要直接在查询中注入数据,而是始终使用参数绑定。它看起来也更好,更容易理解,没有所有的引用废话:)

$result2 = mysqli_query($database,"select distinct snum from shipments where quantity >= 100");
$query = mysqli_prepare($database, 'UPDATE suppliers SET status = status + 5 WHERE snum = ?');
// Check for errors. This is obviously not the right way to handle this when going into production...
if(!$query) {
    var_dump(mysqli_error($database));
    die();
}
foreach($result2 as $shipment){
    $snum = $shipment['snum'];
    $query->bind_param('s', $snum);
    $query->execute();
    $rowCount++;
}

您可能还想通过首先收集所有 ID 来优化这一点,然后为整批 ID 发出单个更新语句。

此外,我希望您能够使用单个查询来执行此操作,对连接执行更新......因此,如果考虑到性能,您可能也想研究一下。

于 2013-08-02T08:33:01.750 回答