我已经查看了我试图做的其他结果,他们都没有按照我的需要去做。我想做的是这样的事情:
myfunction(){
require('./connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='$user'"); //user is defined outside the function but it works in my login function which i use the same way.
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = row['value'];
mysql_close();
return $value;
} else {
$errmsg = "connection failed.";
$value = 0;
return $value;
}
}
在我的php文件中,我会在顶部做这样的事情。
$value = myfunction();
这不起作用。 最终,我想要完成的是从数据库中获取值并将其从该函数输出到另一个文件中。 (这是我在stackoverflow上的第一篇文章,所以如果我需要改变这个,请随时告诉我,我会)
答案 0 :(得分:1)
您的代码有几个语法错误。检查一下,阅读我的评论:
function myfunction() {
//connect to database
require('./connect.php');
//user is defined outside the function but it works in my login function which i use the same way.
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($user) . "'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
return $row['value']; //Missing $ sign
//No need to create $value if you just return with that.
//mysql_close();
//return $value;
} else {
//Where do you use this errmsg????
$errmsg = "connection failed.";
return 0;
// These 2 lines are unnecessary.
//$value = 0;
//return $value;
}
} //Missing function close
在我的示例中,我只是保留了mysql函数,但请不要使用它们,它们已被弃用。请改用mysqli或PDO。另外,通过转义变量来避免sql注入!
答案 1 :(得分:0)
$row = mysql_fetch_assoc($query);
$value = row['value']; // <-------- you forgot the $
并且很可能,提取结果的正确方法是,
$row[0]['value'];
Please, don't use
mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 2 :(得分:-1)
require('./connect.php');
还有一点功能改进
myfunction(){
require_once('../connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='".$user."'"); //user is defined outside the function but it works in my login function which i use the
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = $row['value'];
mysql_close();
}
else{
$errmsg = "connection failed.";
$value = 0;
}
return $value;
}