php_常用方法
来源:互联网 发布:发那科pmc编程手册 编辑:程序博客网 时间:2024/06/03 13:54
ajax传值转换问题
在前端
需要把json字符串转化成json对象 dataType:"json"或者 var obj = JSON.parse(obj); stringify()用于从一个对象解析出字符串,如 var a = {a:1,b:2} 结果: JSON.stringify(a) "{"a":1,"b":2}"
在后台
$arr = json_decode($jsonStr, true); 有true 返回php关联数组,没有true返回对象 -------------------------------- ex: $jsonStr = file_get_contents("jsonURL.json");//得到json字符串 $arr = json_decode($jsonStr, true);将json字符串变成关联数组 //根据前段传递过来的值,取出关联数组中对应的数值 $type = $_GET["type"]; $url = $arr[$type]; $str = file_get_contents($url); echo $str;//返回给前台 ----------------------------- json_encode 转换成json字符串 ex: require_once "DataBase.php"; $db = new DB("localhost","root","","0301php"); $a = $db->selSQL("select * from student where name like '小%'");//得到的一个数组 $a = json_encode($a);//将数组转换成json字符串返回给前台
数据库
数据库
conn.php<?php /* * 1.链接Mysal服务器 * 参数1:Mysql地址(默认端口3306) * 参数2:登录Mysql的用户名 * 参数3密码 * die:出现异常终止代码执行 * mysql_error() 打印Mysql错误信息 * * 2.选择数据库 * 参数1:数据库名字 * 参数2:上一步的链接对象(可以省略)*/ $conn = mysql_connect("localhost","root","") or die("connect is wrong"); mysql_select_db("0301php"); mysql_query("set names utf8"); ?>
01.html<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <style type="text/css"> table {border-collapse:collapse;} table thead tr{ background: red; } table,td,th{border:1px solid dodgerblue;} #tbody tr:nth-child(odd) td {background-color:gainsboro;} #tbody tr:hover td{ background: rgb(150,205, 205); } </style> </head> <body> <table> <thead> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>院系班级</th> </tr> </thead> <tbody id="tbody"></tbody> </table> <script type="text/javascript"> var tbody = document.getElementById("tbody"); $.ajax({ type:"post", url:"01.php", data:{}, success:function(res){ var res = JSON.parse(res); console.log(res); for(var i = 0; i < res.length; i++){ createTd(res[i]); } } }); function createTd(arr){ var tr = document.createElement("tr"); for(prop in arr){ var td = document.createElement("td"); td.innerHTML = arr[prop]; tr.appendChild(td); } tbody.appendChild(tr); } </script> </body></html>
01.php<?php header("Content-type: text/html; charset=utf-8"); require "conn.php"; $sql = "select * from student"; $res = mysql_query($sql) or die("查询失败"); //上面执行查询数据后,会受到一个结果集,我们需要提取数据 //print_r(mysql_fetch_row($res)); //索引数组 //print_r(mysql_fetch_array($res)); //都有 //print_r(mysql_fetch_assoc($res)); //关联数组 //注意:查询的时候,数据集一次只能取一行数据,所以你需要循环取出,直到最后 $arr = array(); //准备空数组,接收最后结果 while($row = mysql_fetch_assoc($res)){ array_push($arr,$row); } //转成字符串发给前端使用 echo json_encode($arr);?>
封装数据库增删改查
DataBase.php<?php class DB{ //链接并选择数据库 function __construct($ip = "", $dataN ="", $dataP ="",$dbName =""){ $con = mysql_connect($ip, $dataN, $dataP); mysql_select_db($dbName) or die(mysql_error()); mysql_query("set names utf8"); } function selSQL($sqlStr){ $result = mysql_query($sqlStr) or die(mysql_error()); $arr = array(); while ($row = mysql_fetch_assoc($result)) { array_push($arr, $row); } //转成字符串发给前端使用 return $arr; } //插入,删除,更新 function iduSQL($sql){ mysql_query($sql); if(mysql_affected_rows() > 0){ return true; }else{ return false; } } }?>for ($i = 1; $i <= 38; $i++) { $sql = mysql_query("UPDATE `content` SET `order` = '$i' WHERE id = {$i}"); var_dump($sql);}----------------------------------------------调用<?php header("content-type:text/html;charset=utf-8"); echo "<pre>"; require_once "DataBase.php"; $db = new DB("localhost","root","","0301php"); $a = $db->selSQL("select * from student where name like '小%'"); $a = json_encode($a); print_r($a);// $re = $db->iduSQL("insert into student(sno, name, age, sex, gradeclass) values('','李四',18,'男','软件工程')");// echo $re;// $re = $db->iduSQL("delete from student where sno = 16");// echo $re;// $re = $db->iduSQL("update student set name = '李vd四' where sno = 17");// echo $re;字符串中的变量 用{}括起来 也可以"update score set count = {$cent} where openid = {$openid}"?>----------------------------------------------$set_pw = "wang11";echo "update member set password = '$set_pw' where userid = 9";echo "update member set password = {$set_pw} where userid = 9";update member set password = 'wang11' where userid =9 update member set password = wang11 where userid = 9----------------------------------------上面总结:sql语句中 $set_pw 如果是数字 可以{$set_pw} 也可以'{$set_pw}';$set_pw 如果是字符串 必须'{$set_pw}'
分页
<?php $conn=@mysql_connect("localhost","root","") or die ("链接失败"); mysql_select_db("lidongxu",$conn); mysql_query("set names utf8");?><!doctype html><html lang="en"><head> <meta charset="utf-8"/> <title>分页</title></head><body><table border="1" cellspacing="0" style="text-align: center;" width="400px"> <th>用户名</th><th>密码</th><th>电话号</th><th>年龄</th><th>地址</th> <?php //表格部分 $nowPageNum = 5; // 设置每页应该显示的数据条数 $pageNum = $_GET["page"]; // 获取当前应该显示的分页数 if ($pageNum == null){ // 如果获取到的是null, 默认设置为0 $pageNum = 0; } echo $pageNum; $sqlStartNum = $pageNum * $nowPageNum; // 计算数据应该从第几条开始获取 $sql = "select * from user limit $sqlStartNum, $nowPageNum"; // 从第几条获取, 获取5条数据 $result = mysql_query($sql); // 执行SQL语句 while ($row = @mysql_fetch_row($result)){ // 每次while循环一次, 拿出一行数据 echo "<tr>"; foreach ($row as $value){ // 遍历这行里所有字段, 利用td标签显示出来 echo "<td>".$value."</td>"; } echo "</tr>"; } ?></table><!-- 分页标签开始 --><div style="width: 400px; overflow: hidden; text-align: center;"> <?php $lastPage = $pageNum - 1; $nextPage = $pageNum + 1; if ($lastPage < 0){ // 强制让上一页恒等于0 $lastPage = 0; } echo "<a href='fenye.php?page = $lastPage' style='float: left';>上一页</a>"; $sql = "select count(*) from user"; $result = mysql_query($sql); $arr = mysql_fetch_array($result); $downPageNum = ceil($arr[0] / $nowPageNum); //一共更有14条数据 / 5 = 3页,也就是最后一页 for ($i = 1; $i <= $downPageNum; $i++){ // 计算一共有多少页, 然后动态创建a标签 $num = $i - 1; echo "<a href='fenye.php?page=$num' style='margin-left: 10px'>$i</a>"; } if ($nextPage >= $downPageNum - 1){ // 因为第一页 对应page的0, 所以最后一个分页 要-1 $nextPage = $downPageNum - 1; } echo "<a href='fenye.php?page=$nextPage' style='float: right';>下一页</a>"; ?></div><tr> <?php echo "共有".$downPageNum."页"; echo "当前为".++$pageNum."页"; ?></tr><!-- 分页标签结束 --></body></html>
验证码
<?php//生成随机数->创建图片->随机数写进图片->保持在SESSION中 session_start(); for($i=0;$i<4;$i++){ $rand.=dechex(rand(1,15));} $_SESSION[check_pic]=$rand; //创建一个图像并设置其尺寸 $im=imagecreatetruecolor(100,20); //调试版的时候,背景颜色 $te=imagecolorallocate($im,255,255,128); //设置线条数目以及颜色 for($i=0;$i<3;$i++){ $te2=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255)); imageline($im,rand(0,100),0,100,30,$te2); } //噪点的制作 for($i=0;$i<200;$i++){ imagesetpixel($im, rand()%100, rand()%100, $te2); } //绘图函数 imagestring ( resource image, font, int x, int y, 内容 , 颜色 ) imagestring($im,10,35,5,$rand,$te);//文字水印// $str="你好吗";// imagettftext($im,12,rand(0,10),30,18,$te,'aa.ttf',$str);//输入图像 header("Content-type:image/jpeg"); imagejpeg($im);?>index.php文件<?php session_start(); if($_POST[check]){ if($_POST[check]==$_SESSION[check_pic]){ echo "yes".$_SESSION[check_pic]; }else{ echo "you are wrong".$_SESSION[check_pic]; }}?><style> input,img{vertical-align:middle;}</style><form action="" method="post"> <input type="text" name="check"> <img src='666.php'><br> <input type="submit" value="submit"></form>
文件上传
<?php if(is_uploaded_file($_FILES['upfile']['tmp_name'])){ $upfile=$_FILES["upfile"]; $name = $upfile["name"]; $type = $upfile["type"]; $size = $upfile["size"]; $tmp_name = $upfile["tmp_name"]; $error = $upfile["error"]; //上传资源的筛选 switch ($type) { case 'image/pjpeg' : $ok=1; break; case 'image/jpeg' : $ok=1; break; case 'image/gif' : $ok=1; break; case 'image/png' : $ok=1; break; } if($ok && $error=='0'){ move_uploaded_file($tmp_name,'up/'.$name); echo "上传成功"; }}?><form action="" enctype="multipart/form-data" method="post" name="upform"> 上传文件: <input name="upfile" type="file"> <input type="submit" value="上传"><br> </form>---------- //根据文件的扩展名来进行判断 是否可以上传成功$points = explode('.' , $name);$num = count($points);$points[$num-1];switch ($points[$num-1]) { case 'zip' : $ok=1; break; default : $ok=0; // application/msword}
搜索关键字(高亮)
<?php $conn=@mysql_connect("localhost","root","") or die ("链接失败"); mysql_select_db("gxt",$conn); mysql_query("set names 'utf8'");//全站搜索// 一个键字搜索 if($_GET[key]){ $sql="select * from poetry where content like'%$_GET[key]%'"; $res=mysql_query($sql,$conn); while($row=mysql_fetch_array($res)){ // 关键字 高亮度 $row[content]=preg_replace("/$_GET[key]/i", "<font color=red> <b>\\0</b></font>", $row[content]); echo "$row[content].<br>"; } } // 多关键字搜索 if($_GET[key]){ $k=explode(" ", $_GET[key]); $sql="select * from poetry where content like'%$k[0]%' and content like'%$k[1]%'"; $res=mysql_query($sql,$conn); while($row=mysql_fetch_array($res)){ //关键字 高亮度 $row[content]=preg_replace("/($k[0])/i", "<font color=red> <b>\\0</b></font>", $row[content]); $row[content]=preg_replace("/($k[1])/i", "<font color=red> <b>\\0</b></font>", $row[content]); echo "$row[content]"."<br>"; } }?><form action="" method="get">关键字:<input type="text" name="key"/><input type="submit" name="sub" value="全站搜索"/></form>
阅读全文
1 0
- php_常用方法
- PHP_常用正则表达式
- PHP_数组
- PHP_数组
- PHP_字符串
- PHP_会话
- php_函数
- php_变量
- php_语法
- 【PHP_配置】_02_检查apache配置文件语法是否出错的方法
- PHP_字符串操作入门教程
- PHP_字符串操作入门教程
- PHP_语法基础
- PHP_面向对象小记
- PHP_学习笔记索引
- PHP_文件目录
- PHP_面向对象
- PHP_实现分页功能
- 神经网络的基本概念
- jQuery中的DOM操作(2)
- Codeforces 757E Bash Plays with Functions
- POJ1611:The Suspects
- 欢迎使用CSDN-markdown编辑器
- php_常用方法
- USACO-Section1.4 Arithmetic Progressions
- Morris二叉树遍历算法
- Netty入门之 TimeServer && TimeClient
- java-SE-8
- samba
- CC2541 之CCDEBUG软件终究修复教程
- Kaggle 神器 xgboost
- 网站静态化处理--总述(1)