IT猫扑网文章教程

分类分类

PHP访问MYSQL数据库快速入门

2015-06-28 00:00作者:网管联盟

  连接

<?php
  //下面使用了函数库mysqli,所以需要将php.ini文件中的extension=php.mysqli 打开
  //这里采用了面向对象的语法,当然,mysqli也支持面向过程的语法
  @ $db = new mysqli('localhost', 'root', 'tograce', 'books');
  //以上代码实例化了mysqli类并且创建了到主机'localhost'的连接,该连接使用的用户名为和密码分别是:root,tograce,同时连接上books数据库
  if (mysqli_connect_errno())
  {
     echo 'Error: Could not connect to database.  Please try again later.';
     exit;
  }
  else{echo &gong xi,Connected successfully&;}
 
  $query = &select * from books&;
  $result = $db->query($query);
  $num_results = $result->num_rows;
  echo '<p>Number of books found: '.$num_results.'</p>';

  $result->free();
  $db->close();
?>

  插入数据

  摘自<PHP和MySQL Web开发>第11章

<html>
<head>
  <title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?php
  // create short variable names
  $isbn=$_POST['isbn'];
  $author=$_POST['author'];
  $title=$_POST['title'];
  $price=$_POST['price'];

  if (!$isbn || !$author || !$title || !$price)
  {
     echo 'You have not entered all the required details.<br />'
          .'Please go back and try again.';
     exit;
  }
  if (!get_magic_quotes_gpc())
  {
    $isbn = addslashes($isbn);
    $author = addslashes($author);
    $title = addslashes($title);
    $price = doubleval($price);
  }

  @ $db = new mysqli('localhost', 'root', 'tograce', 'books');

  if (mysqli_connect_errno())
  {
  

   echo 'Error: Could not connect to database.  Please try again later.';
     exit;
  }

  $query = &insert into books values
            ('&.$isbn.&', '&.$author.&', '&.$title.&', '&.$price.&')&;
  $result = $db->query($query);
  if ($result)
      echo  $db->affected_rows.' book inserted into database.';

  $db->close();
?>
</body>
</html>

展开全部

相关文章

说两句网友评论
    我要跟贴
    取消