• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Head First PHP&MySQL学习笔记(4)_mysql

mysql 搞代码 7年前 (2018-06-06) 160次浏览 已收录 0个评论

Head First PHP&mysql学习笔记(四)

五. 使用存储在文件中的数据

1. "@":PHP错误抑制指令,该表达式可能产生的任何错误信息都被忽略掉。

2. $_FILES内置超级全局变量允许访问上传文件的有关信息

    $_FILES[‘file’][‘name’]:上传文件的文件名              $_FILES[‘file’][‘type’]:上传文件的MIME类型

    $_FILES[‘file’][‘size’]:上传文件的大小                     $_FILES[‘file’][‘tmp_name’]:文件在服务器上的临时存储位置  

    $_FILES[‘file’][‘error’]:文件上传的错误码,0表示成功,其他值表示失败

3. 存储在外部文件中的数据一般就留在外部文件中,即使是数据库应用也往往如此 

4. 在Web页面上放置一个图像只需要该图像文件的一个引用

5. move_uploaded_file($_FILES[‘screenshot’][‘tmp_name’],$target) 接受一个文件的源位置和目标位置,完成文件移动

6. 共享的脚本数据需要在整个应用中都能访问,而无需代码重复;包含文件允许在多个脚本之间共享代码

7. GET和POST这两种Web请求控制着脚本之间如何传递数据:

    POST:用于向服务器发送数据,从而以某种方式导致服务器上状态的改变,如在数据库中插入数据。数据还可以在响应中返回。不同于GET,POST请求只能通过Web表单的动作完成。另外与GET不同,POST请求中发送的数据是隐藏不可见的。

    GET:一般用于数据获取,而不会使服务器有任何改变。对于少量的数据,GET非常有用,可以直接在URL中向服务器发送数据。与POST不同,GET主要适用于发送少量的数据。

8. GET&POST应用代码实例:

<!-- addvars.php -->  <?php   // Define application constants   define('GW_UPLOADPATH', 'images/');   // 将图片文件Move到images文件夹下   define('GW_MAXFILESIZE', 32768);      // 32 KB ?> 
<!-- connectvars.php -->  <?php   // Define database connection constants   define('DB_HOST', 'localhost');   define('DB_USER', 'root');   define('DB_PASSWORD', '');   define('DB_NAME', 'gwdb'); ?> 
<!-- addscore.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" xml:lang="en" lang="en"> <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Guitar Wars - Add Your High Score</title>   <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body>   <h2>Guitar Wars - Add Your High Score</h2>  <?php   require_once('appvars.php');      // require_once()函数,未找到appvars.php会报错   require_once('connectvars.php');    if (isset($_POST['submit'])) {     // Grab the score data from the POST     $name = $_POST['name'];     $score = $_POST['score'];     $screenshot = $_FILES['screenshot']['name'];     $screenshot_type = $_FILES['screenshot']['type'];     $screenshot_size = $_FILES['screenshot']['size'];       if (!empty($name) && !empty($score) && !empty($screenshot)) {       if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png'))         && ($screenshot_size > 0) && ($screenshot_size <= GW_MAXFILESIZE)) {         if ($_FILES['screenshot']['error'] == 0) {           // Move the file to the target upload folder           $target = GW_UPLOADPATH . $screenshot;           if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {     // 将上传图片从临时位置转移到images文件夹下              // Connect to the database             $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);                  // Write the data to the database             $query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";    // NOW()函数用于插入当前日期/时间             mysqli_query($dbc, $query);              // Confirm success with the user             echo '<p>Thanks for adding your new high score! It will be reviewed and added to the high score list as soon as possible.</p>';             echo '<p><strong>Name:</strong> ' . $name . '<br />';             echo '<strong>Score:</strong> ' . $score . '<br />';             echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image" /></p>';             echo '<p><a href="index.php"><< Back to high scores</a></p>';              // Clear the score data to clear the form             $name = "";             $score = "";             $screenshot = "";              mysqli_close($dbc);           }           else {             echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';           }         }       }       else {         echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no greater than ' . (GW_MAXFILESIZE / 1024) . ' KB in size.</p>';       }        // Try to delete the temporary screen shot image file       @unlink($_FILES['screenshot']['tmp_name']);     // unlink()函数从Web服务器删除一个文件,用@以防在文件上传未成功时显示错误报告     }     else {       echo '<p class="error">Please enter all of the information to add your high score.</p>';     }   } ?>    <hr />   <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">     <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo GW_MAXFILESIZE; ?>" />     <label for="name">Name:</label>     <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />     <label for="score">Score:</label>     <input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" /><br />     <label for="screenshot">Screen shot:</label>     <input type="file" id="screenshot" name="screenshot" />     <hr />     <input type="submit" value="Add" name="submit" />   </form> </body>  </html> 
<!-- admin.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" xml:lang="en" lang="en"> <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Guitar Wars - High Scores Administration</title>   <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body>   <h2>Guitar Wars - High Scores Administration</h2>   <p>Below is a list of all Guitar Wars high scores. Use this page to remove scores as needed.</p>   <hr />  <?php   require_once('appvars.php');   require_once('connectvars.php');    // Connect to the database    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);     // Retrieve the score data from MySQL   $query = "SELECT * FROM guitarwars ORDER BY score DESC, date ASC";    // 回忆ORDER BY,DESC,ASC排序用法   $data = mysqli_query($dbc, $query);    // Loop through the array of score data, formatting it as HTML    echo '<table>';   while ($row = mysqli_fetch_array($data)) {      // Display the score data     echo '<tr class="scorerow"><td><strong>' . $row['name'] . '</strong></td>';     echo '<td>' . $row['date'] . '</td>';     echo '<td>' . $row['score'] . '</td>';     echo '<td><a href="removescore.php?id=' . $row['id'] . '&date=' . $row['date'] .    // & = &        '&name=' . $row['name'] . '&score=' . $row['score'] .       '&screenshot=' . $row['screenshot'] . '">Remove</a></td></tr>';   }   echo '</table>';    mysqli_close($dbc);       // 不要忘记mysqli_close()操作 ?>  </body>  </html> 
<!-- index.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" xml:lang="en" lang="en"> <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Guitar Wars - High Scores</title>   <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body>   <h2>Guitar Wars - High Scores</h2>   <p>Welcome, Guitar Warrior, do you have what it takes to crack the high score list? If so, just <a href="addscore.php">add your own score</a>.</p>   <hr />  <?php   require_once('appvars.php');   require_once('connectvars.php');    // Connect to the database    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);     // Retrieve the score data from MySQL   $query = "SELECT * FROM guitarwars ORDER BY score DESC, date ASC";   $data = mysqli_query($dbc, $query);    // Loop through the array of score data, formatting it as HTML    echo '<table>';   $i = 0;   while ($row = mysqli_fetch_array($data)) {      // Display the score data     if ($i == 0) {            // 找到排序好的数据库中第一个,为最高分添加css样式       echo '<tr><td colspan="2" class="topscoreheader">Top Score: ' . $row['score'] . '</td></tr>';     }     echo '<tr><td class="scoreinfo">';     echo '<span class="score">' . $row['score'] . '</span><br />';     echo '<strong>Name:</strong> ' . $row['name'] . '<br />';     echo '<strong>Date:</strong> ' . $row['date'] . '</td>';     // is_file函数查看该文件是否存在,filesize()函数检查并确保上传文件不为空     if (is_file(GW_UPLOADPATH . $row['screenshot']) && filesize(GW_UPLOADPATH . $row['screenshot']) > 0) {       echo '<td><img src="' . GW_UPLOADPATH . $row['screenshot'] . '" alt="Score image" /></td></tr>';     }     else {       echo '<td><img src="' . GW_UPLOADPATH . 'unverified.gif' . '" alt="Unverified score" /></td></tr>';     }     $i++;   }   echo '</table>';    mysqli_close($dbc); ?>  </body>  </html> 
<!-- removescore.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" xml:lang="en" lang="en"> <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Guitar Wars - Remove a High Score</title>   <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body>   <h2>Guitar Wars - Remove a High Score</h2>  <?php   require_once('appvars.php');   require_once('connectvars.php');    if (isset($_GET['id']) && isset($_GET['date']) && isset($_GET['name']) && isset($_GET['score']) && isset($_GET['screenshot'])) {     // Grab the score data from the GET     $id = $_GET['id'];                // 使用GET方法得到admin.php传来的数据     $date = $_GET['date'];     $name = $_GET['name'];     $score = $_GET['score'];     $screenshot = $_GET['screenshot'];   }   else if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score'])) {     // Grab the score data from the POST     $id = $_POST['id'];               // 使用POST方法得到自引用的数据     $name = $_POST['name'];     $score = $_POST['score'];   }   else {     echo '<p class="error">Sorry, no high score was specified for removal.</p>';   }    if (isset($_POST['submit'])) {     if ($_POST['confirm'] == 'Yes') {       // Delete the screen shot image file from the server       @unlink(GW_UPLOADPATH . $screenshot);         // 避免显示错误,尤其适用于unlink()        // Connect to the database       $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);         // Delete the score data from the database       $query = "DELETE FROM guitarwars WHERE id = $id LIMIT 1";       // LIMIT 1限制最多删除一条       mysqli_query($dbc, $query);       mysqli_close($dbc);        // Confirm success with the user       echo '<p>The high score of ' . $score . ' for ' . $name . ' was successfully removed.';     }     else {       echo '<p class="error">The high score was not removed.</p>';     }   }   else if (isset($id) && isset($name) && isset($date) && isset($score)) {     echo '<p>Are you sure you want to delete the following high score?</p>';     echo '<p><strong>Name: </strong>' . $name . '<br /><strong>Date: </strong>' . $date .       '<br /><strong>Score: </strong>' . $score . '</p>';     echo '<form method="post" action="removescore.php">';             // 没有使用$_SERVER['PHP_SELF'],因为它会包含作为GET通过URL查询串传递的所有数据     echo '<input type="radio" name="confirm" value="Yes" /> Yes ';     echo '<input type="radio" name="confirm" value="No" checked="checked" /> No <br />';     echo '<input type="submit" value="Submit" name="submit" />';     echo '<input type="hidden" name="id" value="' . $id . '" />';     // 使用隐藏的表单域存储数据,使之能够作为POST请求的一部分发送     echo '<input type="hidden" name="name" value="' . $name . '" />';     echo '<input type="hidden" name="score" value="' . $score . '" />';     echo '</form>';   }    echo '<p><a href="admin.php"><< Back to admin page</a></p>';  // 提供一个指回Admin页面的链接来改善导航 ?>  </body>  </html> 
/* style.css */  .error {   font-weight: bold;   color: #FF0000; }  .topscoreheader {   text-align: center;   font-size: 200%;   background-color: #36407F;   color: #FFFFFF; }  .score {   font-size:150%;   color: #36407F; }  .scoreinfo {   vertical-align: top;   padding-right:15px; } 

欢迎大家阅读《Head First PHP&MySQL学习笔记(4)_mysql》,跪求各位点评,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Head First PHP&MySQL学习笔记(4)_mysql
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址