简体   繁体   English

使用多个数组更新mysql表

[英]Update mysql table with multiple arrays

I'm attempting to finalise a variation price update routine I've been working on for a few days.我正在尝试完成我已经工作了几天的变化价格更新程序。 I'm still very new PHP.我还是很新的 PHP。

I'm stuck on the final update sequence.我被困在最终的更新顺序上。 I'm not receiving any errors;我没有收到任何错误; but nothing is being updated - presumably because the SQL query is returning 0 values.但没有更新 - 大概是因为 SQL 查询返回 0 值。

Any help massively appreciated.任何帮助都非常感谢。 I'm sure it's something simple.我确定这很简单。

DESIRED RESULT: _price is updated in wp_postmeta for the initially retrieved the post_id record with the _price acquired from the post_parent record.期望的结果: _price 在 wp_postmeta 中更新,用于最初检索的 post_id 记录和从 post_parent 记录获取的 _price。 Looped for all the records in the array.循环遍历数组中的所有记录。

EXAMPLE DATA FROM FINAL DISPLAY OF RETRIVED DATA:取回数据最终显示的示例数据:

$postids (721, 735, 749, 807) $postids (721, 735, 749, 807)

$parentids (714, 740, 742, 815) $parentids (714, 740, 742, 815)

$prices (11.04, 6.32 , 7.69, 21.00) $价格(11.04、6.32、7.69、21.00)

In an ideal world I'd also like to include a formula to multiply the _price by 2.1 prior/during to insertion/update.在理想的世界中,我还想包含一个公式,在插入/更新之前/期间将 _price 乘以 2.1。

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);
//Array and display POST_IDs
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["post_id"]. "<br>";
    }
} else {
   echo "0 results";
}
//Prepare POST_IDs for next query
$postids = [];
foreach ($result as $row){
    $postids[] = $row["post_id"];
}


//Use POST_IDs to select all PARENT_IDs
if (!empty($postids)) {
$sql2 = "SELECT post_parent FROM wp_posts WHERE ID IN (".implode(',',$postids).")";
}
$result2 = $conn->query($sql2);
//Array and display PARENT_IDs
if ($result2->num_rows > 0) {
    // output data of each row
    while($row2 = $result2->fetch_assoc()) {
        echo "parentid: " . $row2["post_parent"]. "<br>";
    }
} else {
    echo "0 results";
}
//Prepare PARENT_IDs for next query
$parentids = [];
foreach ($result2 as $row2){
    $parentids[] = $row2["post_parent"];
}
//Select PRICES using PARENT_IDs and META_KEY for Price
if (!empty($parentids)) {
$sql3 = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_price' AND post_id IN (".implode(',', $parentids).")";
}
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
    // output data of each row
    while($row3 = $result3->fetch_assoc()) {
        echo "price: " . $row3["meta_value"]. "<br>";
    }
} else {
    echo "0 results";
}
//Array and display PRICES
$prices = [];
foreach ($result3 as $row3){
    $prices[] = $row3["meta_value"];
}
//Display all retrieved data
echo "<div><p><table><tr><td> ".implode('<br>', $postids)." </td><td> ".implode('<br>', $parentids)." </td><td> ".implode('<br>', $prices)." </td></tr></table></p></div>";
//UPDATE variant prices with parent prices
foreach ($prices as $key => $postids){
    $prices = $row3["meta_value"];
    $postids = $row["post_id"];
$sqlupdate = "UPDATE wp_postmeta SET meta_value = $prices WHERE post_id = $key AND meta_key = '_price'";
$update = $conn->query($sqlupdate);
     if (!$sqlupdate)  {
        echo "error updating $prices" . mysql_error();
     }
}
$conn->close();
?>

You are trying to consume ALL your query result set's twice.您正试图两次使用所有查询结果集。 Once a query result set is consumed by a while loop it is like getting to the end of a file, it is finished一旦查询结果集被while循环消耗,就像到达文件末尾一样,它就完成了

Merge all 3 of the 2 loops you are using into one loop that outputs and creates the array at the same time.将您正在使用的 2 个循环中的所有 3 个合并到一个循环中,该循环同时输出和创建数组。 Like this像这样

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);

//Array and display POST_IDs

$postids = [];
if ($result->num_rows > 0) {
    // output data of each row
    // and save in array for later use

    while($row = $result->fetch_assoc()) {
        $postids[] = $row["post_id"];
        echo "id: " . $row["post_id"]. "<br>";
    }
} else {
   echo "0 results";
}
/*
No longer needed
//Prepare POST_IDs for next query
foreach ($result as $row){
    $postids[] = $row["post_id"];
}
*/

//Use POST_IDs to select all PARENT_IDs
if (!empty($postids)) {
    $sql2 = "SELECT post_parent 
            FROM wp_posts 
            WHERE ID IN (".implode(',',$postids).")";
}

$result2 = $conn->query($sql2);

//Array and display PARENT_IDs
$parentids = [];
if ($result2->num_rows > 0) {
    // output data of each row
    while($row2 = $result2->fetch_assoc()) {
        $parentids[] = $row2["post_parent"];
        echo "parentid: " . $row2["post_parent"]. "<br>";
    }
} else {
    echo "0 results";
}

//Select PRICES using PARENT_IDs and META_KEY for Price
if (!empty($parentids)) {
    $sql3 = "SELECT meta_value 
                    FROM wp_postmeta 
                    WHERE meta_key = '_price' 
                    AND post_id IN (".implode(',', $parentids).")";
}

$result3 = $conn->query($sql3);

$prices = [];
if ($result3->num_rows > 0) {
    // output data of each row
    while($row3 = $result3->fetch_assoc()) {
        $prices[] = $row3["meta_value"];
        echo "price: " . $row3["meta_value"]. "<br>";
    }
} else {
    echo "0 results";
}

//Display all retrieved data
echo "<div><p><table><tr><td> ".implode('<br>', $postids)." </td><td> ".implode('<br>', $parentids)." </td><td> ".implode('<br>', $prices)." </td></tr></table></p></div>";

And here you are overwriting the $prices array that your loop creates inside your loop.在这里,您将覆盖循环在循环内创建的 $prices 数组。 And using a $row3 resultset that no longer exists!并使用不再存在的$row3结果集!

I am afraid I am not at all sure about the data so this last bit of code chnage is a bit of a guess.恐怕我对数据完全不确定,所以最后一点代码更改有点猜测。

//UPDATE variant prices with parent prices
foreach ($prices as $key => $postids){

    //$prices = $row3["meta_value"];
    $price = $postids

    //$postids = $row["post_id"];

    $sqlupdate = "UPDATE wp_postmeta 
                    SET meta_value = $price 
                    WHERE post_id = $key 
                    AND meta_key = '_price'";
    $update = $conn->query($sqlupdate);
    if (!$sqlupdate)  {
        echo "error updating $prices" . mysql_error();
    }
}
$conn->close();
?>

This was a simple solution in the end.这最终是一个简单的解决方案。 As I said in the question, I am a PHP beginner.正如我在问题中所说,我是一名 PHP 初学者。 A bit of further understanding RE arrays was required on my part.我需要进一步了解 RE 数组。 This is the final query if anyone is interested.如果有人感兴趣,这是最后的查询。

//UPDATE variant prices with parent prices
foreach ($prices as $key => $np){
    $pid = $postids["$key"];
    $sqlupdate = "UPDATE wp_postmeta 
                    SET meta_value = $np
                    WHERE post_id = $pid 
                    AND meta_key = '_price'";
    $update = $conn->query($sqlupdate);
    if(mysqli_query($conn, $sqlupdate)){
        echo "Records were updated successfully.";
    } else {
        echo "ERROR: Was not able to execute $sqlupdate. " . mysqli_error($link);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM