如何使用php PDO查找和替换

时间:2017-03-10 03:50:59

标签: php mysql wordpress pdo

我需要使用PHP 7并建议使用PDO。我的原始代码看起来像这样......

 <?php 

function sentence()  {
    global $post;
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query('set names "utf8"'); 
$query="SELECT name FROM seo ORDER BY RAND() LIMIT 10;";
$result=mysql_query($query);
$num=mysql_numrows($result);

//Begin find and replace
while($row = mysql_fetch_array($result))
{
//this is the string to look into
$myString = $row['name'];
//this is the thing to look for
$patterns = array();
$patterns[0] = '/1111/';
$patterns[1] = '/2222/';
$patterns[2] = '/3333/';
$patterns[3] = '/4444/';
$patterns[4] = '/5555/';
$patterns[5] = '/6666/';
$patterns[6] = '/1234/';
//this is what you replace it with
$result1 = $post->post_title; 
//this is the echo
echo preg_replace($patterns, $result1, $myString);

}
mysql_close();
}


?>

这个php代码的作用是连接数据库,然后是表&#34; seo&#34;。在表中查找名为&#34; name&#34;的列,选择随机10行,并在其中找到字符串&#34; 1111&#34;,将其替换为wordpress post title。输出10个随机行,替换为&#34; 1111&#34;帖子标题。

这在PHP 5中运行得很好,但在PHP 7中没有那么多。我被告知使用php PDO for PHP 7.这是我到目前为止所拥有的...

<?php

$hostdb   = 'localhost';
$dbname   = 'database';
$username = 'user';
$password = 'password';
$table    = 'seo';

    $pdo = new PDO("mysql:host=$hostdb;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql  = "SELECT name FROM $table ORDER BY RAND() LIMIT 2;";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    $result = $stmt->fetchAll();

            //echo '<pre>';
            //print_r($result);
            //echo '</pre>';  

?>

如何实际查找和替换&#34; 1111&#34;帖子标题有点超出我的意义。任何帮助都将非常感激。

谢谢

0 个答案:

没有答案