2016-12-05 22 views
-2

我得到這個錯誤第12行下面的PHP代碼我試圖將數據插入到一個表,如果它成功,警報後重定向到另一個頁面。開捕致命錯誤:類mysqli_result的對象不能轉換爲字符串上線12

<?php 
session_start(); 
include 'dbconn.php'; 
$name = $_POST["name"]; 
$hof = $_POST["hof"]; 
$tier = $_POST["tier"]; 
$services = $_POST["services"]; 
$proced = $_POST["proced"]; 
$addr = $_POST["addr"]; 
$phone = $_POST["phone"]; 
$depname = $_SESSION['depname']; 
$qry = "INSERT INTO '.$depname.'(name,hof,tier,services,method,address,phone) VALUES ('$name','$hof','$tier','$services','$proced','$addr','$phone')"; //This is where the problem is; 
if(mysqli_query($conn,$qry) === TRUE) { 
echo "<script type='text/javascript'>alert('Success'); 
window.location='welcome.php'; 
</script>"; 
} 
else{ 
echo "<script type='text/javascript'>alert('Error'); 
window.location='welcome.php'; 
</script>"; 
} 
?> 
+3

強制性警告:你的代碼非常容易受到攻擊。使用準備好的SQL語句。 – Carcigenicate

+1

由於您使用的PHP爲什麼不使用'header()'來執行重定向? –

+0

'var_dump($ _ SESSION ['depname']);'輸出? – bassxzero

回答

1

除了別人說的話,這應該可以解決您的錯誤。您仍然會遇到需要修復的安全問題。

另外,我不使用的mysqli我用PDO,所以你必須原諒我,如果語法是稍有不當。

您的問題是mysqli_query()不返回行。您需要將需要從你的結果讀取行,然後將其分配給$_SESSION['depname']

的login.php應該是這樣的

// Note we are using prepared statements to prevent SQL injections 
// Also note the use of backticks `, which are used for identifiers 
$mysqli = new mysqli('host', 'user', 'password', 'database'); 
$stmt = $mysqli->prepare('SELECT `id`,`depname` FROM `admin` WHERE `username` = ? and password = ?'); 
$stmt->bind_param('ss', $myusername, $mypassword); 
$stmt->execute(); 
$result = $stmt->get_result(); 
if($result->num_rows == 1) { 
    session_start(); 
    $row = $result->fetch_assoc(); 
    $_SESSION['depname'] = $row['depname']; 
    header("location: welcome.php"); 
    exit; 
} 

其他腳本

<?php 
session_start(); 
include 'dbconn.php'; 
$name = $_POST["name"]; 
$hof = $_POST["hof"]; 
$tier = $_POST["tier"]; 
$services = $_POST["services"]; 
$proced = $_POST["proced"]; 
$addr = $_POST["addr"]; 
$phone = $_POST["phone"]; 
$depname = $_SESSION['depname']; 

$qry = "INSERT INTO `{$depname}` (`name`,`hof`,`tier`,`services`,`method`,`address`,`phone`) VALUES (?,?,?,?,?,?,?)"; 

// prepare our query to prevent sql injections 
$stmt = $mysqli->prepare($qry); 
$stmt->bind_param('sssssss', $name, $hof, $tier, $services, $proced, $addr, $phone); 
$stmt->execute(); 

// not sure why you aren't using header here like @JayBlanchard said, but whatever 
if($stmt->affected_rows == 1) { 
    echo "<script type='text/javascript'>alert('Success'); 
window.location='welcome.php'; 
</script>"; 
} 
else 
{ 
echo "<script type='text/javascript'>alert('Error'); 
window.location='welcome.php'; 
</script>"; 
} 
+0

非常感謝支持。嘗試使用頭來代替window.location ='welcome.php',但警報功能不起作用,頁面在發生之前被重定向。 – chrisjzach

相關問題