使用会话变量在SQL中创建查询

时间:2014-09-05 16:26:30

标签: php sql wamp

所以即时通过简单的登录和用户区域的用户区域创建此站点。

我尝试执行SQL行但显示错误。

这是我的checklogin.php页面,其中我设置了会话变量。

    // Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.
<?php
session_start();
$tbl_name= "members";
$con=mysqli_connect("localhost","root","","bst_planner");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($con,$sql)or die(mysqli_error($con));

// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"

    $_SESSION['myusername'] = $myusername;
    $_SESSION['mypassword'] = $mypassword;
    $row = mysql_fetch_object( $result);
    $_SESSION["userID"] = $row->id;  
    header("location:login_success.php");
}
else {
    echo "Wrong Username or Password";
}

echo $myusername;?>

<html>
<body>

</body>
</html>

这是出现的错误消息:

这是我在user_area.php中的两个代码

<?php 
session_start(); 
$tbl_members= "members";
$tbl_directorio= "subject_directorio";
$con=mysqli_connect("localhost","root","","bst_planner");

if(isset($_SESSION['myusername'])){
    echo "You're logged in";
}
else {
    header("location:index.php");
}
?>

和这个

    <?php 
$userID = $_SESSION["userID"];

$sql="SELECT * FROM $tbl_directorio WHERE Teacher_id='$userID'";
$result=mysqli_query($con,$sql)or die(mysql_error());

// Mysql_num_row is counting table row
$count=mysqli_num_rows($result);

if($count>=1){

echo "Your current planners";

}
else {
    echo "You haven't created a planner yet";
} 
                ?> 
  

捕获致命错误:第69行的C:\ wamp \ www \ user_area.php中无法将类mysqli_result的对象转换为字符串

这是第69行

$sql="SELECT * FROM $tbl_directorio WHERE Teacher_id='$userID'";

我非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:2)

问题是变量$userID是mysqli_result类的对象。这是因为在checklogin.php中,您将对象写入$_SESSION["userID"],稍后在user_area.php中将该对象写入$userID。 要解决此问题,您可以更改行:$row = mysql_fetch_object( $result); $_SESSION["userID"] = $row->id;
$row = mysqli_fetch_assoc($result); $_SESSION["userID"] = $row['id']; 这样您就可以选择它作为数组,只将数字写入变量$userID而不是对象。我希望这会有所帮助。