PHP访问和读取MySQL

接上一篇内容:PHP上传文件到服务器

我们这一章的主要目的是:将PHP文件首先上传到服务器中,然后将文件夹名字和存放在服务器中的路径存放到数据库的一个表中,然后将这些服务器的文件信息,从数据库中读取并显示出来。

首先打开数据库:

mysql -u root -p
创建一个专门存放文件信息的数据库,

create database chenhao;
使用所创建的数据库:

use chenhao;
生成一个列表用来存放文件的姓名和路径:

mysql> create table file
    -> (name  char(20) not null primary key,
    ->  path  char(50) not null );
看下我们生成的这个表格:


然后我们的文件上传模块和上一篇是一样的,上传PHP文件。看一下代码: upload.html

这段代码是创建在/var/www/UploadTest 下面的,如何创建就不讲了。

<html>
<head>
  <title> Administration - upload new files </title>
</head>
<body>
<h1>  Upload new news files</h1>
<form  enctype = "multipart/form-data" action = "upload.php" method = "post">
    <input  type = "hidden" name = "MAX_FILE_SIZE" value = "100000000" />
     <input name = "userfile" type = "file">
    <input type = "submit" value = "Send File">
</form>
</body>
</html
看一下上传代码,主要是加了与数据库连接和存取文件信息的功能:upload.php

<html>
<head>
   <title> Uploading ...</title>
</head>
<body>
<h1>Uploading file ..</h1>
<?php
  	 if($_FILES['userfile']['error'] > 0)
  	 {
        // echo $_FILES['userfile']['error'];
    	 echo 'Problem';
     	 switch($_FILES['userfile']['error'])
     	 {
         	 case 1: echo 'File exceeded upload_max_filesize';break;
          	 case 2: echo 'File exceeded max_file_size';break;
          	 case 3: echo 'File only partically uploaded';break;
          	 case 4: echo 'No file uploaded';break;
     	 }
		 exit;
	}
	else
	{
		echo "Upload:".$_FILES['userfile']['name']."<br/>";
		echo "Type: " . $_FILES['userfile']['type'] . "<br />";
		echo "Size: " . ($_FILES['userfile']['size'] / 1024) . " Kb<br />";
        echo "Stored in: " . $_FILES['userfile']['tmp_name']."<br/>";
    }

 	  // Does  the file have the right MIME type?
 	 if($_FILES['userfile']['type'] != 'text/plain')
  	 {
    	 echo ' problem :file is not plain text';
    	 exit;
  	 }
    
    //put the file where we'd like it
    $upfile = "/var/www/upload".$_FILES['userfile']['name'];
	if(file_exists($upfile))
	{
		echo $_FILES['userfile']['name']."  already exists";
		exit;
	}
	if( is_uploaded_file($_FILES['userfile']['tmp_name']))
  	 {
	    if(!move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile))
	    {
				echo 'Problem :Could not move file to destination directory';
	    		exit;
	   	}
		else
		{
			echo "Stored in: "  .$upfile."<br/>";
		}
   	}
	else
	{
		echo 'Problem: Possible file upload attack.Filename:';
		echo $_FILES['userfile']['name'];
		exit;
	}

	echo 'File uploaded successfullly<br><br>';
	
    $name = $_FILES['userfile']['name'];//file name
	$name = addslashes($name);
	$upfile = addslashes($upfile);

	@ $db = new mysqli('localhost','root','123','chenhao');

	if(mysqli_connect_errno())
	{
		echo 'Error: Could not connect to database,please try later';
		exit;
	}
	else
	{
		echo 'Connect database successfully.!';
		echo '</br>';
	}
	$query = "Insert into file values ('$name','$upfile')";
	echo $query.'</br>';

	$result = $db->query($query)or die ($db->error);

	if($result)
	{
		echo $db->affected_rows.'file message insert into database';
	}
	else
	{
		echo mysql_erron()." ".mysql_error();
		echo "An error has occurred .the item was not added";
	}
	$db->close();

	//reformat the file contents
	$fp = fopen($upfile,'r');
	$contents = fread($fp,filesize($upfile));
	fclose($fp);
	
	$contents = strip_tags($contents);
	$fp = fopen($upfile,'w');
	fwrite($fp,$contents);
	fclose($fp);

	//show what ws uploaded
	echo 'Preview of uploaded file contents:<br><hr>';
	echo $contents;
	echo '<br><hr>';
?>
</body>
</html>

看一下上传的结果:



然后我们查看下数据库那边的表格信息:


多了一个名字为hehe.txt 路径为:/var/www/uploadhehe.txt

最后我们在写一个PHP文件,将数据库中的这个列表中的关于文件的信息都打印出来:getFileMessage.php

<html>
<head>
	<title> Get  File  Message from Database </title>
</head>

<body>
	<h3> File  Message </h3>
<?php
	
	@ $db = new mysqli('localhost','root','123','chenhao');

	if(mysqli_connect_error())
	{
		echo 'Error: Could not connect to database';
		exit;
	}
	else
	{
		echo 'Connect database successfully!'.'</br>';
	}

	$query = "select * from file";
//	echo $query.'</br>';

	$result = $db->query($query);
	$num_results = $result ->num_rows;
	
	echo '<p>Number of file message found:'.$num_results.'<p>';

//	echo "<table border = 1><tr><td> file name </td><td> Path  </td></tr>";

	for( $i = 0; $i < $num_results;$i++)  
	{
		$row = $result ->fetch_assoc();
		echo ($i+1).'file   :';
		echo 'filename:'.stripslashes($row['name']).'      ';
		echo 'filepath:'. stripslashes($row['path']).'</br>';
	//	echo $i.'</br>';
//		echo '$num_results ='.$num_results.'</br>';

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

查看下运行结果:


可以看到文件的名字,和存放在服务器的哪个文件夹下面的信息,其实也可以以表格的形式写出来:

修改一下 for循环的代码就可以:

    echo "<table border = 1><tr><td> file name </td><td> Path  </td></tr>";

    for( $i = 0; $i < $num_results;$i++)
    {
        $row = $result ->fetch_assoc();
        echo "<tr><td>".stripslashes($row['name'])."</td><td>".
        stripslashes($row['path'])."</td></tr>";
    }
    echo "</table>";

执行效果:


OK,暂时就到这结束了,过后会添加下载功能。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值