我编写了一个工作正常的代码,但现在我希望它在一个函数中,以便在url上调用它。如果你们能提供帮助,我将非常感激。
这是我的代码。
$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
}
function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
if($result = mysqli_query($conn,$sql)){
while($row = mysqli_fetch_assoc($result)){
echo $row['user_uname']."<br />";
}
}
}
我在网址上称它为 http://localhost/test/index.php/day
请告诉我我做错了什么。我在网址上错误地称它为错误吗?
答案 0 :(得分:0)
在这种情况下,您必须打破网址以获取index.php
之后的最后一个参数,在您的情况下为day
。代表此参数创建不同的代码块并根据传递的参数执行它们。
答案 1 :(得分:0)
你不能在核心php中调用这样的函数
你必须这样打电话:
第一种方式:
http://localhost/test/index.php
$conn = mysqli_connect("localhost","root","","testing");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
} else {
day($conn);
}
第二种方式:
http://localhost/test/index.php?day=yes
$conn = mysqli_connect("localhost","root","","testing");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
} else {
echo "connection successfull";
}
if($_GET['day']) {
day($conn);
}
声明功能:
function day($conn){
}
====================================
<强> test.php的强>
class Test
{
const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "";
const DB = "testing";
public function processApi(){
$func = strtolower(trim(str_replace("/","",$_REQUEST['func'])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
echo "Method not exist";
}
private function get_data() {
$conn = mysqli_connect("localhost","root","","testing");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
} else {
//replace your query here
$sql = "SELECT * FROM tbl_employee";
if($result = mysqli_query($conn,$sql)){
while($row = mysqli_fetch_assoc($result)){
echo $row['name']."<br />";
}
}
}
}
}
$test = new Test;
$test->processApi();
?>
在.htaccess文件中定义路由
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ test.php?func=$1 [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ test.php [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ test.php [QSA,NC,L]
</IfModule>
您可以运行以下示例:
http://localhost/core_route/get_data
答案 2 :(得分:0)
call_user_func($_GET['function']);
并使用网址http://localhost/test/index.php?function=day
通过这种方式,您可以执行通过GET参数传递的任何函数。
答案 3 :(得分:-1)
你必须告诉PHP,你正在使用另一个范围的$conn
。
http://php.net/manual/en/language.variables.scope.php
只需在功能标签内使用global $conn
。
$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
echo "Unable to connect".mysqli_connect_error();
}
function day(){
global $conn;
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
if($result = mysqli_query($conn,$sql)){
while($row = mysqli_fetch_assoc($result)){
echo $row['user_uname']."<br />";
}
}
}