二款PostgreSQL连接数据的方法和操作实例

 更新时间:2016年11月25日 16:39  点击:1704
 代码如下 复制代码

$pg=@pg_connect("host=localhost user=postgres password=sa dbname=employes")
or die("can't connect to database.");
$query="select * from employes order by serial_no";

//$query="insert into employes values(10008,'susan','1985-09-04','80','50')";
$result=@pg_query($pg,$query) or die("can't run query to table.");
//echo pg_num_rows($result); //输出多少条记录被查询
//if($result)
//{
//echo "recrods inserted sucessfully!";
//echo pg_affected_rows($result);//输出多少条记录被插入
//}

//实例一[pg_fetch_row]
echo "<table border=1>";
echo "<tr>";
echo "<td>serial_no</td>";
echo"<td>name</td>";
echo"<td>birthday</td>";
echo"</tr>";

for($i=0;$i<pg_num_rows($result);$i++)
{

$row=@pg_fetch_row($result) or die("can't fetch row from table.");
$serial_no= $row[0];
$name= $row[1];
$birthday= $row[2];
echo"<tr>";
echo"<td>$serial_no</td>";
echo"<td>$name</td>";
echo"<td>$birthday</td>";
echo"</tr>";

}
echo"</table>";

//实例二[pg_fetch_array]
//echo "<table border=1>";
//echo "<tr>";
//echo "<td>serial_no</td>";
//echo"<td>name</td>";
//echo"<td>birthday</td>";
//echo"</tr>";
//
//for($i=0;$i<pg_num_rows($result);$i++)
//{
//
//$row=@pg_fetch_array($result) or die("can't fetch row from table.");
//$serial_no= $row['serial_no'];
//$name= $row['name'];
//$birthday= $row['birthday'];
//echo"<tr>";
//echo"<td>$serial_no</td>";
//echo"<td>$name</td>";
//echo"<td>$birthday</td>";
//echo"</tr>";
//
//}
//echo"</table>";

//增加,删除,修改实例
//$newrow=array("serial_no"=>"1006","name"=>"peter","birthday"=>"1990-07-03","salary"=>"90","bonus"=>"80");
//$reusult=@pg_insert($pg,"employes",$newrow) or die("can't insert data to table.");
//if($reusult)
//{
//echo "rechords inserted sucessfully!";
//}
//
pg_close($pg);

这是一款简单的php留言板程序代码,如果你正学习网站开发,这款留言板源码可以帮助哦,希望本文章对你有帮助。
 代码如下 复制代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gbk" />
<title>所有留言</title>
<link rel="stylesheet" type="text/css教程" href="style.css" media="all" />
</head>

<body>
<a href="add.php">发表留言</a>
<?php
require('common.php');
$result = mysql教程_query("select * from gb_content order by id desc");//查询数据

while ($row = mysql_fetch_array($result, mysql_both)) {// 取一条数据
?>
<table width="700" border="0" cellspacing="0" cellpadding="0" class="tb">
  <tr>
    <td class="bg"><b>[<?php echo htmlentities($row['username'],ent_compat,'utf-8') ?>]</b> 发表于:<?php echo htmlentities($row['insert_time'],ent_compat,'utf-8') ?></td>
  </tr>
  <tr>
    <td><?php echo htmlentities($row['content'],ent_compat,'utf-8') ?></td>
  </tr>
  <tr>
    <td align="right"><a href="edit.php?id=<?php echo $row['id'] ?>">修改</a> <a href="delete.php?id=<?php echo $row['id'] ?>">删除</a></td>
  </tr>
</table>
<?php
}

mysql_free_result($result);

?>
</body>
</html>

 

本款php连接mysql数据库连接程序代码是一款比较简单实用的连接代码,希望本教程对各位同学会有所帮助哦。

 代码如下 复制代码

class mysql {
      public $sqlserver = 'localhost';
      public $sqluser = 'root';
      public $sqlpassword = '';
      public $database;

      public $last_query = '';

      private $connection;
      private $query_result;

      public function __construct() {}

      public function __destruct() {
       $this->close();
      }

    //+======================================================+
    // create a connection to the mysql database
    //+======================================================+
    public function connect($server = null, $user = null, $password = null, $database = null){
     if (isset($server)) $this->sqlserver = $server;
     if (isset($user)) $this->sqluser = $user;
     if (isset($password)) $this->sqlpassword = $password;
     if (isset($database)) $this->database = $database;

    $this->connection = mysql_connect($this->sqlserver, $this->sqluser, $this->sqlpassword);
    if($this->connection){
    if (mysql_select_db($this->database)){
    return $this->connection;
    }else{
    return $this->error();
    }
    }else{
    return $this->error();
    }
    }
    //+======================================================+
    // execute a query
    //+======================================================+
    public function query($query, $die = false){
      if ($query != null){
       $this->last_query = $query;
       $this->query_result = mysql_query($query, $this->connection);
       if(!$this->query_result){
        if ($die) die("die: ".$this->query_result);
        return $this->error();
       }else{
        if ($die) die("die: ".$this->query_result);
        return $this->query_result;
       }
      }else{
       echo "empty query cannot be executed!";
      }
    }
    //+======================================================+
    // returns the result
    //+======================================================+
    public function getresult(){
       return $this->query_result;
    }
    //+======================================================+
    // returns the connection
    //+======================================================+
    public function getconnection(){
       return $this->connection;
    }
    //+======================================================+
    // returns an object with properties rep
    //     resenting the result fields www.111cn.net and values
    //+======================================================+
    public function getobject($qry = null){
     if (isset($qry)) $this->query($qry);
     return mysql_fetch_object($this->getresult());
    }
    //+======================================================+
    // returns an array with keys representi
    //     ng the result fields and values
    //+======================================================+
    public function getarray($query_id = ""){
      if($query_id == null){
       $return = mysql_fetch_array($this->getresult());
      }else{
       $return = mysql_fetch_array($query_id);
      }
      return $return ? $return : $this->error();
    }
    //+======================================================+
    // returns the number of rows in the res
    //     ult
    //+======================================================+
      public function getnumrows($qry = null){
       if (isset($qry)) $this->query($qry);
       $amount = mysql_num_rows($this->getresult());
       return empty($amount) ? 0 : $amount;
    }
    //+======================================================+
    // returns if the result contains rows
    //+======================================================+
    public function hasresults($qry = null) {
      if (isset($qry)) $this->query($qry);
     return $this->getnumrows($qry) > 0;
    }
    //+======================================================+
    // returns the number of rows that where
    //     affected by the last action
    //+======================================================+
    public function getaffectedrows($qry = null, $query_id = null){
      if (isset($qry)) $this->query($qry);
      if(empty($query_id)){
       $return = mysql_affected_rows($this->getresult());
      }else{
       $return = mysql_affected_rows($query_id);
      }
      return $return ? $return : $this->error();
    }
    //+======================================================+
    // returns the auto generated id from th
    //     e last insert action
    //+======================================================+
    public function getinsertid($connection_link = null){
    return mysql_insert_id(isset($connection_link) ? $connection_link : $this->connection);
    }
    //+======================================================+
    // close the connection to the mysql dat
    //     abase
    //+======================================================+
    public function close(){
    if(isset($this->connection)){
    return @mysql_close($this->connection);
    }
    else {
     return $this->error();
    }
    }
    //+======================================================+
    // outputs the mysql error
    //+======================================================+
    private function error(){
    if(mysql_error() != ''){
    echo '<b>mysql errorwww.111cn.net</b>: '.mysql_error().'<br/>';
    }
    }
    }

    //demo
    // database object initialization
$db = new mysql();
$db->connect("localhost", "root", "123456", "user");

// update query
//$db->query("update table_name set field_name = value where another_field = another_value");

// select with check for record amount

if ($db->hasresults("select * from userinfo")) {
//   loop through the user records, and get them as objects
//   note that the getobject method will use the last executed query when not provided with a new one
  while ($user = $db->getobject()) {
    echo "user $user->username is called $user->password<br /> ";
  }
}
else {
  echo "no results where found";
}

本程序实现数据导入原理是先把csv文件上传到服务器,然后再通过php的fopen与fgetcsv文件把数据保存到数组,然后再用while把数据一条条插入到mysql数据库
 代码如下 复制代码
$fname = $_files['myfile']['name'];
$do = copy($_files['myfile']['tmp_name'],$fname);
if ($do){
echo"导入数据成功<br>";
}else{
echo "";
}

 

 代码如下 复制代码

error_reporting(0);// 导入csv格式的文件
$connect=mysql_connect("localhost","root","") or die("could not connect to database");
mysql_select_db("gklqtzcx",$connect) or die (mysql_error());
mysql_query("set names 'gbk'");
$fname = $_files['myfile']['name'];
$handle=fopen("$fname","r");
while($data=fgetcsv($handle,10000,",")){
$q="insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
mysql_query($q) or die (mysql_error());
}
fclose($handle);
echo "<meta http-equiv="refresh" content="1;url=list.php">1秒钟转入列表页,请稍等."

?>
<form enctype="multipart/form-data" action="<?php echo"".$_server["php_self"].""; ?>" method="post">
<p>导入cvs数据 <input name="myfile" type="file"> <input value="提交" type="submit">
</p>
</form>

 代码如下 复制代码

class excel{

    /**
     *头的excel文件(前缀的行)
     *
     *从excel复制的xml规格。
     *
     * @访问私有
     * @无功串
     */
    var $header = "<?xml version="1.0" encoding="utf-8"?>
<workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/tr/rec-html40">";

    /**
     *页脚的excel文件(附加到行)
     *
     *从excel复制的xml规格。
     *
     * @访问私有
     * @无功串
     */
    var $footer = "</workbook>";

    /**
     * document lines (rows in an array)
     *
     * @access private
     * @var array
     */
    var $lines = array ();

    /**
     工作表名称
     *
     *包含一个单一的工作表名称
     *
     * @访问私有
     * @无功串
     */
    var $worksheet_title = "table1";

    /**
  添加一个单行的文档字符串$
     *
     * @访问私有
     * @帕拉姆库马拉阵列一维阵列
     * @待办事项行创造应做减本-> addarray
     */
    function addrow ($array) {

        // initialize all cells for this row
        $cells = "";
       
        // foreach key -> write value into cells
        foreach ($array as $k => $v):
   
         // 加个字符串与数字的判断 避免生成的 excel 出现数字以字符串存储的警告
         if(is_numeric($v)) {
          // 防止首字母为 0 时生成 excel 后 0 丢失
          if(substr($v, 0, 1) == 0) {
           $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
          } else {
           $cells .= "<cell><data ss:type="number">" . $v . "</data></cell> ";
          }
         } else {
             $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
         }

        endforeach;

        // transform $cells content into one row
        $this->lines[] = "<row> " . $cells . "</row> ";

    }

    /**
    *添加一个数组到文档
     *
     *这应该是唯一的方法需要生成一个excel
     *文件。
     *
     * @访问公开
     * @帕拉姆库马拉数组二维数组
     * @待办事项可以转移到__construct()稍后
     */
    function addarray ($array) {

        // run through the array and add them into rows
        foreach ($array as $k => $v):
            $this->addrow ($v);
        endforeach;

    }

    /**
    设置工作表名称
     *
     *检查的字符串不允许字符(: /?*),
     *削减它的最大31个字符,并设置标题。该死
     *为何未允许字符无处可寻?视窗
     *帮助没有帮助...
     *
     * @访问公开
     * @帕拉姆库马拉字符串$标题设计标题
     */
    function setworksheettitle ($title) {

        // strip out special chars first
        $title = preg_replace ("/[\|:|/|?|*|[|]]/", "", $title);

        // now cut it to the allowed length
        $title = substr ($title, 0, 31);

        // set title
        $this->worksheet_title = $title;

    }

   /**
     *生成excel文件
     *
     *最后生成的excel文件,并使用header()函数
     *提供给浏览器。
     *
     * @访问公开
     * @帕拉姆库马拉字符串$文件名名称的excel文件来生成(... xls)中
     */
    function generatexml ($filename) {

        // deliver header (as recommended in php manual)
        header("content-type: application/vnd.ms-excel; charset=utf-8");
        header("content-disposition: inline; filename="" . $filename . ".xls"");

        // print out document to the browser
        // need to use strips教程lashes for the damn ">"
        echo stripslashes ($this->header);
        echo " <worksheet ss:name="" . $this->worksheet_title . ""> <table> ";
        echo "<column ss:index="1" ss:autofitwidth="0" ss:width="110"/> ";
        echo implode (" ", $this->lines);
        echo "</table> </worksheet> ";
        echo $this->footer;

    }

}

/**
 *  cakephp中使用方法
 *  注意 ** cakephp 配置文件 define('debug', 0);
 *
 *  vendor ('excel');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new excel;
 *  $xls->addarray ( $doc );
 *  $xls->generatexml ("mytest");
 */

/**
 *  非框架使用方法
 *
 *  require_once('excel.php');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new excel;
 *  $xls->addarray ( $doc );
 *  $xls->generatexml ("mytest");
 */

[!--infotagslink--]

相关文章

  • php 中file_get_contents超时问题的解决方法

    file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结。...2016-11-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • php简单数据操作的实例

    最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • HTTP 408错误是什么 HTTP 408错误解决方法

    相信很多站长都遇到过这样一个问题,访问页面时出现408错误,下面一聚教程网将为大家介绍408错误出现的原因以及408错误的解决办法。 HTTP 408错误出现原因: HTT...2017-01-22
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • Antd-vue Table组件添加Click事件,实现点击某行数据教程

    这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • 详解如何清理redis集群的所有数据

    这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • vue 获取到数据但却渲染不到页面上的解决方法

    这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
  • intellij idea快速查看当前类中的所有方法(推荐)

    这篇文章主要介绍了intellij idea快速查看当前类中的所有方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • Mysql select语句设置默认值的方法

    1.在没有设置默认值的情况下: 复制代码 代码如下:SELECT userinfo.id, user_name, role, adm_regionid, region_name , create_timeFROM userinfoLEFT JOIN region ON userinfo.adm_regionid = region.id 结果:...2014-05-31
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ht...2013-10-13
  • mybatis-plus 处理大数据插入太慢的解决

    这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
  • php把读取xml 文档并转换成json数据代码

    在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
  • mysql 批量更新与批量更新多条记录的不同值实现方法

    批量更新mysql更新语句很简单,更新一条数据的某个字段,一般这样写:复制代码 代码如下:UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value';如果更新同一字段为同一个值,mysql也很简单,修改下where即...2013-10-04
  • js基础知识(公有方法、私有方法、特权方法)

    本文涉及的主题虽然很基础,在许多人看来属于小伎俩,但在JavaScript基础知识中属于一个综合性的话题。这里会涉及到对象属性的封装、原型、构造函数、闭包以及立即执行表达式等知识。公有方法 公有方法就是能被外部访问...2015-11-08
  • ps怎么制作倒影 ps设计倒影的方法

    ps软件是一款非常不错的图片处理软件,有着非常不错的使用效果。这次文章要给大家介绍的是ps怎么制作倒影,一起来看看设计倒影的方法。 用ps怎么做倒影最终效果&#819...2017-07-06
  • PHP 验证码不显示只有一个小红叉的解决方法

    最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04