使用PHP获取URL参数以进行Mysqli数据库搜索

时间:2013-05-19 17:30:49

标签: php ajax url parameters mysqli

我正在尝试研究如何使用PHP从URL获取参数。 所以我的代码开始于一些ajax触发php和响应的警报:

$.ajax({                                      
    url: 'blog/assets/php/load-blog.php',
    dataType: 'json',    
    success: function(data){
     alert(data);
    }
  });

然后我有我的php:

<?php
  //==== CONNECTION VARIABLE
  $con = new mysqli($host,$user,$pass,$database);


  //==== GET URL PARAMETER
  $urlParam =  $_GET["date"];


  //==== FETCH DATA
  $result = $con->query("SELECT * FROM $table WHERE DATE = '$urlParam'");


  //==== CREATE ARRAY
  $blogArray = array();
  while ($row = $result->fetch_row()) {
    $blogArray[] = $row;
  }


  //==== ECHO AS JSON
  echo json_encode($blogArray);
?>

网址如下所示:

http://www.mysite.com/blog/?date=2013-05-14

所有这一切的问题是没有正确选择URL参数,但我不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

的Javascript

var date = '2013-05-14';

$.ajax({         
    type: "GET",                             
    url: 'blog/assets/php/load-blog.php',
    dataType: 'json',
    data: { date: date }
    success: function(data){
     alert(data);
    }
});

PHP

<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);


//==== GET URL PARAMETER
$urlParam =  $_GET["date"];

//==== PREPARED STATEMENT
$stmt = $con->prepare("SELECT id,name FROM __TABLE_NAME__ WHERE date = ?");
$stmt->bind_param("s", $urlParam );
$stmt->execute();
$stmt->bind_result($id, $name);

//==== CREATE ARRAY
$blogArray = array();

//==== FETCH DATA   
while ($stmt->fetch()) {
    $blogArray[] = array(
    'id' => $id,
    'name' => $name
    );
}

//==== CLOSE STATEMENT
$stmt->close();

//==== ECHO AS JSON
echo json_encode($blogArray);
?>