1

I wrote this quick script which updates the database when moving the location of the word press blog. The question: It would be good if it showed how many rows have been updated. Is this possible?

 <?php
if(isset($_GET['confirm'])){

    // Load Wordpress
    require_once('wp-load.php');

    // Form variables
    $site_was = $_GET['site_was'];
    $site_now = $_GET['site_now'];

    $db_queries = array(
        "UPDATE wp_options SET option_value = replace(option_value, '".$site_was."', '".$site_now."') WHERE option_name = 'home' OR option_name = 'siteurl'",
        "UPDATE wp_posts SET guid = REPLACE (guid, '".$site_was."', '".$site_now."')",
        "UPDATE wp_posts SET post_content = REPLACE (post_content, '".$site_was."', '".$site_now."')",
        "UPDATE wp_posts SET post_content = REPLACE (post_content, 'src=\"".$site_was."', 'src=\"".$site_now."')",
        "UPDATE wp_posts SET  guid = REPLACE (guid, '".$site_was."', '".$site_now."') WHERE post_type = 'attachment'",
        "UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, '".$site_was."','".$site_now."')"
    );

    foreach ($db_queries as $sql) {
        $wpdb->query($sql);
    }

} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
    <p>E.g http://examples.com or http://www.example.com/shop</p>
    <label>
        Site was:
        <input type="text" name="site_was" value="<?php if(isset($_GET['site_was'])) echo $_GET['site_was']?>" size="50" />
    </label>
    <br />
    <label>
        Site now:
        <input type="text" name="site_now" value="<?php if(isset($_GET['site_now'])) echo $_GET['site_now']?>" size="50" />
    </label>

    <input type="submit" name="confirm" value="Update Datebase" />
</form>
<?php } ?>
1
  • 1
    I don't have your answer but i see you are using the full table names. it's better to use $wpdb->prefix.'options' instead of 'wp_options', if you ever change the table prefix you won't have to adjust your queries Commented Jan 10, 2012 at 4:46

1 Answer 1

2

You should be calling $wpdb->update() with the relevant table rows and data. That will return the number of affected rows.

e.g.

$rows = $wpdb->update( 
    'table', 
    array( 
        'column1' => 'value1',  // string
        'column2' => 'value2'   // integer (number) 
    ), 
    array( 'ID' => 1 ), 
    array( 
        '%s',   // value1
        '%d'    // value2
    ), 
    array( '%d' ) 
);

See here: http://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows

Sign up to request clarification or add additional context in comments.

2 Comments

How would I set the WHERE with an OR?
Oh, well if you need to be that specific you can do $rows = $wpdb->query($wpdb->prepare($query))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.