做微信公众平台 在php页面从数据库中读取数据,用在微信公众平台的关注自动回复上
求指教怎么做
public function handleevent($postobj) { //header('content-type:text/html;charset=utf-8'); //定义输出格式编码为utf-8 $db = new mysqli('127.0.0.1','root','123','weixin'); //建立mysql数据库连接 $_rows = $db->query('select * from event_subscribe'); //用sql语句获取数据 //mysql_query(set names utf8);//设置编码utf8 while($_row = $_rows->fetch_assoc()) //$title= $_row->ess_title; //$description= $_row->ess_description; //$picurl= $_row->ess_pictureurl; //$url= $row->ess_url; $title= $_row['ess_title']; $description= $_row['ess_description']; $picurl= $_row['ess_pictureurl']; $url= $row['ess_url']; //$contentstr = 欢迎关注哟; $fromusername = $postobj->fromusername; $tousername = $postobj->tousername; $msgtype = news; $time = time(); $texttpl = %s 1 1 ; $resultstr = sprintf($texttpl, $fromusername, $tousername, $time,$title,$description,$picurl,$url); echo $resultstr;
回复讨论(解决方案)
没有值传到item内各项
log
2015-06-19 09:20:52 query_string:signature=2580385de24285215c55584528a9732b68327681×tamp=1434676848&nonce=18942184112015-06-19 09:20:52 1434676852 1 1
首先,这代码是有很大问题的。
1.数据库查询信息条数,使用while($_row = $_rows->fetch_assoc())表示循环查询嘛,不知道你数据库中有多少条记录。假设只有一条,那最好。在这里你可以使用var_dump($_row),查看下数组结构,再进行赋值。我推荐多条记录使用$_row = $_rows->fetch_array()的方式,fetch_array()查询结果为二维数组。assoc是一维数组。多条记录用二维,单条记录用一维即可。
2.回复信息类型是图文消息,xml数据包中声明的是单图文,也就只能接收一条数据库记录了。你之前sql查询的没有where条件,还是先var_dump看一下。
3.最后的echo使用时记得改成return。
这个代码中让我最费解的是那个第8行的where。既然使用了where,说明你知道会查询多条记录。如果只有一条记录,那么
1.将sql查询语句设置where条件,保证只能查出一条记录。
2.不使用where,改成if(记得下面的代码用括号括起来),或者干脆去掉where,只保留$_row = $_rows->fetch_assoc()
。
如果要组合多图文消息,那么
1.使用do{}---while()循环,因为我之前讲过,while循环会丢失第一条记录(这或许就是你查不到赋值信息的原因)。
2.循环
public function handleevent($postobj) { //header('content-type:text/html;charset=utf-8'); //定义输出格式编码为utf-8 $db = new mysqli('127.0.0.1','root','123','weixin'); //建立mysql数据库连接 $_rows = $db->query('select * from event_subscribe limit 5'); //用sql语句获取数据 $newsarray = array(); do { $newsarray[]=array(title=>$_row['ess_title'], description=>$_row['ess_description'], picurl=>$_row['ess_pictureurl'], url =>$row['ess_url']); }while ($_row = $_rows->fetch_array()); $itemtpl = ; $item_str = ; foreach ($newsarray as $item){ $item_str .= sprintf($itemtpl, $item['title'], $item['description'], $item['picurl'], $item['url']); } $newstpl = %s %s $item_str ; $result = sprintf($newstpl, $postobj->fromusername, $postobj->tousername, time(), count($newsarray)); return $result; }
新的代码 public function handleevent($postobj) { //header('content-type:text/html;charset=utf-8'); //定义输出格式编码为utf-8 $db = new mysqli('127.0.0.1','root','123','weixin'); //建立mysql数据库连接 $db->query(set names utf8);//防止乱码 $_rows = $db->query('select * from event_subscribe where ispublic=1'); //用sql语句获取数据 $_row = mysqli_fetch_assoc($_rows); $texttpl = %s 1 1 ; $resultstr = sprintf($texttpl, $postobj->fromusername, $postobj->tousername, time(),$_row['ess_title'],$_row['ess_description'],$_row['ess_pictureurl'],$_row['ess_url']); return $resultstr; }