如何从php url获取参数并用于查询结果

时间:2016-04-14 06:09:34

标签: php mysqli

我是php的新手,我不知道如何从url执行带有php参数的where子句的SQL查询请帮助我。

网址: http://myurl.com/eng.php?name=fab

PHP代码

 <?php
 header('Content-Type: application/json; charset=utf-8');
 $mysqli = new mysqli ( 'localhost', 'mabhim92', '9993115300', 'gcm_chat');
 //PROBLEM LANGUAGE ?????
if( function_exists('mysql_set_charset') ){
mysqli_set_charset($mysqli , 'utf8');
}else{
 mysqli_query($mysqli , "SET NAMES 'utf8'");
}
 // Check if album id is posted as GET parameter
$id = intval($_GET['name']);
$myq = $mysqli ->query ("SELECT * FROM  gkfordate WHERE monthforgk=$id");   
   while ($myr = $myq->fetch_assoc()) {
        $array["Questions"][] = (array(   
    'month'      => $myr['monthforgk'],
    'date' => $myr['dateforgk'],
     ));
  }
  echo json_encode($array, JSON_UNESCAPED_UNICODE);
   ?>

结果:在我的数据库表中只有两列monthforgk和dateforgk

{
 "Questions": [
{
  "month": "jan",
  "date": "2016-04-13 20:30:49"
},
{
  "month": "jan",
  "date": "2016-04-13 20:30:49"
},
{
  "month": "jan",
  "date": "2016-04-13 20:30:49"
},
{
  "month": "fab",
  "date": "2016-04-13 20:30:49"
},
{
  "month": "fab",
  "date": "2016-04-13 20:30:49"
}
]
}

如果我为name = fab传递参数,那么为什么要从数据库中给我所有结果。

2 个答案:

答案 0 :(得分:4)

您尝试查询

"SELECT * FROM  gkfordate WHERE monthforgk='$id'";

答案 1 :(得分:2)

您正在通过intval()函数运行查询字符串,该函数返回字符串'fab'的整数值,即0。

试试这个:

echo 'intval of fab = '.intval('fab');

你需要的只是这个:

if(isset($_GET['name'])){
    $id = $mysqli->real_escape_string($_GET['name']);
}

然后在查询中:

$myq = $mysqli ->query ("SELECT * FROM  gkfordate WHERE monthforgk='$id'");