如何使用php PDO查找和替换
我需要使用PHP7,有人建议我使用PDO。我的原始代码如下所示如何使用php PDO查找和替换,php,mysql,wordpress,pdo,Php,Mysql,Wordpress,Pdo,我需要使用PHP7,有人建议我使用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="SE
<?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();
}
?>
如果您想替换一行中的某个内容,可以使用更新
queryOk cool。这里看起来像什么?我对编程非常陌生。奇怪的是,你问的代码与数据库无关,基本上保持不变,不管你使用的是什么数据库。这真的是你上面贴的代码吗?
<?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>';
?>