重写连接和从mysql到mysqli的查询

时间:2013-02-03 13:30:23

标签: php mysqli

始终使用PHP MySQL与典型的mysql_querymysql_fetch_array,但现在我转移到Mysqli,因为它将是未来。

我是新手,并将其用于个人,所以我决定问你如何在Mysqli的规则中重写所有这些

让我们假设我们有以下数据库users(id,name,job,number)

CREATE TABLE `users` (
  `id` bigint(20) unsigned NOT NULL auto_increment,
  `name` varchar(255) default '0',
  `job` varchar(255) default NULL,
  `number` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

INSERT INTO `users` VALUES (1, 'John', 'Plumber', '555');
INSERT INTO `users` VALUES (2, 'Iva', 'Reporter', '666');
INSERT INTO `users` VALUES (3, 'Robert', 'Writer', '777');
INSERT INTO `users` VALUES (4, 'Irin', 'Writer', '888');

现在那些是正常的Mysql所以任何人都可以重写为Mysqli

1)连接

$DB["host"]   = "localhost";
$DB["dbName"] = "dbname";
$DB["user"]   = "dbuser";
$DB["pass"]   = "dbpass";
$link = mysql_connect($DB["host"],$DB["user"],$DB["pass"]) or die("Connection Failed");
mysql_select_db($DB["dbName"]);

2)从数据库确切的条目中调用

    $sql = "select * from users where job='Plumber'";
    $reg = mysql_query($sql) or die(mysql_error());
    $aee = mysql_fetch_array($reg);

    echo $aee[name]; // should gives name John

3)从数据库结果调用

$qry="select * from users where job='Writer'";
$result=mysql_query($qry) or die($qry);

if(mysql_num_rows($result)=='0'){

echo "No results"; // if not found any for this conditional job

}else{
while($line=mysql_fetch_array($result)){

echo $line[name]."<br>"; // should gives Robert <br> Irin

}
}

这对我很有帮助,并且不鼓励我为insert,update,delete打开下一个新问题,因为我相信这对像我这样的新手很有帮助〜谢谢

1 个答案:

答案 0 :(得分:1)

我的答案不是关于“如何从一个原始API重写到另一个原始API”而是“它是如何倾向于”的主题

1)连接

$params["db"]   = "dbname";
$params["user"] = "dbuser";
$params["pass"] = "dbpass";
$db = new DB($params);

2)从数据库确切的条目中调用

echo $db->getOne("select name from users where job='Plumber'");

3)从数据库结果调用

$data = $db->getAll("select * from users where job='Writer'");
// assuming the following code inside of PHP template
?>
<? if(!$data): ?>
    No results
<? else: ?>
<ul>
    <? foreach($data as $line): ?>
    <li><?=$line['name']?></li>
    <? endforeach ?>
</ul>
<? endif ?>