简体   繁体   中英

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.

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.

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. Looped for all the records in the array.

EXAMPLE DATA FROM FINAL DISPLAY OF RETRIVED DATA:

$postids (721, 735, 749, 807)

$parentids (714, 740, 742, 815)

$prices (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.

// 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

Merge all 3 of the 2 loops you are using into one loop that outputs and creates the array at the same time. 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. And using a $row3 resultset that no longer exists!

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. A bit of further understanding RE arrays was required on my part. 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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