Home php教程 php手册 PHP高手带路:问题汇总解答(2)

PHP高手带路:问题汇总解答(2)

Jun 21, 2016 am 08:59 AM
gt mysql nbsp return

  [回顾]:上集介绍了"调试程序","如何使用session","规范SQL语句"等15个问题(Php高手带路--问题汇总解答[1])。本集继续作出16条常见问题的解答。

16:我想修改MySQL的用户,密码
  首先要声明一点,大部分情况下,修改MySQL是需要有mysql里的root权限的,

  所以一般用户无法更改密码,除非请求管理员.

  方法一

  使用phpmyadmin,这是最简单的了,修改mysql库的user表,

  不过别忘了使用PASSWORD函数。

  方法二

  使用mysqladmin,这是前面声明的一个特例。

  mysqladmin -u root -p password mypasswd

  输入这个命令后,需要输入root的原密码,然后root的密码将改为mypasswd。

  把命令里的root改为你的用户名,你就可以改你自己的密码了。

  当然如果你的mysqladmin连接不上mysql server,或者你没有办法执行mysqladmin,

  那么这种方法就是无效的。

  而且mysqladmin无法把密码清空。
  下面的方法都在mysql提示符下使用,且必须有mysql的root权限:

  方法三

  mysql> INSERT INTO mysql.user (Host,User,Password)

  VALUES('%','jeffrey',PASSWORD('biscuit'));

  mysql> FLUSH PRIVILEGES

  确切地说这是在增加一个用户,用户名为jeffrey,密码为biscuit。

  在《mysql中文参考手册》里有这个例子,所以我也就写出来了。

  注意要使用PASSWORD函数,然后还要使用FLUSH PRIVILEGES。

  方法四

  和方法三一样,只是使用了REPLACE语句

  mysql> REPLACE INTO mysql.user (Host,User,Password)

  VALUES('%','jeffrey',PASSWORD('biscuit'));

  mysql> FLUSH PRIVILEGES

  方法五

  使用SET PASSWORD语句,

  mysql> SET PASSWORD FOR jeffrey@"%" = PASSWORD('biscuit');

  你也必须使用PASSWORD()函数,

  但是不需要使用FLUSH PRIVILEGES。

  方法六

  使用GRANT ... IDENTIFIED BY语句

  mysql> GRANT USAGE ON *.* TO jeffrey@"%" IDENTIFIED BY 'biscuit';


  这里PASSWORD()函数是不必要的,也不需要使用FLUSH PRIVILEGES。
  注意: PASSWORD() [不是]以在Unix口令加密的同样方法施行口令加密。


17:我想知道他是通过哪个网站连接到本页
  PHP代码:

  
  //必须通过超级连接进入才有输出

  Echo $_SERVER['HTTP_REFERER'];

  ?>

18:数据放入数据库和取出来显示在页面需要注意什么
  入库时

  $str=addslashes($str);

  $sql="insert into `tab` (`content`) values('$str')";

  出库时

  $str=stripslashes($str);

  显示时

  $str=htmlspecialchars(nl2br($str)) ;
  
  //$content来自数据库

  $content=nl2br(htmlspecialchars($content));

  $content=str_replace(" "," ",$content);

  $content=str_replace("\n","
\n",$content);

  ?>

19:如何读取当前地址栏信息
  PHP代码:

  
  $s="http://{$_SERVER['HTTP_HOST']}:{$_SERVER["SERVER_PORT"]}{$_SERVER['SCRIPT_NAME']}";

  $se='';
  foreach ($_GET as $key => $value) {
  $se.=$key."=".$value."&";
  }
  $se=Preg_Replace("/(.*)&$/","$1",$se);
  $se?$se="?".$se:"";
  echo $s."?$se";
  ?>

20:我点击后退按钮,为什么之前填写的东西不见
  这是因为你使用了session.

  解决办法:
  PHP代码:

    .....................?>

21:怎么在图片里显示IP地址

  PHP代码:

   Header("Content-type: image/png");

  $img = ImageCreate(180,50);
  $ip = $_SERVER['REMOTE_ADDR'];

   ImageColorTransparent($img,$bgcolor);

  $bgColor = ImageColorAllocate($img, 0x2c,0x6D,0xAF); // 背景颜色

  $shadow = ImageColorAllocate($img, 250,0,0); // 阴影颜色

  $textColor = ImageColorAllocate($img, oxff,oxff,oxff); // 字体颜色

  ImageTTFText($img,10,0,78,30,$shadow,"d:/windows/fonts/Tahoma.ttf",$ip);
//显示背景

  ImageTTFText($img,10,0,25,28,$textColor,"d:/windows/fonts/Tahoma.ttf","your ip is".$ip);

 // 显示IP    

  ImagePng($img);    

  imagecreatefrompng($img);
  ImageDestroy($img);      

  ?>

22:如何取得用户的真实IP

  PHP代码:

   function iptype1 () {

   if (getenv("HTTP_CLIENT_IP"))

   {
  return getenv("HTTP_CLIENT_IP");

  }

  else

  {

  return "none";
  }

  }

  function iptype2 () {

  if (getenv("HTTP_X_FORWARDED_FOR"))

  {

   return
  getenv("HTTP_X_FORWARDED_FOR");

  }

  else {

  return "none";
  }

  }

  function iptype3 () {

  if (getenv("REMOTE_ADDR"))

  {

   return getenv("REMOTE_ADDR");
  }

   else {

  return "none";

   }

   }

  function ip() {

   $ip1 = iptype1();

   $ip2 = iptype2();

  $ip3 = iptype3();

  if (isset($ip1) && $ip1 != "none" && $ip1 != "unknown")

  {

  return $ip1;

  }

   elseif (isset($ip2) && $ip2 != "none" && $ip2 != "unknown")
  {

  return $ip2;

  }

  elseif (isset($ip3) && $ip3 != "none" && $ip3 != "unknown")

   {

  return $ip3;

  }

   else

  { return "none"; }

  }

   Echo ip();

  ?>


23:如何从数据库读取三天内的所有记录
  首先表格里要有一个DATETIME字段记录时间,

  格式为'2003-7-15 16:50:00'
  SELECT * FROM `xltxlm` WHERE TO_DAYS(NOW()) - TO_DAYS(`date`)

24:如何远程链接Mysql数据库

  在增加用户的mysql表里有一个host字段,修改为"%",或者指定允许连接的ip地址,这样,你就可以远程调用了。
  $link=mysql_connect("192.168.1.80:3306","root","");


25:正则到底怎么用
点击这里
正则表达式中的特殊字符

26:用Apache后,主页出现乱码

  方法一:

  AddDefaultCharset ISO-8859-1 改为 AddDefaultCharset off

  方法二:

  AddDefaultCharset GB2312


27:为什么单引号,双引号在接受页面变成(\'\")
  解决方法:

  方法一:在php.ini中设置:magic_quotes_gpc = Off

  方法二: $str=stripcslashes($str)


28:怎么让程序一直运行下去,而不是超过30秒就停止
  set_time_limit(60)//最长运行时间一分钟

  set_time_limit(0)//运行到程序自己结束,或手动停止


29:计算当前在线人数
  例子一:用文本实现
  PHP代码:

  
  //首先你要有读写文件的权限

  //本程序可以直接运行,第一次报错,以后就可以

   $online_log = "count.dat"; //保存人数的文件,

   $timeout = 30;//30秒内没动作者,认为掉线

   $entries = file($online_log);
   $temp = array();

   for ($i=0;$i
   $entry = explode(",",trim($entries[$i]));

   if (($entry[0] != getenv('REMOTE_ADDR')) && ($entry[1] > time()))
{

   array_push($temp,$entry[0].",".$entry[1]."\n"); //取出其他浏览者的信息,并去掉超时者,保存进$temp

   }

   }
   array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout))."\n");
//更新浏览者的时间

   $users_online = count($temp); //计算在线人数
   $entries = implode("",$temp);

   //写入文件

   $fp = fopen($online_log,"w");

   flock($fp,LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作

   fputs($fp,$entries);

   flock($fp,LOCK_UN);

   fclose($fp);
   echo "当前有".$users_online."人在线";
  ?>


30:什么是模板,怎么用
  我用的是phplib模板

  下面是其中几个函数的使用
  $T->Set_File("随便定义","模板文件.tpl");
  $T->Set_Block("在set_file中定义的","","随便定义");

  $T->Parse("在Set_Block中定义的","",true);

  $T->Parse("随便输出结果","在Set_File中定义的");
  设置循环格式为:
  
  如何将模板生成静态网页


  PHP代码:

  
  //这里使用phplib模板

  ............

  ............

  $tpl->parse("output","html");

  $output = $tpl->get("output");// $output 为整个网页内容


  function wfile($file,$content,$mode='w') {

  $oldmask = umask(0);

  $fp = fopen($file, $mode);

  if (!$fp) return false;

  fwrite($fp,$content);

  fclose($fp);

  umask($oldmask);

  return true;

  }

  // 写到文件里

  Wfile($FILE,$output);

  header("location:$FILE");//重定向到生成的网页

  }

  ?>
  phplib下载地址 smarty下载地址

31:怎么用php解释字符   

  比如:输入2+2*(1+2),自动输出8  可以用eval函数

  PHP代码:

  



  

  


  
  $str=$_POST['str'];

  eval("\$o=$str;");

  Echo "$o";

  ?>


  到此,php的问题解答就为大家介绍完毕,希望能对各位有所帮助。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mysql whether to change table lock table mysql whether to change table lock table Apr 08, 2025 pm 05:06 PM

When MySQL modifys table structure, metadata locks are usually used, which may cause the table to be locked. To reduce the impact of locks, the following measures can be taken: 1. Keep tables available with online DDL; 2. Perform complex modifications in batches; 3. Operate during small or off-peak periods; 4. Use PT-OSC tools to achieve finer control.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

Can mysql handle multiple connections Can mysql handle multiple connections Apr 08, 2025 pm 03:51 PM

MySQL can handle multiple concurrent connections and use multi-threading/multi-processing to assign independent execution environments to each client request to ensure that they are not disturbed. However, the number of concurrent connections is affected by system resources, MySQL configuration, query performance, storage engine and network environment. Optimization requires consideration of many factors such as code level (writing efficient SQL), configuration level (adjusting max_connections), hardware level (improving server configuration).

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles