PHP编程

PHP访问MYSQL数据库快速入门

日期:2015-06-28 00:00:00 来源: IT猫扑网

  连接

  //下面使用了函数库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 '

Number of books found: '.$num_results.'

';

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

  插入数据

  摘自第11章



  Book-O-Rama Book Entry Results


Book-O-Rama Book Entry Results


  // 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.
'
          .'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();
?>

相关文章

相关下载

网友评论

我要评论...
    没有更早的评论了
    取消