可捕获的致命错误:类mysqli_result的对象无法在第12行转换为字符串

时间:2016-12-05 17:15:02

标签: php mysqli xampp

我在第12行的以下php代码中收到此错误。我尝试将数据插入表中,如果成功,请在警报后重定向到另一个页面。

<?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>";
}
?>

1 个答案:

答案 0 :(得分: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>";
}