2014-09-05 80 views
1

所以即時通訊使用簡單的登錄和用戶區域來創建此網站。使用會話變量在SQL中創建查詢

我試圖執行一個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"; 
} 
       ?> 

Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\wamp\www\user_area.php on line 69

這是69行

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

我真的很感謝您提供的任何幫助。

+0

'session_start();'loaded?另外,將'或者死(mysql_error())'改爲'或死(mysqli_error($ con))'''$ con'是你的數據庫連接變量。你不能混合使用MySQL API。 – 2014-09-05 16:27:30

+2

您還需要向我們展示更多代碼。你發佈的代碼和錯誤消息一樣,沒有人能夠給你一個明確的答案。投票結束爲*「這個問題是由於無法再生產的問題引起的......」* – 2014-09-05 16:34:37

+0

對於缺乏信息感到抱歉。我現在已經添加了更多的PHP代碼。 – fmonper1 2014-09-05 22:41:46

回答

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代替的對象。我希望這有幫助。