我无法在函数内部获取数组,但我可以在函数外部执行此操作。当我在函数外部取出它并将其回显时,它打印出1,但在函数内部,使用相同的获取数组代码并将其回显,它回显为null。我可以告诉因为---符号回声,但数字1没有。我很困惑,因为如果它在函数之外工作,相同的代码应该在函数内部工作,对吧?除非我做错了什么?请帮忙。谢谢。
<?php
include('connect.php');
include('username.php');
//include('functionGet.php');
$boo = $_GET['boo'];
echo "$boo";
function getData($select,$from,$where,$equals){
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "---$fetch---";
}
if($boo = 'yes'){
$acceptedChallenges =
getData("acceptedChallenges","userLogin","username",$username);
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "$acceptedChallenges$username$fetch";
//mysql_query("UPDATE userLogin SET openChallenges = '0' WHERE username =
'$username'");
//mysql_query("UPDATE userLogin SET acceptedChallenges =
'$acceptedChallenges' WHERE username = '$username'");
}
else{
}
?>
答案 0 :(得分:1)
您在查询中使用$username
,但您的功能中没有此类变量:
function getData($select,$from,$where,$equals){
$fetch = mysql_fetch_array(mysql_query("SELECT acceptedChallenges FROM
userLogin WHERE username = '$username'"));
$fetch = $fetch['acceptedChallenges'];
echo "---$fetch---";
}
关于评论中的讨论,这里有一个演示变量范围的剪辑:
$username = "Testing";
function test1() {
echo $username; // Will emit Notice, since $username is undefined
}
function test2() {
global $username;
echo $username; // Will work, but this is bad practice
}
function test3($username) {
echo $username; // This is the proper way to do it
}
test1();
test2();
test3($username);
你可以玩它here。
答案 1 :(得分:1)
您正在传递$where
而非$username
,因此请更改
function getData($select,$from,$where,$equals){
到
function getData($select,$from,$username,$equals){
答案 2 :(得分:0)
这段代码非常糟糕:
我建议:
在get()函数内部使用预准备语句传递数据并防止注入
private databse;
function __construct($database) {
$this->databse=$databse;
}
function get($user) {
$sql='SELECT acceptedChallenges FROM userLogin WHERE username = :user';
$this->database->prepare($sql)
$this->database->bindParam(":user",$user,'PDO::INT_VALUE);
$this->database->execute();
if ($user=$this->databse->fetch()) {
return $user;
}
return false;
}
<?php
$database=new PDO(...);
$challengeObject=new ChallengeObject($database);
$user=$challengeObject->get($_POST['boo']);
if ($user!=false) {
echo "Authenticated successfull";
}